1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//! ## dyncast
//!
//! [![github]](https://github.com/cynecx/dyncast) [![crates-io]](https://crates.io/crates/dyncast)
//!
//! [github]: https://img.shields.io/badge/github-cynecx/dyncast-blue?logo=github
//! [crates-io]: https://img.shields.io/crates/v/dyncast.svg?logo=rust
//!
//! **Fair warning**: This crate is a **proof of concept**. The soundness of this crate has **not** been validated. **Use at your own risk**.
//!
//! This library provides opt-in type downcasting to `dyn Trait`s.
//!
//! The entrypoint for this library is the [`dyncast`] proc-macro, which should be applied on every `trait` and `impl`, you'd want to enable downcasting to. The proc-macro will additionally implement [`Dyncast`] for the selected trait (`dyn Trait`), which can be used to check whether a concrete type implements such trait.
//!
//! ### Example
//!
//! ```rust
//! use std::any::Any;
//!
//! use dyncast::{dyncast, DyncastExt};
//!
//! #[dyncast]
//! trait Foo {
//! fn bar(&self);
//! }
//!
//! #[dyncast]
//! impl Foo for () {
//! fn bar(&self) {
//! println!("a")
//! }
//! }
//!
//! #[test]
//! fn boba() {
//! let a = &() as &dyn Any;
//! assert!(a.dyncast_to::<dyn Foo>().is_some());
//! }
//! ```
use Any;
/// [This](`dyncast`) proc-macro can be used on trait definitions and trait impls.
///
/// ```
/// use dyncast::dyncast;
///
/// #[dyncast]
/// trait Foo {}
///
/// #[dyncast]
/// impl Foo for () {}
///
/// # fn main() {}
/// ```
///
/// [`dyncast`] also supports traits with generics. However, this is limited type parameters.
///
/// ```
/// use dyncast::dyncast;
///
/// #[dyncast]
/// trait Foo<T: 'static> {}
///
/// #[dyncast]
/// impl Foo<String> for () {}
///
/// # fn main() {}
/// ```
pub use dyncast;
/// Provides a shorthand method [`dyncast_to`](`DyncastExt::dyncast_to`).
///
/// ```
/// use dyncast::{dyncast, DyncastExt};
///
/// #[dyncast]
/// trait Bar {}
///
/// fn foo(val: &dyn std::any::Any) {
/// assert!(val.dyncast_to::<dyn Bar>().is_none());
/// }
///
/// # fn main() {}
/// ```