Skip to main content

stoat/
ulid.rs

1use std::{ops::Deref, time::SystemTime};
2
3use crate::{Error, Identifiable, Result};
4
5/// Wrapper around a ULID string, the ID format used for Stoat models.
6pub struct Ulid(String);
7
8impl Ulid {
9    /// Verifies the input is a valid ULID and creates an instance of [`Ulid`].
10    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    /// Creates an instance of [`Ulid`] **_without verifying it is valid_**.
19    ///
20    /// Do not use this function unless you already know the input is valid.
21    pub fn from_string_unchecked(id: String) -> Self {
22        Self(id)
23    }
24
25    /// Returns the stored timestamp of when the ID was created.
26    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}