dtz_identifier/
identity_id.rs1use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
2use std::fmt::Display;
3use uuid::Uuid;
4
5static PREFIX: &str = "identity-";
6
7#[derive(Debug, Clone, PartialEq, Copy)]
8pub struct IdentityId {
9 pub id: Uuid,
10}
11
12impl Display for IdentityId {
13 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14 f.write_str(&format!("{PREFIX}{}", self.id))
15 }
16}
17
18impl Default for IdentityId {
19 fn default() -> Self {
20 Self { id: Uuid::now_v7() }
21 }
22}
23
24impl<'de> Deserialize<'de> for IdentityId {
25 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
26 where
27 D: Deserializer<'de>,
28 {
29 struct IdentityIdVisitor;
30
31 impl Visitor<'_> for IdentityIdVisitor {
32 type Value = IdentityId;
33
34 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
35 formatter.write_str("a string starting with 'identity-' 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::parse_str(uuid_str).map_err(E::custom)?;
44 Ok(IdentityId { id: uuid })
45 } else {
46 Err(E::custom("invalid format"))
47 }
48 }
49 }
50
51 deserializer.deserialize_str(IdentityIdVisitor)
52 }
53}
54
55impl Serialize for IdentityId {
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> for IdentityId {
65 fn from(id: Uuid) -> Self {
66 IdentityId { id }
67 }
68}
69
70impl TryFrom<&str> for IdentityId {
71 type Error = String;
72
73 fn try_from(value: &str) -> Result<Self, Self::Error> {
74 if let Some(uuid_str) = value.strip_prefix(PREFIX) {
75 let uuid =
76 uuid::Uuid::parse_str(uuid_str).map_err(|_e| "invalid format".to_string())?;
77 Ok(IdentityId { id: uuid })
78 } else {
79 Err("invalid format".to_string())
80 }
81 }
82}
83
84#[test]
85fn id_tostring() {
86 let id = IdentityId::default();
87 let full_id = format!("{id}");
88 println!("full-id: {full_id}");
89 assert!(full_id.starts_with(PREFIX));
90}