1use std::str::FromStr;
18
19use hex::FromHex;
20use hex::ToHex;
21use serde_with::DeserializeFromStr;
22use serde_with::SerializeDisplay;
23
24pub type CUIDInner = [u8; 32];
25
26#[derive(
27 Copy, Clone, Hash, PartialEq, Eq, SerializeDisplay, DeserializeFromStr, Default, PartialOrd, Ord,
28)]
29#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
30#[repr(transparent)]
31pub struct CUID(CUIDInner);
32
33impl CUID {
34 pub const fn new(inner: CUIDInner) -> Self {
35 Self(inner)
36 }
37}
38
39impl AsRef<CUIDInner> for CUID {
40 fn as_ref(&self) -> &CUIDInner {
41 &self.0
42 }
43}
44
45impl FromHex for CUID {
46 type Error = <CUIDInner as FromHex>::Error;
47
48 fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
49 CUIDInner::from_hex(hex).map(Self)
50 }
51}
52
53impl ToHex for CUID {
54 fn encode_hex<T: std::iter::FromIterator<char>>(&self) -> T {
55 ToHex::encode_hex(&self.0)
56 }
57
58 fn encode_hex_upper<T: std::iter::FromIterator<char>>(&self) -> T {
59 ToHex::encode_hex_upper(&self.0)
60 }
61}
62
63impl FromStr for CUID {
64 type Err = hex::FromHexError;
65
66 fn from_str(s: &str) -> Result<Self, Self::Err> {
67 FromHex::from_hex(s)
68 }
69}
70
71use std::fmt;
72
73impl fmt::Display for CUID {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.write_str(&self.encode_hex::<String>())
76 }
77}
78
79impl fmt::Debug for CUID {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 f.debug_tuple("CUID").field(&self.to_string()).finish()
82 }
83}