1#[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#[derive(Debug, Clone, Copy, Eq, PartialEq)]
24pub enum UlidEntropyError {
25 Unavailable,
27 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#[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 pub const MIN: Self = Self([0; 16]);
74 pub const MAX: Self = Self([255; 16]);
76 const MILLIS_END: i64 = 1 << ::ulid::Ulid::TIME_BITS;
77
78 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 #[must_use]
101 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
102 Self(bytes)
103 }
104
105 #[must_use]
107 pub const fn from_u128(value: u128) -> Self {
108 Self(value.to_be_bytes())
109 }
110
111 #[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 #[must_use]
121 pub const fn to_bytes(self) -> [u8; 16] {
122 self.0
123 }
124}
125
126#[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}