1use serde::{Deserialize, Deserializer, Serialize, Serializer};
4
5use crate::error::Error;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub struct Uuid(uuid::Uuid);
10
11impl Uuid {
12 pub const fn new() -> Self {
14 Self(uuid::Uuid::nil())
15 }
16
17 pub const fn from_inner(uuid: uuid::Uuid) -> Self {
19 Self(uuid)
20 }
21
22 pub const fn into_inner(self) -> uuid::Uuid {
24 self.0
25 }
26}
27
28impl Default for Uuid {
29 fn default() -> Self {
30 Self::new()
31 }
32}
33
34impl TryFrom<&str> for Uuid {
35 type Error = Error;
36
37 fn try_from(val: &str) -> Result<Self, Self::Error> {
38 uuid::Uuid::parse_str(val).map(Self).map_err(Error::from)
39 }
40}
41
42impl TryFrom<String> for Uuid {
43 type Error = Error;
44
45 fn try_from(val: String) -> Result<Self, Self::Error> {
46 Self::try_from(val.as_str())
47 }
48}
49
50impl From<Uuid> for String {
51 fn from(val: Uuid) -> Self {
52 Self::from(&val)
53 }
54}
55
56impl From<&Uuid> for String {
57 fn from(val: &Uuid) -> Self {
58 val.0
59 .hyphenated()
60 .encode_lower(&mut uuid::Uuid::encode_buffer())
61 .to_string()
62 }
63}
64
65impl Serialize for Uuid {
66 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
67 where
68 S: Serializer,
69 {
70 uuid::fmt::Hyphenated::from_uuid(self.0).serialize(s)
71 }
72}
73
74impl<'de> Deserialize<'de> for Uuid {
75 fn deserialize<D>(d: D) -> Result<Self, D::Error>
76 where
77 D: Deserializer<'de>,
78 {
79 use serde::de::Error as _;
80
81 String::deserialize(d)
82 .as_deref()
83 .map_err(|err| D::Error::custom(format!("missing UUID string: {err}")))
84 .and_then(|u| {
85 uuid::Uuid::parse_str(u)
86 .map(Self)
87 .map_err(|err| D::Error::custom(format!("error parsing UUID: {err}")))
88 })
89 }
90}
91
92impl std::fmt::Display for Uuid {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 write!(f, "{}", String::from(self))
95 }
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101
102 #[test]
103 fn test_uuid() {
104 let uuid_str = "936da01f-9abd-4d9d-80c7-02af85c822a8";
105 let uuid_json = serde_json::to_string(&uuid_str).unwrap();
106 let inner_uuid = uuid::Uuid::parse_str(uuid_str).unwrap();
107 let uuid = Uuid::from_inner(inner_uuid);
108
109 assert_eq!(Uuid::try_from(uuid_str), Ok(uuid));
110 assert_eq!(Uuid::try_from(uuid_str.to_string()), Ok(uuid));
111
112 assert_eq!(uuid.into_inner(), inner_uuid);
113 assert_eq!(format!("{uuid}").as_str(), uuid_str);
114
115 assert_eq!(serde_json::to_string(&uuid).unwrap(), uuid_json);
116 assert_eq!(serde_json::from_str::<Uuid>(&uuid_json).unwrap(), uuid);
117 }
118}