1use std::{fmt, str::FromStr};
4
5#[cfg(target_arch = "wasm32")]
6mod canister;
7#[cfg(target_arch = "wasm32")]
8pub use canister::UlidEntropyError;
9#[cfg(target_arch = "wasm32")]
10pub use pseudo::SeededUlidGenerator;
11mod generator;
12#[cfg(any(target_arch = "wasm32", test))]
13mod pseudo;
14#[cfg(test)]
15mod tests;
16pub use generator::{UlidGenerationError, UlidGenerator};
17
18#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
23pub struct Ulid([u8; 16]);
24
25impl Ulid {
26 pub const MIN: Self = Self([0; 16]);
28 pub const MAX: Self = Self([255; 16]);
30 fn from_millis_and_suffix(millis: u64, suffix: [u8; 10]) -> Self {
31 let mut bytes = [0; 16];
32 bytes[..6].copy_from_slice(&millis.to_be_bytes()[2..]);
33 bytes[6..].copy_from_slice(&suffix);
34 Self(bytes)
35 }
36
37 #[must_use]
39 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
40 Self(bytes)
41 }
42
43 #[must_use]
45 pub const fn from_u128(value: u128) -> Self {
46 Self(value.to_be_bytes())
47 }
48
49 #[must_use]
51 pub const fn to_bytes(self) -> [u8; 16] {
52 self.0
53 }
54}
55
56#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub struct UlidParseError;
59
60impl fmt::Display for UlidParseError {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 f.write_str("expected a canonical uppercase 26-character ULID")
63 }
64}
65impl std::error::Error for UlidParseError {}
66impl fmt::Display for Ulid {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
69 }
70}
71impl fmt::Debug for Ulid {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 fmt::Debug::fmt(&self.to_string(), f)
74 }
75}
76impl FromStr for Ulid {
77 type Err = UlidParseError;
78 fn from_str(text: &str) -> Result<Self, Self::Err> {
79 let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
80 if value.to_string() != text {
81 return Err(UlidParseError);
82 }
83 Ok(Self::from_bytes(value.to_bytes()))
84 }
85}