1use std::{borrow::Borrow, fmt, str::FromStr};
2
3use uuid::Uuid;
4
5#[derive(Default, Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
8pub struct Id(String);
9
10impl Id {
11 pub const STR_LEN: usize = 32;
12
13 pub fn new() -> Self {
14 Uuid::new_v4().into()
15 }
16
17 pub fn is_valid(&self) -> bool {
18 !self.0.is_empty()
19 }
20
21 pub fn as_str(&self) -> &str {
22 self.0.as_str()
23 }
24}
25
26impl AsRef<String> for Id {
27 fn as_ref(&self) -> &String {
28 &self.0
29 }
30}
31
32impl AsRef<str> for Id {
34 fn as_ref(&self) -> &str {
35 self.0.as_str()
36 }
37}
38
39impl From<String> for Id {
41 fn from(from: String) -> Self {
42 Self(from)
43 }
44}
45
46impl From<&str> for Id {
48 fn from(from: &str) -> Self {
49 from.to_owned().into()
50 }
51}
52
53impl From<Uuid> for Id {
54 fn from(from: Uuid) -> Self {
55 from.as_simple().to_string().into()
56 }
57}
58
59impl From<Id> for String {
60 fn from(from: Id) -> Self {
61 from.0
62 }
63}
64
65impl FromStr for Id {
66 type Err = ();
67 fn from_str(s: &str) -> Result<Id, Self::Err> {
68 Ok(s.into())
69 }
70}
71
72impl Borrow<str> for Id {
73 fn borrow(&self) -> &str {
74 self.as_ref()
75 }
76}
77
78impl fmt::Display for Id {
79 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
80 f.write_str(self.as_ref())
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[ignore]
90 #[test]
91 fn parse_id() {
92 let invalid_id = "foo".parse::<Id>();
93 assert!(invalid_id.is_err());
94 }
95}