Skip to main content

doppleganger_core/
lib.rs

1use std::{borrow::Cow, collections::HashMap};
2
3pub trait Mirror {
4    type Source;
5    type Dest;
6
7    fn mirror(source: Self::Source) -> Self::Dest;
8}
9
10impl<T> Mirror for Vec<T>
11where
12    T: Mirror,
13{
14    type Source = Vec<T::Source>;
15
16    type Dest = Vec<T::Dest>;
17
18    #[inline]
19    fn mirror(source: Self::Source) -> Self::Dest {
20        source.into_iter().map(<T as Mirror>::mirror).collect()
21    }
22}
23
24impl<T> Mirror for Option<T>
25where
26    T: Mirror,
27{
28    type Source = Option<T::Source>;
29
30    type Dest = Option<T::Dest>;
31
32    #[inline]
33    fn mirror(source: Self::Source) -> Self::Dest {
34        source.map(<T as Mirror>::mirror)
35    }
36}
37
38impl<T, E> Mirror for Result<T, E>
39where
40    T: Mirror,
41    E: Mirror,
42{
43    type Source = Result<T::Source, E::Source>;
44
45    type Dest = Result<T::Dest, E::Dest>;
46
47    #[inline]
48    fn mirror(source: Self::Source) -> Self::Dest {
49        source
50            .map(<T as Mirror>::mirror)
51            .map_err(<E as Mirror>::mirror)
52    }
53}
54
55impl<K, V> Mirror for HashMap<K, V>
56where
57    K: Mirror,
58    V: Mirror,
59    K::Dest: Eq + std::hash::Hash,
60{
61    type Source = HashMap<K::Source, V::Source>;
62
63    type Dest = HashMap<K::Dest, V::Dest>;
64
65    fn mirror(source: Self::Source) -> Self::Dest {
66        source
67            .into_iter()
68            .map(|(k, v)| (<K as Mirror>::mirror(k), <V as Mirror>::mirror(v)))
69            .collect()
70    }
71}
72
73pub trait Primitive: Sized {}
74
75impl<T> Mirror for T
76where
77    T: Primitive,
78{
79    type Source = Self;
80
81    type Dest = Self;
82
83    #[inline]
84    fn mirror(source: Self::Source) -> Self::Dest {
85        source
86    }
87}
88
89impl Primitive for String {}
90impl Primitive for &str {}
91impl<'a> Primitive for Cow<'a, str> {}
92impl Primitive for isize {}
93impl Primitive for i64 {}
94impl Primitive for i32 {}
95impl Primitive for i16 {}
96impl Primitive for i8 {}
97impl Primitive for usize {}
98impl Primitive for u64 {}
99impl Primitive for u32 {}
100impl Primitive for u16 {}
101impl Primitive for u8 {}
102impl Primitive for f64 {}
103impl Primitive for f32 {}
104impl Primitive for bool {}
105
106#[cfg(feature = "chrono")]
107impl Primitive for chrono::DateTime<chrono::Utc> {}
108
109#[cfg(feature = "uuid")]
110impl Primitive for uuid::Uuid {}