1extern crate downcast;
2use downcast::{downcast, downcast_sync, Any, AnySync};
3use std::sync::Arc;
4
5trait Simple: Any {}
6downcast!(dyn Simple);
7
8trait WithParams<T, U>: Any {}
9downcast!(<T, U> dyn WithParams<T, U>);
10struct Param1;
11struct Param2;
12
13struct ImplA {
14 data: String
15}
16impl Simple for ImplA {}
17impl WithParams<Param1, Param2> for ImplA {}
18
19struct ImplB;
20impl Simple for ImplB {}
21impl WithParams<Param1, Param2> for ImplB {}
22
23#[test]
24fn 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]
37fn 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
49trait SimpleSync: AnySync {}
50downcast_sync!(dyn SimpleSync);
51
52impl SimpleSync for ImplA {}
53impl SimpleSync for ImplB {}
54
55#[test]
56fn 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
65trait WithParamsSync<T, U>: AnySync {}
66downcast_sync!(<T, U> dyn WithParamsSync<T, U>);
67impl WithParamsSync<Param1, Param2> for ImplA {}
68impl WithParamsSync<Param1, Param2> for ImplB {}
69
70#[test]
71fn 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