abs_data/models/typed/
datakey.rs

1use crate::{config::Config, error_code::ErrorCode};
2use std::fmt::{self, Display, Formatter};
3
4use crate::result::Result;
5
6#[derive(Debug)]
7pub struct DataKey {
8    inner: Box<str>,
9}
10
11impl DataKey {
12    pub fn parse(str: &str) -> Result<Self> {
13        Self::try_from(str)
14    }
15
16    pub fn no_filter() -> Self {
17        Self {
18            inner: "all".into(),
19        }
20    }
21}
22
23impl PartialEq for DataKey {
24    fn eq(&self, other: &Self) -> bool {
25        self.inner == other.inner
26    }
27    fn ne(&self, other: &Self) -> bool {
28        self.inner != other.inner
29    }
30}
31
32impl TryFrom<&str> for DataKey {
33    type Error = ErrorCode;
34
35    fn try_from(str: &str) -> Result<Self> {
36        let dot_count = str.matches('.').count();
37
38        if dot_count != Config::DATA_KEY_REQUIRED_DOT_COUNT {
39            return Err(ErrorCode::DataKeyLengthIncorrect(str.len()));
40        }
41
42        let key = Self { inner: str.into() };
43
44        let byte_len = format!("{}", key).len();
45
46        if byte_len > Config::DATA_KEY_MAX_LENGTH {
47            return Err(ErrorCode::DataKeyLengthIncorrect(byte_len));
48        };
49
50        Ok(key)
51    }
52}
53
54impl Display for DataKey {
55    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
56        write!(f, "{}", self.inner)
57    }
58}
59
60impl AsRef<str> for DataKey {
61    fn as_ref(&self) -> &str {
62        &self.inner
63    }
64}
65
66impl Default for DataKey {
67    fn default() -> Self {
68        Self::no_filter()
69    }
70}