Skip to main content

appletheia_application/event/
event_name_owned.rs

1use std::{fmt, fmt::Display, str::FromStr};
2
3use appletheia_domain::EventName;
4use serde::{Deserialize, Serialize};
5
6use super::EventNameOwnedError;
7
8#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
9#[serde(transparent)]
10pub struct EventNameOwned(String);
11
12impl EventNameOwned {
13    pub fn new(value: String) -> Result<Self, EventNameOwnedError> {
14        Self::validate(&value)?;
15        Ok(Self(value))
16    }
17
18    pub fn value(&self) -> &str {
19        &self.0
20    }
21
22    fn validate(value: &str) -> Result<(), EventNameOwnedError> {
23        if value.is_empty() {
24            return Err(EventNameOwnedError::Empty);
25        }
26        if value.len() > EventName::MAX_LENGTH {
27            return Err(EventNameOwnedError::TooLong);
28        }
29        if !value
30            .as_bytes()
31            .iter()
32            .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
33        {
34            return Err(EventNameOwnedError::InvalidFormat);
35        }
36        Ok(())
37    }
38}
39
40impl Display for EventNameOwned {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        write!(f, "{}", self.value())
43    }
44}
45
46impl FromStr for EventNameOwned {
47    type Err = EventNameOwnedError;
48
49    fn from_str(s: &str) -> Result<Self, Self::Err> {
50        Self::new(s.to_string())
51    }
52}
53
54impl TryFrom<&str> for EventNameOwned {
55    type Error = EventNameOwnedError;
56
57    fn try_from(value: &str) -> Result<Self, Self::Error> {
58        Self::from_str(value)
59    }
60}
61
62impl TryFrom<String> for EventNameOwned {
63    type Error = EventNameOwnedError;
64
65    fn try_from(value: String) -> Result<Self, Self::Error> {
66        Self::new(value)
67    }
68}
69
70impl From<EventName> for EventNameOwned {
71    fn from(value: EventName) -> Self {
72        Self(value.value().to_string())
73    }
74}