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;
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    fn from_millis_and_suffix(millis: u64, suffix: [u8; 10]) -> Self {
77        let mut bytes = [0; 16];
78        bytes[..6].copy_from_slice(&millis.to_be_bytes()[2..]);
79        bytes[6..].copy_from_slice(&suffix);
80
81        Self(bytes)
82    }
83
84    /// Construct from exactly 16 bytes, timestamp prefix first.
85    #[must_use]
86    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
87        Self(bytes)
88    }
89
90    /// Construct from the unsigned big-endian integer representation.
91    #[must_use]
92    pub const fn from_u128(value: u128) -> Self {
93        Self(value.to_be_bytes())
94    }
95
96    /// Return the exact 16-byte representation.
97    #[must_use]
98    pub const fn to_bytes(self) -> [u8; 16] {
99        self.0
100    }
101}
102
103/// Text was not an exact canonical uppercase 26-character ULID.
104#[derive(Clone, Copy, Debug, Eq, PartialEq)]
105pub struct UlidParseError;
106
107impl fmt::Display for UlidParseError {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        f.write_str("expected a canonical uppercase 26-character ULID")
110    }
111}
112impl std::error::Error for UlidParseError {}
113impl fmt::Display for Ulid {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
116    }
117}
118impl fmt::Debug for Ulid {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        fmt::Debug::fmt(&self.to_string(), f)
121    }
122}
123impl FromStr for Ulid {
124    type Err = UlidParseError;
125    fn from_str(text: &str) -> Result<Self, Self::Err> {
126        let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
127        if value.to_string() != text {
128            return Err(UlidParseError);
129        }
130
131        Ok(Self::from_bytes(value.to_bytes()))
132    }
133}