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