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 serde::Serialize for Ulid {
49    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
50        if serializer.is_human_readable() {
51            serializer.collect_str(self)
52        } else {
53            self.0.serialize(serializer)
54        }
55    }
56}
57
58impl<'de> serde::Deserialize<'de> for Ulid {
59    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
60        if deserializer.is_human_readable() {
61            String::deserialize(deserializer)?
62                .parse()
63                .map_err(serde::de::Error::custom)
64        } else {
65            <[u8; 16]>::deserialize(deserializer).map(Self::from_bytes)
66        }
67    }
68}
69
70impl Ulid {
71    /// Minimum (nil) identifier.
72    pub const MIN: Self = Self([0; 16]);
73    /// Maximum identifier; all 128 bits are valid data.
74    pub const MAX: Self = Self([255; 16]);
75    fn from_millis_and_suffix(millis: u64, suffix: [u8; 10]) -> Self {
76        let mut bytes = [0; 16];
77        bytes[..6].copy_from_slice(&millis.to_be_bytes()[2..]);
78        bytes[6..].copy_from_slice(&suffix);
79        Self(bytes)
80    }
81
82    /// Construct from exactly 16 bytes, timestamp prefix first.
83    #[must_use]
84    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
85        Self(bytes)
86    }
87
88    /// Construct from the unsigned big-endian integer representation.
89    #[must_use]
90    pub const fn from_u128(value: u128) -> Self {
91        Self(value.to_be_bytes())
92    }
93
94    /// Return the exact 16-byte representation.
95    #[must_use]
96    pub const fn to_bytes(self) -> [u8; 16] {
97        self.0
98    }
99}
100
101/// Text was not an exact canonical uppercase 26-character ULID.
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub struct UlidParseError;
104
105impl fmt::Display for UlidParseError {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.write_str("expected a canonical uppercase 26-character ULID")
108    }
109}
110impl std::error::Error for UlidParseError {}
111impl fmt::Display for Ulid {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
114    }
115}
116impl fmt::Debug for Ulid {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        fmt::Debug::fmt(&self.to_string(), f)
119    }
120}
121impl FromStr for Ulid {
122    type Err = UlidParseError;
123    fn from_str(text: &str) -> Result<Self, Self::Err> {
124        let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
125        if value.to_string() != text {
126            return Err(UlidParseError);
127        }
128        Ok(Self::from_bytes(value.to_bytes()))
129    }
130}