use std::{fmt, str::FromStr};
#[cfg(target_arch = "wasm32")]
mod canister;
#[cfg(target_arch = "wasm32")]
pub use canister::UlidEntropyError;
#[cfg(target_arch = "wasm32")]
pub use pseudo::SeededUlidGenerator;
mod generator;
#[cfg(any(target_arch = "wasm32", test))]
mod pseudo;
#[cfg(test)]
mod tests;
pub use generator::{UlidGenerationError, UlidGenerator};
#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Ulid([u8; 16]);
impl Ulid {
pub const MIN: Self = Self([0; 16]);
pub const MAX: Self = Self([255; 16]);
fn from_millis_and_suffix(millis: u64, suffix: [u8; 10]) -> Self {
let mut bytes = [0; 16];
bytes[..6].copy_from_slice(&millis.to_be_bytes()[2..]);
bytes[6..].copy_from_slice(&suffix);
Self(bytes)
}
#[must_use]
pub const fn from_bytes(bytes: [u8; 16]) -> Self {
Self(bytes)
}
#[must_use]
pub const fn from_u128(value: u128) -> Self {
Self(value.to_be_bytes())
}
#[must_use]
pub const fn to_bytes(self) -> [u8; 16] {
self.0
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UlidParseError;
impl fmt::Display for UlidParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("expected a canonical uppercase 26-character ULID")
}
}
impl std::error::Error for UlidParseError {}
impl fmt::Display for Ulid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
}
}
impl fmt::Debug for Ulid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.to_string(), f)
}
}
impl FromStr for Ulid {
type Err = UlidParseError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
if value.to_string() != text {
return Err(UlidParseError);
}
Ok(Self::from_bytes(value.to_bytes()))
}
}