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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
///! Rust enums are great for types where all variations are known beforehand. But in
///! the case where you want to implement a container of user-defined types, an
///! open-ended type like a trait object is needed. In some cases, it is useful to
///! cast the trait object back into its original concrete type to access additional
///! functionality and performant inlined implementations.
///! 
///! `downcast-rs` adds basic downcasting support to trait objects, supporting **type
///! parameters and constraints**.
///! 
///! To make a trait downcastable, make it extend the `downcast::Downcast` trait and
///! invoke `impl_downcast!` on it as follows:
///!
///! ```rust
///! # #[macro_use]
///! # extern crate downcast_rs;
///! # use downcast_rs::Downcast;
///! trait Trait: Downcast {}
///! impl_downcast!(Trait);
///!
///! // or
///! 
///! trait TraitGeneric<T>: Downcast {}
///! impl_downcast!(TraitGeneric<T>);
///!
///! // or
///!
///! trait TraitGenericConstrained<T: Copy>: Downcast {}
///! impl_downcast!(TraitGenericConstrained<T> where T: Copy);
///!
///! // or
///!
///! // Use this variant when specifying concrete type parameters.
///! trait TraitGenericConcrete<T: Copy>: Downcast {}
///! impl_downcast!(concrete TraitGenericConcrete<u32>);
///! #
///! # fn main() {}
///! ```
///! 
///! # Example without generics
///!
///! ```rust
///! #[macro_use]
///! extern crate downcast_rs;
///! use downcast_rs::Downcast;
///! 
///! // To create a trait with downcasting methods, extend `Downcast` and run
///! // impl_downcast!() on the trait.
///! trait Base: Downcast {}
///! impl_downcast!(Base);
///! 
///! // Concrete type implementing Base.
///! struct Foo(u32);
///! impl Base for Foo {}
///! 
///! fn main() {
///!     // Create a trait object.
///!     let mut base: Box<Base> = Box::new(Foo(42));
///! 
///!     // Downcast to Foo.
///!     assert_eq!(base.downcast_ref::<Foo>().unwrap().0, 42);
///! }
///! ```
///!
///! # Example with a generic trait
///!
///! ```rust
///! #[macro_use]
///! extern crate downcast_rs;
///! use downcast_rs::Downcast;
///! 
///! // To create a trait with downcasting methods, extend `Downcast` and run
///! // impl_downcast!() on the trait.
///! trait Base<T>: Downcast {}
///! impl_downcast!(Base<T>);
///! 
///! // Concrete type implementing Base.
///! struct Foo(u32);
///! impl Base<u32> for Foo {}
///! 
///! fn main() {
///!     // Create a trait object.
///!     let mut base: Box<Base<u32>> = Box::new(Foo(42));
///! 
///!     // Downcast to Foo.
///!     assert_eq!(base.downcast_ref::<Foo>().unwrap().0, 42);
///! }
///! ```

use std::any::Any;

/// Supports conversion to `Any`. Traits to be extended by `impl_downcast!` must extend `Downcast`.
pub trait Downcast: Any {
    fn as_any(&self) -> &Any;
    fn as_any_mut(&mut self) -> &mut Any;
}

impl<T: Any> Downcast for T {
    fn as_any(&self) -> &Any { self }
    fn as_any_mut(&mut self) -> &mut Any { self }
}

