1 | extern crate downcast; |
2 | use downcast::{downcast, downcast_sync, Any, AnySync}; |
3 | use std::sync::Arc; |
4 | |
5 | trait Simple: Any {} |
6 | downcast!(dyn Simple); |
7 | |
8 | trait WithParams<T, U>: Any {} |
9 | downcast!(<T, U> dyn WithParams<T, U>); |
10 | struct Param1; |
11 | struct Param2; |
12 | |
13 | struct ImplA { |
14 | data: String |
15 | } |
16 | impl Simple for ImplA {} |
17 | impl WithParams<Param1, Param2> for ImplA {} |
18 | |
19 | struct ImplB; |
20 | impl Simple for ImplB {} |
21 | impl WithParams<Param1, Param2> for ImplB {} |
22 | |
23 | #[test] |
24 | fn simple(){ |
25 | let mut a: Box<dyn Simple> = Box::new(ImplA{ data: "data" .into() }); |
26 | |
27 | assert_eq!(a.downcast_ref::<ImplA>().unwrap().data, "data" ); |
28 | assert!(a.downcast_ref::<ImplB>().is_err()); |
29 | |
30 | assert_eq!(a.downcast_mut::<ImplA>().unwrap().data, "data" ); |
31 | assert!(a.downcast_mut::<ImplB>().is_err()); |
32 | |
33 | assert_eq!(a.downcast::<ImplA>().unwrap().data, "data" ); |
34 | } |
35 | |
36 | #[test] |
37 | fn with_params(){ |
38 | let mut a: Box<dyn WithParams<Param1, Param2>> = Box::new(ImplA{ data: "data" .into() }); |
39 | |
40 | assert_eq!(a.downcast_ref::<ImplA>().unwrap().data, "data" ); |
41 | assert!(a.downcast_ref::<ImplB>().is_err()); |
42 | |
43 | assert_eq!(a.downcast_mut::<ImplA>().unwrap().data, "data" ); |
44 | assert!(a.downcast_mut::<ImplB>().is_err()); |
45 | |
46 | assert_eq!(a.downcast::<ImplA>().unwrap().data, "data" ); |
47 | } |
48 | |
49 | trait SimpleSync: AnySync {} |
50 | downcast_sync!(dyn SimpleSync); |
51 | |
52 | impl SimpleSync for ImplA {} |
53 | impl SimpleSync for ImplB {} |
54 | |
55 | #[test] |
56 | fn simple_sync(){ |
57 | let a: Arc<dyn SimpleSync> = Arc::new(ImplA{ data: "data" .into() }); |
58 | |
59 | assert_eq!(a.downcast_ref::<ImplA>().unwrap().data, "data" ); |
60 | assert!(a.downcast_ref::<ImplB>().is_err()); |
61 | |
62 | assert_eq!(a.downcast_arc::<ImplA>().unwrap().data, "data" ); |
63 | } |
64 | |
65 | trait WithParamsSync<T, U>: AnySync {} |
66 | downcast_sync!(<T, U> dyn WithParamsSync<T, U>); |
67 | impl WithParamsSync<Param1, Param2> for ImplA {} |
68 | impl WithParamsSync<Param1, Param2> for ImplB {} |
69 | |
70 | #[test] |
71 | fn with_params_sync() { |
72 | let a: Arc<dyn WithParamsSync<Param1, Param2>> = Arc::new(ImplA{ data: "data" .into() }); |
73 | |
74 | assert_eq!(a.downcast_ref::<ImplA>().unwrap().data, "data" ); |
75 | assert!(a.downcast_ref::<ImplB>().is_err()); |
76 | |
77 | assert_eq!(a.downcast_arc::<ImplA>().unwrap().data, "data" ); |
78 | } |
79 | |