psyche_core/
id.rs

1use serde::{Deserialize, Serialize};
2use std::cmp::Ordering;
3use std::fmt;
4use std::hash::{Hash, Hasher};
5use std::marker::PhantomData;
6use uuid::Uuid;
7
8/// Universal Identifier (uuidv4).
9#[derive(Clone, Serialize, Deserialize)]
10#[repr(C)]
11pub struct ID<T> {
12    id: Uuid,
13    #[serde(skip_serializing, skip_deserializing)]
14    _phantom: PhantomData<T>,
15}
16
17impl<T> ID<T> {
18    /// Creates new identifier.
19    #[inline]
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    /// Creates new identifier from raw bytes.
25    #[inline]
26    pub fn from_bytes(bytes: [u8; 16]) -> Self {
27        Self {
28            id: Uuid::from_bytes(bytes),
29            _phantom: PhantomData,
30        }
31    }
32
33    /// Gets underlying UUID object.
34    #[inline]
35    pub fn uuid(&self) -> Uuid {
36        self.id
37    }
38}
39
40impl<T> Default for ID<T> {
41    #[inline]
42    fn default() -> Self {
43        Self {
44            id: Uuid::new_v4(),
45            _phantom: PhantomData,
46        }
47    }
48}
49
50impl<T> fmt::Debug for ID<T> {
51    #[inline]
52    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53        write!(f, "{}", self.to_string())
54    }
55}
56
57impl<T> ToString for ID<T> {
58    #[inline]
59    fn to_string(&self) -> String {
60        format!("ID({})", self.id)
61    }
62}
63
64impl<T> Hash for ID<T> {
65    #[inline]
66    fn hash<H>(&self, state: &mut H)
67    where
68        H: Hasher,
69    {
70        self.id.hash(state)
71    }
72}
73
74impl<T> PartialEq for ID<T> {
75    #[inline]
76    fn eq(&self, other: &Self) -> bool {
77        self.id == other.id
78    }
79}
80
81impl<T> Eq for ID<T> {}
82impl<T> Copy for ID<T> where T: Clone {}
83
84impl<T> PartialOrd for ID<T> {
85    #[inline]
86    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
87        Some(self.id.cmp(&other.id))
88    }
89}
90
91impl<T> Ord for ID<T> {
92    #[inline]
93    fn cmp(&self, other: &Self) -> Ordering {
94        self.id.cmp(&other.id)
95    }
96}