react/__private/
auto_wrap_rc.rs

1pub mod __impl {
2    use std::rc::Rc;
3
4    pub trait CheckIsRc {
5        type Output;
6        fn check_is_rc(&self) -> Self::Output;
7    }
8
9    pub struct IsRc;
10
11    impl IsRc {
12        #[inline]
13        pub fn auto_wrap_rc<T>(self, v: Rc<T>) -> Rc<T> {
14            v
15        }
16    }
17
18    pub struct NotRc;
19
20    impl NotRc {
21        #[inline]
22        pub fn auto_wrap_rc<T>(self, v: T) -> Rc<T> {
23            Rc::new(v)
24        }
25    }
26
27    impl<T: ?Sized> CheckIsRc for Rc<T> {
28        type Output = IsRc;
29
30        #[inline]
31        fn check_is_rc(&self) -> Self::Output {
32            IsRc
33        }
34    }
35
36    impl<T> CheckIsRc for &T {
37        type Output = NotRc;
38
39        fn check_is_rc(&self) -> Self::Output {
40            NotRc
41        }
42    }
43}
44
45#[macro_export]
46macro_rules! auto_wrap_rc {
47    ($e:expr) => {{
48        use $crate::__private::auto_wrap_rc::__impl::CheckIsRc;
49        match $e {
50            ref v => v.check_is_rc().auto_wrap_rc($e),
51        }
52    }};
53}
54
55#[cfg(test)]
56mod tests {
57    use std::rc::Rc;
58
59    #[test]
60    fn auto_wrap_rc() {
61        let a = crate::auto_wrap_rc!(1);
62        let _: Rc<i32> = a;
63
64        let b = crate::auto_wrap_rc!(Rc::new(true));
65        let _: Rc<bool> = b;
66
67        let c = String::new();
68        let c = crate::auto_wrap_rc!(c);
69        let _: Rc<String> = c;
70
71        let d = Rc::new(String::new());
72        let d = crate::auto_wrap_rc!(d);
73        let _: Rc<String> = d;
74    }
75
76    #[test]
77    fn nested() {
78        let a = crate::auto_wrap_rc!(crate::auto_wrap_rc!(String::new()));
79        let _: Rc<String> = a;
80    }
81}