slid/
common_traits.rs

1use crate::Id;
2use std::any::type_name;
3use std::cmp::Ordering;
4use std::fmt::{Debug, Display, Formatter};
5use std::hash::{Hash, Hasher};
6use std::marker::PhantomData;
7
8impl<Label, const SIZE: usize> Debug for Id<Label, SIZE> {
9    /// Formats the `Id` for debugging purposes
10    ///
11    /// ```
12    /// # use slid::Id;
13    /// let id: Id<String> = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255].into();
14    /// assert_eq!(
15    ///     format!("{:?}", id),
16    ///     "Id<alloc::string::String>(000000000000000000000000000000ff)"
17    /// );
18    /// ```
19    ///
20    /// Note: the Debug representation may change in the future
21    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
22        write!(f, "Id<{}>(", type_name::<Label>())?;
23        for byte in self.data {
24            write!(f, "{:02x}", byte)?;
25        }
26        write!(f, ")")?;
27
28        Ok(())
29    }
30}
31
32impl<Label, const SIZE: usize> Display for Id<Label, SIZE> {
33    /// Produces the hex representation of the Id
34    ///
35    /// ```
36    /// # use slid::Id;
37    /// let id: Id<String> = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255].into();
38    /// assert_eq!(
39    ///     format!("{:}", id),
40    ///     "000000000000000000000000000000ff"
41    /// );
42    /// ```
43    ///
44    /// Note: the Display representation may change in the future
45    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
46        for byte in self.data {
47            write!(f, "{:02x}", byte)?;
48        }
49
50        Ok(())
51    }
52}
53
54impl<Label, const SIZE: usize> Hash for Id<Label, SIZE> {
55    fn hash<H: Hasher>(&self, state: &mut H) {
56        self.data.hash(state)
57    }
58}
59
60impl<Label, const SIZE: usize> Copy for Id<Label, SIZE> {}
61
62impl<Label, const SIZE: usize> Clone for Id<Label, SIZE> {
63    fn clone(&self) -> Self {
64        Id {
65            data: self.data,
66            _phantom: PhantomData,
67        }
68    }
69}
70
71impl<Label, const SIZE: usize> Eq for Id<Label, SIZE> {}
72
73impl<Label, const SIZE: usize> PartialEq for Id<Label, SIZE> {
74    fn eq(&self, other: &Self) -> bool {
75        self.data.eq(&other.data)
76    }
77}
78
79#[test]
80fn test_eq() {
81    let a: Id<()> = [0; 16].into();
82    let b: Id<()> = [0; 16].into();
83    let c: Id<()> = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].into();
84
85    assert_eq!(a, b);
86    assert_ne!(a, c);
87}
88
89impl<Label, const SIZE: usize> PartialOrd for Id<Label, SIZE> {
90    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
91        Some(self.data.cmp(&other.data))
92    }
93}
94
95impl<Label, const SIZE: usize> Ord for Id<Label, SIZE> {
96    fn cmp(&self, other: &Self) -> Ordering {
97        self.data.cmp(&other.data)
98    }
99}