Skip to main content

ic_db/ulid/
mod.rs

1//! Canonical ULID value, adapted from IcyDB's schema-owned atom.
2//! Issuers use host-supplied time; the value owns its byte and text formats.
3use std::{fmt, str::FromStr};
4
5#[cfg(target_arch = "wasm32")]
6mod canister;
7#[cfg(target_arch = "wasm32")]
8pub use canister::UlidEntropyError;
9#[cfg(target_arch = "wasm32")]
10pub use pseudo::SeededUlidGenerator;
11mod generator;
12#[cfg(any(target_arch = "wasm32", test))]
13mod pseudo;
14#[cfg(test)]
15mod tests;
16pub use generator::{UlidGenerationError, UlidGenerator};
17
18/// A 128-bit ULID with exact 16-byte storage and canonical uppercase text.
19///
20/// Use `Ulid::generate_prand()` for synchronous canister-local issuance on Wasm. Construct
21/// supplied identifiers with [`Self::from_bytes`], [`Self::from_u128`] or parsing.
22#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
23pub struct Ulid([u8; 16]);
24
25impl Ulid {
26    /// Minimum (nil) identifier.
27    pub const MIN: Self = Self([0; 16]);
28    /// Maximum identifier; all 128 bits are valid data.
29    pub const MAX: Self = Self([255; 16]);
30    fn from_millis_and_suffix(millis: u64, suffix: [u8; 10]) -> Self {
31        let mut bytes = [0; 16];
32        bytes[..6].copy_from_slice(&millis.to_be_bytes()[2..]);
33        bytes[6..].copy_from_slice(&suffix);
34        Self(bytes)
35    }
36
37    /// Construct from exactly 16 bytes, timestamp prefix first.
38    #[must_use]
39    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
40        Self(bytes)
41    }
42
43    /// Construct from the unsigned big-endian integer representation.
44    #[must_use]
45    pub const fn from_u128(value: u128) -> Self {
46        Self(value.to_be_bytes())
47    }
48
49    /// Return the exact 16-byte representation.
50    #[must_use]
51    pub const fn to_bytes(self) -> [u8; 16] {
52        self.0
53    }
54}
55
56/// Text was not an exact canonical uppercase 26-character ULID.
57#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub struct UlidParseError;
59
60impl fmt::Display for UlidParseError {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str("expected a canonical uppercase 26-character ULID")
63    }
64}
65impl std::error::Error for UlidParseError {}
66impl fmt::Display for Ulid {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
69    }
70}
71impl fmt::Debug for Ulid {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        fmt::Debug::fmt(&self.to_string(), f)
74    }
75}
76impl FromStr for Ulid {
77    type Err = UlidParseError;
78    fn from_str(text: &str) -> Result<Self, Self::Err> {
79        let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
80        if value.to_string() != text {
81            return Err(UlidParseError);
82        }
83        Ok(Self::from_bytes(value.to_bytes()))
84    }
85}