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.
3
4#[cfg(target_arch = "wasm32")]
5mod canister;
6mod generator;
7#[cfg(not(target_arch = "wasm32"))]
8mod native;
9mod pseudo;
10#[cfg(test)]
11mod tests;
12
13#[cfg(target_arch = "wasm32")]
14use canister as platform;
15#[cfg(not(target_arch = "wasm32"))]
16use native as platform;
17use std::{fmt, str::FromStr};
18
19pub use generator::{UlidGenerationError, UlidGenerator};
20pub use pseudo::{SeededUlidGenerator, insert_ulid};
21
22/// Failure to obtain fresh entropy for a ULID.
23#[derive(Debug, Clone, Copy, Eq, PartialEq)]
24pub enum UlidEntropyError {
25    /// The native entropy source failed or the IC management call produced no successful reply.
26    Unavailable,
27    /// The management protocol frame was invalid.
28    InvalidFrame,
29}
30
31impl fmt::Display for UlidEntropyError {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.write_str(match self {
34            Self::Unavailable => "ULID entropy unavailable",
35            Self::InvalidFrame => "invalid ULID entropy frame",
36        })
37    }
38}
39
40impl std::error::Error for UlidEntropyError {}
41
42/// A 128-bit ULID with exact 16-byte storage and canonical uppercase text.
43///
44/// Use [`Self::generate_prand`] for synchronous issuance on the IC or a native host.
45/// Construct supplied identifiers with [`Self::from_bytes`], [`Self::from_u128`] or parsing.
46#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
47pub struct Ulid([u8; 16]);
48
49impl serde::Serialize for Ulid {
50    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
51        if serializer.is_human_readable() {
52            serializer.collect_str(self)
53        } else {
54            self.0.serialize(serializer)
55        }
56    }
57}
58
59impl<'de> serde::Deserialize<'de> for Ulid {
60    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
61        if deserializer.is_human_readable() {
62            String::deserialize(deserializer)?
63                .parse()
64                .map_err(serde::de::Error::custom)
65        } else {
66            <[u8; 16]>::deserialize(deserializer).map(Self::from_bytes)
67        }
68    }
69}
70
71impl Ulid {
72    /// Minimum (nil) identifier.
73    pub const MIN: Self = Self([0; 16]);
74    /// Maximum identifier; all 128 bits are valid data.
75    pub const MAX: Self = Self([255; 16]);
76    const MILLIS_END: i64 = 1 << ::ulid::Ulid::TIME_BITS;
77
78    // Every suffix belongs to the encoded millisecond. Inclusive key bounds
79    // can represent the last tick through Ulid::MAX without wrapping.
80    pub(crate) fn time_bounds(range: std::ops::Range<crate::Timestamp>) -> Option<(Self, Self)> {
81        let start = range.start.as_millis().max(0);
82        let end = range.end.as_millis().min(Self::MILLIS_END);
83        (start < end).then(|| {
84            (
85                Self::from_millis_and_suffix(start as u64, [0; 10]),
86                Self::from_millis_and_suffix((end - 1) as u64, [255; 10]),
87            )
88        })
89    }
90
91    fn from_millis_and_suffix(millis: u64, suffix: [u8; 10]) -> Self {
92        let mut bytes = [0; 16];
93        bytes[..6].copy_from_slice(&millis.to_be_bytes()[2..]);
94        bytes[6..].copy_from_slice(&suffix);
95
96        Self(bytes)
97    }
98
99    /// Construct from exactly 16 bytes, timestamp prefix first.
100    #[must_use]
101    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
102        Self(bytes)
103    }
104
105    /// Construct from the unsigned big-endian integer representation.
106    #[must_use]
107    pub const fn from_u128(value: u128) -> Self {
108        Self(value.to_be_bytes())
109    }
110
111    /// Read the logical Unix timestamp embedded in the first 48 bits.
112    /// A monotonic generator can retain the preceding timestamp when its clock moves backward.
113    #[must_use]
114    pub const fn timestamp(self) -> crate::Timestamp {
115        let millis = ::ulid::Ulid::from_bytes(self.0).timestamp_ms();
116        crate::Timestamp::from_millis(millis as i64)
117    }
118
119    /// Return the exact 16-byte representation.
120    #[must_use]
121    pub const fn to_bytes(self) -> [u8; 16] {
122        self.0
123    }
124}
125
126/// Text was not an exact canonical uppercase 26-character ULID.
127#[derive(Clone, Copy, Debug, Eq, PartialEq)]
128pub struct UlidParseError;
129
130impl fmt::Display for UlidParseError {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        f.write_str("expected a canonical uppercase 26-character ULID")
133    }
134}
135impl std::error::Error for UlidParseError {}
136impl fmt::Display for Ulid {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
139    }
140}
141impl fmt::Debug for Ulid {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        fmt::Debug::fmt(&self.to_string(), f)
144    }
145}
146impl FromStr for Ulid {
147    type Err = UlidParseError;
148    fn from_str(text: &str) -> Result<Self, Self::Err> {
149        let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
150        if value.to_string() != text {
151            return Err(UlidParseError);
152        }
153
154        Ok(Self::from_bytes(value.to_bytes()))
155    }
156}