Skip to main content

hanzo_protocol/
thread_id.rs

1use std::fmt::Display;
2
3use schemars::JsonSchema;
4use schemars::r#gen::SchemaGenerator;
5use schemars::schema::Schema;
6use serde::Deserialize;
7use serde::Serialize;
8use ts_rs::TS;
9use uuid::Uuid;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, TS, Hash)]
12#[ts(type = "string")]
13pub struct ThreadId {
14    uuid: Uuid,
15}
16
17impl ThreadId {
18    pub fn new() -> Self {
19        Self {
20            uuid: Uuid::now_v7(),
21        }
22    }
23
24    pub fn from_string(s: &str) -> Result<Self, uuid::Error> {
25        Ok(Self {
26            uuid: Uuid::parse_str(s)?,
27        })
28    }
29}
30
31impl TryFrom<&str> for ThreadId {
32    type Error = uuid::Error;
33
34    fn try_from(value: &str) -> Result<Self, Self::Error> {
35        Self::from_string(value)
36    }
37}
38
39impl TryFrom<String> for ThreadId {
40    type Error = uuid::Error;
41
42    fn try_from(value: String) -> Result<Self, Self::Error> {
43        Self::from_string(value.as_str())
44    }
45}
46
47impl From<ThreadId> for String {
48    fn from(value: ThreadId) -> Self {
49        value.to_string()
50    }
51}
52
53impl From<ThreadId> for Uuid {
54    fn from(value: ThreadId) -> Self {
55        value.uuid
56    }
57}
58
59impl Default for ThreadId {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl Display for ThreadId {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        Display::fmt(&self.uuid, f)
68    }
69}
70
71impl Serialize for ThreadId {
72    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
73    where
74        S: serde::Serializer,
75    {
76        serializer.collect_str(&self.uuid)
77    }
78}
79
80impl<'de> Deserialize<'de> for ThreadId {
81    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
82    where
83        D: serde::Deserializer<'de>,
84    {
85        let value = String::deserialize(deserializer)?;
86        let uuid = Uuid::parse_str(&value).map_err(serde::de::Error::custom)?;
87        Ok(Self { uuid })
88    }
89}
90
91impl JsonSchema for ThreadId {
92    fn schema_name() -> String {
93        "ThreadId".to_string()
94    }
95
96    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
97        <String>::json_schema(generator)
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    #[test]
105    fn test_thread_id_default_is_not_zeroes() {
106        let id = ThreadId::default();
107        assert_ne!(id.uuid, Uuid::nil());
108    }
109}