Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make DowncastSync Optional #22

Merged
merged 1 commit into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ keywords = ["downcast", "any", "trait", "associated", "no_std"]
license = "MIT/Apache-2.0"

[features]
default = ["std"]
default = ["std", "sync"]
std = []
sync = []
15 changes: 11 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
//!
//! Since 1.2.0, the minimum supported Rust version is 1.36 due to needing stable access to alloc.
//!
//! ```
#![cfg_attr(feature = "sync", doc = "```")]
#![cfg_attr(not(feature = "sync"), doc = "```ignore")]
//! # #[macro_use]
//! # extern crate downcast_rs;
//! # use downcast_rs::{Downcast, DowncastSync};
Expand Down Expand Up @@ -72,7 +73,8 @@
//!
//! # Example without generics
//!
//! ```
#![cfg_attr(feature = "sync", doc = "```")]
#![cfg_attr(not(feature = "sync"), doc = "```ignore")]
//! # use std::rc::Rc;
//! # use std::sync::Arc;
//! // Import macro via `macro_use` pre-1.30.
Expand Down Expand Up @@ -168,7 +170,10 @@ pub extern crate std as __std;
pub extern crate alloc as __alloc;

use __std::any::Any;
use __alloc::{boxed::Box, rc::Rc, sync::Arc};
use __alloc::{boxed::Box, rc::Rc};

#[cfg(feature = "sync")]
use __alloc::sync::Arc;

/// Supports conversion to `Any`. Traits to be extended by `impl_downcast!` must extend `Downcast`.
pub trait Downcast: Any {
Expand All @@ -193,13 +198,15 @@ impl<T: Any> Downcast for T {
fn as_any_mut(&mut self) -> &mut dyn Any { self }
}

#[cfg(feature = "sync")]
/// Extends `Downcast` to support `Sync` traits that thus support `Arc` downcasting as well.
pub trait DowncastSync: Downcast + Send + Sync {
/// Convert `Arc<Trait>` (where `Trait: Downcast`) to `Arc<Any>`. `Arc<Any>` can then be
/// further `downcast` into `Arc<ConcreteType>` where `ConcreteType` implements `Trait`.
fn into_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
}

#[cfg(feature = "sync")]
impl<T: Any + Send + Sync> DowncastSync for T {
fn into_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> { self }
}
Expand Down Expand Up @@ -420,7 +427,7 @@ macro_rules! impl_downcast {
}


#[cfg(test)]
#[cfg(all(test, feature = "sync"))]
mod test {
macro_rules! test_mod {
(
Expand Down
Loading