dtz_identifier/
execution_id.rs

1use std::fmt::Display;
2
3static PREFIX: &str = "execution-";
4
5#[derive(Debug, Clone, PartialEq)]
6pub struct ExecutionId {
7    pub id: String,
8}
9
10impl Default for ExecutionId {
11    fn default() -> Self {
12        Self {
13            id: crate::generate_internal_id(18),
14        }
15    }
16}
17
18impl Display for ExecutionId {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        f.write_str(&format!("{PREFIX}{}", self.id))
21    }
22}
23
24impl TryFrom<String> for ExecutionId {
25    type Error = String;
26
27    fn try_from(value: String) -> Result<Self, Self::Error> {
28        if let Some(id_str) = value.strip_prefix(PREFIX) {
29            Ok(ExecutionId {
30                id: id_str.to_string(),
31            })
32        } else {
33            Err("invalid format".to_string())
34        }
35    }
36}
37
38impl TryFrom<&str> for ExecutionId {
39    type Error = String;
40
41    fn try_from(value: &str) -> Result<Self, Self::Error> {
42        if let Some(id_str) = value.strip_prefix(PREFIX) {
43            Ok(ExecutionId {
44                id: id_str.to_string(),
45            })
46        } else {
47            Err("invalid format".to_string())
48        }
49    }
50}
51
52impl<'de> serde::Deserialize<'de> for ExecutionId {
53    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
54    where
55        D: serde::Deserializer<'de>,
56    {
57        struct ExecutionIdVisitor;
58
59        impl serde::de::Visitor<'_> for ExecutionIdVisitor {
60            type Value = ExecutionId;
61
62            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
63                formatter.write_str("a string starting with '")?;
64                formatter.write_str(PREFIX)?;
65                formatter.write_str("' followed by a 8-character alphanumeric string")
66            }
67
68            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
69            where
70                E: serde::de::Error,
71            {
72                if let Some(id_str) = value.strip_prefix(PREFIX) {
73                    Ok(ExecutionId {
74                        id: id_str.to_string(),
75                    })
76                } else {
77                    Err(E::custom("invalid format"))
78                }
79            }
80        }
81
82        deserializer.deserialize_str(ExecutionIdVisitor)
83    }
84}
85
86impl serde::Serialize for ExecutionId {
87    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
88    where
89        S: serde::Serializer,
90    {
91        serializer.serialize_str(&self.to_string())
92    }
93}