1use std::{ops::Deref, time::SystemTime};
2
3use crate::{Error, Identifiable, Result};
4
5pub struct Ulid(String);
7
8impl Ulid {
9 pub fn from_string(id: String) -> Result<Self> {
11 if ulid::Ulid::from_string(&id).is_err() {
12 return Err(Error::MalformedID);
13 };
14
15 Ok(Self(id))
16 }
17
18 pub fn from_string_unchecked(id: String) -> Self {
22 Self(id)
23 }
24
25 pub fn timestamp(&self) -> SystemTime {
27 ulid::Ulid::from_string(&self.0).unwrap().datetime()
28 }
29
30 pub fn as_str(&self) -> &str {
31 &self.0
32 }
33
34 pub fn to_string(self) -> String {
35 self.0
36 }
37}
38
39impl Deref for Ulid {
40 type Target = String;
41
42 fn deref(&self) -> &Self::Target {
43 &self.0
44 }
45}
46
47impl Identifiable for Ulid {
48 fn id(&self) -> &str {
49 &self.0
50 }
51}
52
53impl TryFrom<String> for Ulid {
54 type Error = Error;
55
56 fn try_from(value: String) -> Result<Self> {
57 Ulid::from_string(value)
58 }
59}