1use std::{fmt, str::FromStr};
4
5mod generator;
6pub use generator::{UlidGenerationError, UlidGenerator};
7
8#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
13pub struct Ulid([u8; 16]);
14
15impl Ulid {
16 pub const MIN: Self = Self([0; 16]);
18 pub const MAX: Self = Self([255; 16]);
20 #[must_use]
22 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
23 Self(bytes)
24 }
25
26 #[must_use]
28 pub const fn from_u128(value: u128) -> Self {
29 Self(value.to_be_bytes())
30 }
31
32 #[must_use]
34 pub const fn to_bytes(self) -> [u8; 16] {
35 self.0
36 }
37}
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
41pub struct UlidParseError;
42
43impl fmt::Display for UlidParseError {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 f.write_str("expected a canonical uppercase 26-character ULID")
46 }
47}
48impl std::error::Error for UlidParseError {}
49impl fmt::Display for Ulid {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
52 }
53}
54impl fmt::Debug for Ulid {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 fmt::Debug::fmt(&self.to_string(), f)
57 }
58}
59impl FromStr for Ulid {
60 type Err = UlidParseError;
61 fn from_str(text: &str) -> Result<Self, Self::Err> {
62 let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
63 if value.to_string() != text {
64 return Err(UlidParseError);
65 }
66 Ok(Self::from_bytes(value.to_bytes()))
67 }
68}