egml_core/model/base/
id.rs

1use crate::Error;
2use sha2::{Digest, Sha256};
3use std::fmt;
4use uuid::Uuid;
5
6#[derive(Debug, Clone, PartialEq, Eq, Hash)]
7pub struct Id(String);
8
9impl Id {
10    pub fn from_hashed_string(val: &str) -> Self {
11        let mut sha256 = Sha256::new();
12        sha256.update(val);
13        let hash: String = format!("{:X}", sha256.finalize());
14        Self(hash)
15    }
16
17    pub fn from_hashed_u64(val: u64) -> Self {
18        let mut sha256 = Sha256::new();
19        sha256.update(val.to_le_bytes());
20        let hash: String = format!("{:X}", sha256.finalize());
21        Self(hash)
22    }
23
24    pub fn generate_uuid_v4() -> Self {
25        let uuid: String = Uuid::new_v4().into();
26        Self(uuid)
27    }
28}
29
30impl From<Id> for String {
31    fn from(item: Id) -> Self {
32        item.0
33    }
34}
35
36impl TryFrom<&String> for Id {
37    type Error = Error;
38
39    fn try_from(item: &String) -> Result<Self, Self::Error> {
40        if item.is_empty() {
41            Err(Error::MustNotBeEmpty("id"))
42        } else {
43            Ok(Self(item.to_string()))
44        }
45    }
46}
47
48impl TryFrom<&str> for Id {
49    type Error = Error;
50
51    fn try_from(item: &str) -> Result<Self, Self::Error> {
52        if item.is_empty() {
53            Err(Error::MustNotBeEmpty("id"))
54        } else {
55            Ok(Self(item.to_string()))
56        }
57    }
58}
59
60impl TryFrom<String> for Id {
61    type Error = Error;
62
63    fn try_from(item: String) -> Result<Self, Self::Error> {
64        if item.is_empty() {
65            Err(Error::MustNotBeEmpty("id"))
66        } else {
67            Ok(Self(item))
68        }
69    }
70}
71
72/*impl From<String> for Id {
73    fn from(item: String) -> Self {
74        Self(item)
75    }
76}*/
77
78impl fmt::Display for Id {
79    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
80        write!(f, "{}", self.0)
81    }
82}