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