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 #[must_use]
27 pub const fn from_u128(value: u128) -> Self {
28 Self(value.to_be_bytes())
29 }
30 #[must_use]
32 pub const fn to_bytes(self) -> [u8; 16] {
33 self.0
34 }
35}
36
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub struct UlidParseError;
40
41impl fmt::Display for UlidParseError {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 f.write_str("expected a canonical uppercase 26-character ULID")
44 }
45}
46impl std::error::Error for UlidParseError {}
47impl fmt::Display for Ulid {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 fmt::Display::fmt(&::ulid::Ulid::from_bytes(self.0), f)
50 }
51}
52impl fmt::Debug for Ulid {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 fmt::Debug::fmt(&self.to_string(), f)
55 }
56}
57impl FromStr for Ulid {
58 type Err = UlidParseError;
59 fn from_str(text: &str) -> Result<Self, Self::Err> {
60 let value = text.parse::<::ulid::Ulid>().map_err(|_| UlidParseError)?;
61 if value.to_string() != text {
62 return Err(UlidParseError);
63 }
64 Ok(Self::from_bytes(value.to_bytes()))
65 }
66}