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;
7mod generator;
8#[cfg(not(target_arch = "wasm32"))]
9mod native;
10mod pseudo;
11#[cfg(test)]
12mod tests;
13#[cfg(target_arch = "wasm32")]
14use canister as platform;
15#[cfg(not(target_arch = "wasm32"))]
16use native as platform;
17
18pub use generator::{UlidGenerationError, UlidGenerator};
19pub use pseudo::SeededUlidGenerator;
20
21/// Failure to obtain fresh entropy for a ULID.
22#[derive(Debug, Clone, Copy, Eq, PartialEq)]
23pub enum UlidEntropyError {
24    /// The native entropy source failed or the IC management call produced no successful reply.
25    Unavailable,
26    /// The management protocol frame was invalid.
27    InvalidFrame,
28}
29
30impl fmt::Display for UlidEntropyError {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        f.write_str(match self {
33            Self::Unavailable => "ULID entropy unavailable",
34            Self::InvalidFrame => "invalid ULID entropy frame",
35        })
36    }
37}
38
39impl std::error::Error for UlidEntropyError {}
40
41/// A 128-bit ULID with exact 16-byte storage and canonical uppercase text.
42///
43/// Use [`Self::generate_prand`] for synchronous issuance on the IC or a native host.
44/// Construct supplied identifiers with [`Self::from_bytes`], [`Self::from_u128`] or parsing.
45#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
46pub struct Ulid([u8; 16]);
47
48impl Ulid {
49    /// Minimum (nil) identifier.
50    pub const MIN: Self = Self([0; 16]);
51    /// Maximum identifier; all 128 bits are valid data.
52    pub const MAX: Self = Self([255; 16]);
53    fn from_millis_and_suffix(millis: u64, suffix: [u8; 10]) -> Self {
54        let mut bytes = [0; 16];
55        bytes[..6].copy_from_slice(&millis.to_be_bytes()[2..]);
56        bytes[6..].copy_from_slice(&suffix);
57        Self(bytes)
58    }
59
60    /// Construct from exactly 16 bytes, timestamp prefix first.
61    #[must_use]
62    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
63        Self(bytes)
64    }
65
66    /// Construct from the unsigned big-endian integer representation.
67    #[must_use]
68    pub const fn from_u128(value: u128) -> Self {
69        Self(value.to_be_bytes())
70    }
71
72    /// Return the exact 16-byte representation.
73    #[must_use]
74    pub const fn to_bytes(self) -> [u8; 16] {
75        self.0
76    }
77}
78
79/// Text was not an exact canonical uppercase 26-character ULID.
80#[derive(Clone, Copy, Debug, Eq, PartialEq)]
81pub struct UlidParseError;
82
83impl fmt::Display for UlidParseError {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.write_str("expected a canonical uppercase 26-character ULID")
86    }
87}
88impl std::error::Error for UlidParseError {}
89impl fmt::Display for Ulid {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
92    }
93}
94impl fmt::Debug for Ulid {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        fmt::Debug::fmt(&self.to_string(), f)
97    }
98}
99impl FromStr for Ulid {
100    type Err = UlidParseError;
101    fn from_str(text: &str) -> Result<Self, Self::Err> {
102        let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
103        if value.to_string() != text {
104            return Err(UlidParseError);
105        }
106        Ok(Self::from_bytes(value.to_bytes()))
107    }
108}