1use std::{fmt, str::FromStr};
4
5#[cfg(target_arch = "wasm32")]
6mod canister;
7mod generator;
8#[cfg_attr(
9 all(not(target_arch = "wasm32"), not(test)),
10 expect(
11 dead_code,
12 reason = "only the IC issuance API and native stream tests own a process-local generator"
13 )
14)]
15mod pseudo;
16#[cfg(test)]
17mod tests;
18pub use generator::{UlidGenerationError, UlidGenerator};
19pub use pseudo::SeededUlidGenerator;
20
21#[derive(Debug, Clone, Copy, Eq, PartialEq)]
23pub enum UlidEntropyError {
24 Unavailable,
26 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#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
46pub struct Ulid([u8; 16]);
47
48impl Ulid {
49 pub const MIN: Self = Self([0; 16]);
51 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 #[must_use]
62 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
63 Self(bytes)
64 }
65
66 #[must_use]
68 pub const fn from_u128(value: u128) -> Self {
69 Self(value.to_be_bytes())
70 }
71
72 #[must_use]
74 pub const fn to_bytes(self) -> [u8; 16] {
75 self.0
76 }
77}
78
79#[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}