vertigo/computed/
to_computed.rs

1use super::Computed;
2
3/// A trait allowing converting the type into computed.
4///
5/// ```rust
6/// use vertigo::{ToComputed, transaction};
7///
8/// let comp_1 = 5.to_computed();
9/// let comp_2 = 'x'.to_computed();
10/// let comp_3 = false.to_computed();
11///
12/// transaction(|context| {
13///     assert_eq!(comp_1.get(context), 5);
14///     assert_eq!(comp_2.get(context), 'x');
15///     assert_eq!(comp_3.get(context), false);
16/// });
17///
18/// ```
19pub trait ToComputed<T: Clone> {
20    fn to_computed(&self) -> Computed<T>;
21}
22
23impl<T: Clone + 'static> ToComputed<T> for Computed<T> {
24    fn to_computed(&self) -> Computed<T> {
25        self.clone()
26    }
27}
28
29impl<T: Clone + 'static> ToComputed<T> for &Computed<T> {
30    fn to_computed(&self) -> Computed<T> {
31        (*self).clone()
32    }
33}
34
35macro_rules! impl_to_computed {
36    ($typename: ty) => {
37        impl ToComputed<$typename> for $typename {
38            fn to_computed(&self) -> Computed<$typename> {
39                let value = *self;
40                Computed::from(move |_| value)
41            }
42        }
43    };
44}
45
46impl_to_computed!(i8);
47impl_to_computed!(i16);
48impl_to_computed!(i32);
49impl_to_computed!(i64);
50impl_to_computed!(i128);
51impl_to_computed!(isize);
52
53impl_to_computed!(u8);
54impl_to_computed!(u16);
55impl_to_computed!(u32);
56impl_to_computed!(u64);
57impl_to_computed!(u128);
58impl_to_computed!(usize);
59
60impl_to_computed!(f32);
61impl_to_computed!(f64);
62
63impl_to_computed!(char);
64
65impl_to_computed!(bool);
66
67impl_to_computed!(());