Skip to main content

ic_db/ulid/
mod.rs

1//! Canonical ULID value, adapted from IcyDB's schema-owned atom.
2//! Generation, clocks and entropy are separate write-policy responsibilities.
3use std::{fmt, str::FromStr};
4
5mod generator;
6pub use generator::{UlidGenerationError, UlidGenerator};
7
8/// A 128-bit ULID with exact 16-byte storage and canonical uppercase text.
9///
10/// This value has no automatic generator or randomness requirement. Construct
11/// supplied identifiers with [`Self::from_bytes`], [`Self::from_u128`] or parsing.
12#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
13pub struct Ulid([u8; 16]);
14
15impl Ulid {
16    /// Minimum (nil) identifier.
17    pub const MIN: Self = Self([0; 16]);
18    /// Maximum identifier; all 128 bits are valid data.
19    pub const MAX: Self = Self([255; 16]);
20    /// Construct from exactly 16 bytes, timestamp prefix first.
21    #[must_use]
22    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
23        Self(bytes)
24    }
25
26    /// Construct from the unsigned big-endian integer representation.
27    #[must_use]
28    pub const fn from_u128(value: u128) -> Self {
29        Self(value.to_be_bytes())
30    }
31
32    /// Return the exact 16-byte representation.
33    #[must_use]
34    pub const fn to_bytes(self) -> [u8; 16] {
35        self.0
36    }
37}
38
39/// Text was not an exact canonical uppercase 26-character ULID.
40#[derive(Clone, Copy, Debug, Eq, PartialEq)]
41pub struct UlidParseError;
42
43impl fmt::Display for UlidParseError {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.write_str("expected a canonical uppercase 26-character ULID")
46    }
47}
48impl std::error::Error for UlidParseError {}
49impl fmt::Display for Ulid {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
52    }
53}
54impl fmt::Debug for Ulid {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        fmt::Debug::fmt(&self.to_string(), f)
57    }
58}
59impl FromStr for Ulid {
60    type Err = UlidParseError;
61    fn from_str(text: &str) -> Result<Self, Self::Err> {
62        let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
63        if value.to_string() != text {
64            return Err(UlidParseError);
65        }
66        Ok(Self::from_bytes(value.to_bytes()))
67    }
68}