use std::fmt;
use std::str::FromStr;
use ulid::Ulid;
use uuid::Uuid;
#[derive(Debug, thiserror::Error)]
#[error("not a ULID: {0}")]
pub struct ParseIdError(#[source] ulid::DecodeError);
macro_rules! ulid_newtype {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct $name(Ulid);
impl $name {
pub fn new() -> Self {
Self(Ulid::generate())
}
pub fn as_uuid(&self) -> Uuid {
Uuid::from(self.0)
}
pub fn from_uuid(uuid: Uuid) -> Self {
Self(Ulid::from(uuid))
}
pub fn timestamp_ms(&self) -> u64 {
self.0.timestamp_ms()
}
pub fn from_parts(timestamp_ms: u64, random: u128) -> Self {
Self(Ulid::from_parts(timestamp_ms, random))
}
}
impl Default for $name {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut buf = [0u8; ulid::ULID_LEN];
f.write_str(self.0.array_to_str(&mut buf))
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({})", stringify!($name), self)
}
}
impl FromStr for $name {
type Err = ParseIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ulid::from_string(s).map(Self).map_err(ParseIdError)
}
}
impl serde::Serialize for $name {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = <std::borrow::Cow<'de, str> as serde::Deserialize>::deserialize(d)?;
s.parse().map_err(serde::de::Error::custom)
}
}
impl From<$name> for Uuid {
fn from(id: $name) -> Uuid {
id.as_uuid()
}
}
impl From<Uuid> for $name {
fn from(uuid: Uuid) -> Self {
Self::from_uuid(uuid)
}
}
};
}
ulid_newtype! {
RecordId
}
ulid_newtype! {
VersionId
}