uuid_like/lib.rs
1use std::{
2 fmt::{Debug, Display},
3 hash::Hash,
4};
5
6use uuid::Version;
7
8mod wrapper;
9
10#[doc(hidden)]
11pub use uuid::Uuid;
12
13/// Common methods for UUID-like types.
14///
15/// Feel free to use [`wrapper!`] to generate a UUID wrapper implementing this
16/// trait.
17pub trait UuidLike:
18 Clone + Copy + Debug + Display + PartialEq + Eq + PartialOrd + Ord + Hash + Send + Sync + 'static
19{
20 /// Generates a new random UUID-like value.
21 fn random() -> Self;
22
23 /// Returns the UUID-like value represented by the given bytes.
24 ///
25 /// See [`Uuid::from_bytes()`].
26 fn from_bytes(bytes: [u8; 16]) -> Self;
27
28 /// Returns the UUID-like value represented by the given 128-bit value.
29 ///
30 /// See [`Uuid::from_u128()`].
31 #[inline]
32 fn from_u128(value: u128) -> Self {
33 let bytes = value.to_be_bytes();
34 Self::from_bytes(bytes)
35 }
36
37 /// Returns the UUID-like value represented by the given pair of 64-bit values.
38 ///
39 /// See [`Uuid::from_u64_pair()`].
40 #[inline]
41 fn from_u64_pair(high: u64, low: u64) -> Self {
42 let value = ((high as u128) << 64) | (low as u128);
43 Self::from_u128(value)
44 }
45
46 /// Returns `true` if the UUID-like value is the nil UUID.
47 ///
48 /// See [`Uuid::is_nil()`].
49 #[inline]
50 fn is_nil(&self) -> bool {
51 self.as_u128() == 0
52 }
53
54 /// Returns the UUID version number of the UUID-like value.
55 ///
56 /// See [`Uuid::get_version_num()`].
57 #[inline]
58 fn get_version_num(&self) -> usize {
59 (self.as_bytes()[6] >> 4) as usize
60 }
61
62 /// Returns the UUID version of the UUID-like value.
63 ///
64 /// See [`Uuid::get_version()`].
65 #[inline]
66 fn get_version(&self) -> Option<Version> {
67 match self.get_version_num() {
68 0 if self.is_nil() => Some(Version::Nil),
69 1 => Some(Version::Mac),
70 2 => Some(Version::Dce),
71 3 => Some(Version::Md5),
72 4 => Some(Version::Random),
73 5 => Some(Version::Sha1),
74 6 => Some(Version::SortMac),
75 7 => Some(Version::SortRand),
76 8 => Some(Version::Custom),
77 0xff => Some(Version::Max),
78 _ => None,
79 }
80 }
81
82 /// Returns the bytes representing the UUID-like value.
83 ///
84 /// See [`Uuid::as_bytes()`].
85 fn as_bytes(&self) -> &[u8; 16];
86
87 /// Returns a 128-bit value representing the UUID-like value.
88 ///
89 /// See [`Uuid::as_u128()`].
90 #[inline]
91 fn as_u128(&self) -> u128 {
92 let bytes = self.as_bytes();
93 u128::from_be_bytes(*bytes)
94 }
95
96 /// Returns a pair of 64-bit values representing the UUID-like value.
97 ///
98 /// See [`Uuid::as_u64_pair()`].
99 #[inline]
100 fn as_u64_pair(&self) -> (u64, u64) {
101 let value = self.as_u128();
102 ((value >> 64) as u64, value as u64)
103 }
104
105 /// Returns the bytes representing the UUID-like value, consuming the value.
106 ///
107 /// See [`Uuid::into_bytes()`].
108 fn into_bytes(self) -> [u8; 16];
109}