dtz_identifier/
object_id.rs

1static PREFIX: &str = "object-";
2
3#[derive(Debug, Clone, PartialEq, Copy)]
4pub struct ObjectId {
5    pub id: uuid::Uuid,
6}
7
8impl Default for ObjectId {
9    fn default() -> Self {
10        Self {
11            id: uuid::Uuid::now_v7(),
12        }
13    }
14}
15
16impl std::fmt::Display for ObjectId {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        f.write_str(&format!("{PREFIX}{}", self.id))
19    }
20}
21
22impl<'de> serde::Deserialize<'de> for ObjectId {
23    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
24    where
25        D: serde::Deserializer<'de>,
26    {
27        struct ObjectIdVisitor;
28
29        impl serde::de::Visitor<'_> for ObjectIdVisitor {
30            type Value = ObjectId;
31
32            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
33                formatter.write_str("a string starting with '")?;
34                formatter.write_str(PREFIX)?;
35                formatter.write_str("' followed by a UUID")
36            }
37
38            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
39            where
40                E: serde::de::Error,
41            {
42                if let Some(uuid_str) = value.strip_prefix(PREFIX) {
43                    let uuid = uuid::Uuid::parse_str(uuid_str).map_err(E::custom)?;
44                    Ok(ObjectId { id: uuid })
45                } else {
46                    Err(E::custom("invalid format"))
47                }
48            }
49        }
50
51        deserializer.deserialize_str(ObjectIdVisitor)
52    }
53}
54
55impl serde::Serialize for ObjectId {
56    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
57    where
58        S: serde::Serializer,
59    {
60        serializer.serialize_str(&self.to_string())
61    }
62}
63
64impl From<uuid::Uuid> for ObjectId {
65    fn from(id: uuid::Uuid) -> Self {
66        ObjectId { id }
67    }
68}
69
70#[test]
71fn test_from() {
72    let uuid = uuid::Uuid::now_v7();
73    let ctx = ObjectId::from(uuid);
74    assert_eq!(ctx.id, uuid);
75}