Skip to main content

ahri_tre_protocol/
ids.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3use uuid::Uuid;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
6#[serde(try_from = "String", into = "String")]
7pub struct RequestId(Uuid);
8
9impl RequestId {
10    pub fn new() -> Self {
11        Self(Uuid::new_v4())
12    }
13
14    pub const fn from_uuid(uuid: Uuid) -> Self {
15        Self(uuid)
16    }
17
18    pub const fn as_uuid(self) -> Uuid {
19        self.0
20    }
21}
22
23impl Default for RequestId {
24    fn default() -> Self {
25        Self::new()
26    }
27}
28
29impl fmt::Display for RequestId {
30    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31        self.0.hyphenated().fmt(formatter)
32    }
33}
34
35impl TryFrom<String> for RequestId {
36    type Error = uuid::Error;
37
38    fn try_from(value: String) -> Result<Self, Self::Error> {
39        Uuid::parse_str(&value).map(Self)
40    }
41}
42
43impl From<RequestId> for String {
44    fn from(value: RequestId) -> Self {
45        value.to_string()
46    }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
50#[serde(try_from = "String", into = "String")]
51pub struct PublicUuid(Uuid);
52
53impl PublicUuid {
54    pub const fn from_uuid(uuid: Uuid) -> Self {
55        Self(uuid)
56    }
57
58    pub const fn as_uuid(self) -> Uuid {
59        self.0
60    }
61}
62
63impl fmt::Display for PublicUuid {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        self.0.hyphenated().fmt(formatter)
66    }
67}
68
69impl TryFrom<String> for PublicUuid {
70    type Error = uuid::Error;
71
72    fn try_from(value: String) -> Result<Self, Self::Error> {
73        Uuid::parse_str(&value).map(Self)
74    }
75}
76
77impl From<PublicUuid> for String {
78    fn from(value: PublicUuid) -> Self {
79        value.to_string()
80    }
81}
82
83#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
84#[serde(try_from = "String", into = "String")]
85pub struct PublicName(String);
86
87impl PublicName {
88    pub fn new(value: impl Into<String>) -> Result<Self, String> {
89        let value = value.into();
90        let trimmed = value.trim();
91        if trimmed.is_empty() {
92            return Err("public name must not be empty".to_string());
93        }
94        Ok(Self(trimmed.to_string()))
95    }
96
97    pub fn as_str(&self) -> &str {
98        &self.0
99    }
100}
101
102impl TryFrom<String> for PublicName {
103    type Error = String;
104
105    fn try_from(value: String) -> Result<Self, Self::Error> {
106        Self::new(value)
107    }
108}
109
110impl From<PublicName> for String {
111    fn from(value: PublicName) -> Self {
112        value.0
113    }
114}