/// Adds downcasting support to traits that extend `downcast::Downcast` by defining forwarding
/// methods to the corresponding implementations on `std::any::Any` in the standard library.
///
/// See https://users.rust-lang.org/t/how-to-create-a-macro-to-impl-a-provided-type-parametrized-trait/5289
/// for why this is implemented this way to support templatized traits.
#[macro_export]
macro_rules! impl_downcast {
    (@$trait_:ident) => {
        impl_downcast! {
            @as_item
            impl $trait_ {
                impl_downcast! { @impl_body @$trait_ [] }
            }
        }
    };

    (@$trait_:ident [$($args:ident,)*]) => {
        /// Implementation for a trait with generic parameters passed.
        /// In its current state, this will not work if the trait requires any constraints on the
        /// type parameters other than `::std::any::Any` and `'static`.
        impl_downcast! {
            @as_item
            impl<$($args),*> $trait_<$($args),*>
                where $( $args: ::std::any::Any + 'static ),*
            {
                impl_downcast! { @impl_body @$trait_ [$($args,)*] }
            }
        }
    };

    (@$trait_:ident [$($args:ident,)*] where [$($preds:tt)+]) => {
        /// Implementation for a trait with generic parameters passed.
        /// In its current state, this will not work if the trait requires any constraints on the
        /// type parameters other than `::std::any::Any` and `'static`.
        impl_downcast! {
            @as_item
            impl<$($args),*> $trait_<$($args),*>
                where $( $args: ::std::any::Any + 'static, )*
                      $($preds)*
            {
                impl_downcast! { @impl_body @$trait_ [$($args,)*] }
            }
        }
    };

    (concrete @$trait_:ident [$($args:ident,)*]) => {
        /// Implementation for a trait with concrete types passed.
        impl_downcast! {
            @as_item
            impl $trait_<$($args),*> {
                impl_downcast! { @impl_body @$trait_ [$($args,)*] }
            }
        }
    };

    (@impl_body @$trait_:ident [$($args:ident,)*]) => {
        /// Returns true if the boxed type is the same as `__T`.
        #[inline]
        pub fn is<__T: $trait_<$($args),*>>(&self) -> bool {
            $crate::Downcast::as_any(self).is::<__T>()
        }
        /// Returns a reference to the boxed value if it is of type `__T`, or
        /// `None` if it isn't.
        #[inline]
        pub fn downcast_ref<__T: $trait_<$($args),*>>(&self) -> Option<&__T> {
            $crate::Downcast::as_any(self).downcast_ref::<__T>()
        }
        /// Returns a mutable reference to the boxed value if it is of type
        /// `__T`, or `None` if it isn't.
        #[inline]
        pub fn downcast_mut<__T: $trait_<$($args),*>>(&mut self) -> Option<&mut __T> {
            $crate::Downcast::as_any_mut(self).downcast_mut::<__T>()
        }
    };

    (@as_item $i:item) => { $i };

    ($trait_:ident <>) => { impl_downcast! { @$trait_ } };
    ($trait_:ident < $($args:ident),* $(,)* >) => { impl_downcast! { @$trait_ [$($args,)*] } };
    ($trait_:ident) => { impl_downcast! { @$trait_ } };
    (concrete $trait_:ident < $($args:ident),* $(,)* >) => {
        impl_downcast! { concrete @$trait_ [$($args,)*] }
    };
    ($trait_:ident < $($args:ident),* $(,)* > where $($preds:tt)+) => {
        impl_downcast! { @$trait_ [$($args,)*] where [$($preds)*] }
    };
}


#[cfg(test)]
mod test {

    mod non_generic {
        use super::super::Downcast;

        // A trait that can be downcast.
        trait Base: Downcast {}
        impl_downcast!(Base);

        // Concrete type implementing Base.
        struct Foo(u32);
        impl Base for Foo {}

        // Functions that can work on references to Base trait objects.
        fn get_val(base: &Box<Base>) -> u32 {
            match base.downcast_ref::<Foo>() {
                Some(val) => val.0,
                None => 0
            }
        }
        fn set_val(base: &mut Box<Base>, val: u32) {
            if let Some(foo) = base.downcast_mut::<Foo>() {
                foo.0 = val;
            }
        }

        #[test]
        fn test() {
            let mut base: Box<Base> = Box::new(Foo(42));
            assert_eq!(get_val(&base), 42);

            set_val(&mut base, 6*9);
            assert_eq!(get_val(&base), 6*9);

            assert!(base.is::<Foo>());
        }
    }

    mod generic {
        use super::super::Downcast;

        // A trait that can be downcast.
        trait Base<T>: Downcast {}
        impl_downcast!(Base<T>);

        // Concrete type implementing Base.
        struct Foo(u32);
        impl Base<u32> for Foo {}

        // Functions that can work on references to Base trait objects.
        fn get_val(base: &Box<Base<u32>>) -> u32 {
            match base.downcast_ref::<Foo>() {
                Some(val) => val.0,
                None => 0
            }
        }
        fn set_val(base: &mut Box<Base<u32>>, val: u32) {
            if let Some(foo) = base.downcast_mut::<Foo>() {
                foo.0 = val;
            }
        }

        #[test]
        fn test() {
            let mut base: Box<Base<u32>> = Box::new(Foo(42));
            assert_eq!(get_val(&base), 42);

            set_val(&mut base, 6*9);
            assert_eq!(get_val(&base), 6*9);

            assert!(base.is::<Foo>());
        }
    }

    mod constrained_generic {
        use super::super::Downcast;

        // A trait that can be downcast.
        trait Base<T: Copy>: Downcast {}
        impl_downcast!(Base<T> where T: Copy);

        // Concrete type implementing Base.
        struct Foo(u32);
        impl Base<u32> for Foo {}

        // Functions that can work on references to Base trait objects.
        fn get_val(base: &Box<Base<u32>>) -> u32 {
            match base.downcast_ref::<Foo>() {
                Some(val) => val.0,
                None => 0
            }
        }
        fn set_val(base: &mut Box<Base<u32>>, val: u32) {
            if let Some(foo) = base.downcast_mut::<Foo>() {
                foo.0 = val;
            }
        }

        #[test]
        fn test() {
            let mut base: Box<Base<u32>> = Box::new(Foo(42));
            assert_eq!(get_val(&base), 42);

            set_val(&mut base, 6*9);
            assert_eq!(get_val(&base), 6*9);

            assert!(base.is::<Foo>());
        }
    }

    mod concrete {
        use super::super::Downcast;

        // A trait that can be downcast.
        trait Base<T>: Downcast {}
        impl_downcast!(concrete Base<u32>);

        // Concrete type implementing Base.
        struct Foo(u32);
        impl Base<u32> for Foo {}

        // Functions that can work on references to Base trait objects.
        fn get_val(base: &Box<Base<u32>>) -> u32 {
            match base.downcast_ref::<Foo>() {
                Some(val) => val.0,
                None => 0
            }
        }
        fn set_val(base: &mut Box<Base<u32>>, val: u32) {
            if let Some(foo) = base.downcast_mut::<Foo>() {
                foo.0 = val;
            }
        }

        #[test]
        fn test() {
            let mut base: Box<Base<u32>> = Box::new(Foo(42));
            assert_eq!(get_val(&base), 42);

            set_val(&mut base, 6*9);
            assert_eq!(get_val(&base), 6*9);

            assert!(base.is::<Foo>());
        }
    }

}