rsdiff_core/id/
traits.rs

1/*
2    Appellation: traits <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5use core::borrow::Borrow;
6
7/// An `Identifier` is a type that can be used as an identifier
8pub trait Identifier: ToString {
9    private!();
10}
11
12/// The `Id` trait describes the behavior of a type that can be used as an id.
13/// An `Id` is almost identical to an `Identifier`, but it is a trait that can be implemented for any type.
14///
15pub trait Id<K>
16where
17    K: Identifier,
18{
19    type Q: Borrow<K>;
20
21    fn from_id(id: Self::Q) -> Self;
22
23    fn get(&self) -> &Self::Q;
24}
25
26pub trait Identifiable: Identify {
27    fn get_id(&self) -> &Self::Id;
28}
29
30pub trait IdentifierExt: Identifier
31where
32    Self: Copy + Eq + Ord + core::hash::Hash,
33{
34}
35
36pub trait HashId: Identifier
37where
38    Self: Eq + core::hash::Hash,
39{
40}
41
42pub trait IntoId {
43    type Id: Identifier;
44
45    fn into_id(self) -> Self::Id;
46}
47
48pub trait Identify {
49    type Id: Identifier;
50
51    fn id(&self) -> &Self::Id;
52}
53
54pub trait IdentifyMut: Identify {
55    fn id_mut(&mut self) -> &mut Self::Id;
56}
57
58/*
59 *********** impls ***********
60*/
61impl<K, Q> Id<K> for Q
62where
63    K: Identifier,
64    Q: Borrow<K>,
65{
66    type Q = Q;
67
68    fn from_id(id: Self::Q) -> Self {
69        id
70    }
71
72    fn get(&self) -> &Self::Q {
73        self
74    }
75}
76
77impl<S> Identify for S
78where
79    S: Identifier,
80{
81    type Id = S;
82
83    fn id(&self) -> &Self::Id {
84        self
85    }
86}
87
88impl<Id> HashId for Id where Id: Eq + Identifier + core::hash::Hash {}
89
90impl<Id> IdentifierExt for Id where Id: Copy + Eq + Identifier + Ord + core::hash::Hash {}
91
92macro_rules! identifier {
93    ($($t:ty),*) => {
94        $(
95            identifier!(@impl $t);
96        )*
97    };
98    (@impl $t:ty) => {
99        impl Identifier for $t {
100            seal!();
101        }
102    };
103}
104
105identifier!(
106    f32, f64, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
107);
108identifier!(bool, char, &str, String);