#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum UuidError {
#[error("invalid UUID format")]
Format,
#[error("UUID must be version 4 (Random)")]
Version,
}
macro_rules! define_uuid_type {
(
$(#[$meta:meta])*
$vis:vis struct $Name:ident;
) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
$vis struct $Name(uuid::Uuid);
impl $Name {
pub fn parse(value: impl AsRef<str>) -> Result<Self, $crate::error::TypeError> {
let raw = value.as_ref().trim();
let parsed = uuid::Uuid::parse_str(raw).map_err(|_| $crate::error::TypeError::Uuid($crate::uuid_types::UuidError::Format))?;
if parsed.get_version() != Some(uuid::Version::Random) {
return Err($crate::error::TypeError::Uuid($crate::uuid_types::UuidError::Version));
}
Ok(Self(parsed))
}
#[inline]
pub fn generate() -> Self {
Self(uuid::Uuid::new_v4())
}
#[inline]
pub fn to_hyphenated_string(self) -> String {
self.0.as_hyphenated().to_string()
}
#[inline]
pub fn as_uuid(&self) -> &uuid::Uuid {
&self.0
}
#[inline]
pub fn into_inner(self) -> uuid::Uuid {
self.0
}
}
impl std::fmt::Display for $Name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.as_hyphenated())
}
}
impl std::ops::Deref for $Name {
type Target = uuid::Uuid;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl TryFrom<&str> for $Name {
type Error = $crate::error::TypeError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::parse(value)
}
}
impl TryFrom<String> for $Name {
type Error = $crate::error::TypeError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::parse(&value) }
}
impl From<$Name> for String {
fn from(value: $Name) -> Self {
value.to_hyphenated_string()
}
}
impl serde::Serialize for $Name {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut buffer = uuid::Uuid::encode_buffer();
let s = self.0.as_hyphenated().encode_lower(&mut buffer);
serializer.serialize_str(s)
}
}
#[allow(unknown_lints)]
impl<'de> serde::Deserialize<'de> for $Name {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = <&str>::deserialize(deserializer)?;
Self::parse(s).map_err(serde::de::Error::custom)
}
}
};
}
define_uuid_type! {
pub struct JobId;
}
define_uuid_type! {
pub struct SessionId;
}
define_uuid_type! {
pub struct RequestId;
}
define_uuid_type! {
pub struct Reuid;
}
#[cfg(test)]
macro_rules! uuid_type_tests {
($mod_name:ident, $Type:ident) => {
mod $mod_name {
use super::*;
const VALID: &str = "9b7e597e-893e-4e11-92cf-f4e7d4f923b1";
const VALID_UPPER: &str = "9B7E597E-893E-4E11-92CF-F4E7D4F923B1";
const VALID_SIMPLE: &str = "9b7e597e893e4e1192cff4e7d4f923b1";
const INVALID_V1: &str = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
#[test]
fn valid_hyphenated_should_parse() {
assert!($Type::parse(VALID).is_ok());
}
#[test]
fn valid_simple_format_should_parse() {
let id = $Type::parse(VALID_SIMPLE).unwrap();
assert_eq!(id.to_hyphenated_string(), VALID);
}
#[test]
fn uppercase_should_be_normalized() {
let id = $Type::parse(VALID_UPPER).unwrap();
assert_eq!(id.to_hyphenated_string(), VALID);
}
#[test]
fn whitespace_should_be_trimmed() {
let id = $Type::parse(format!(" {VALID} ")).unwrap();
assert_eq!(id.to_hyphenated_string(), VALID);
}
#[test]
fn invalid_uuid_should_be_rejected() {
assert!(matches!(
$Type::parse("not-a-uuid").unwrap_err(),
$crate::error::TypeError::Uuid($crate::uuid_types::UuidError::Format)
));
assert!(matches!(
$Type::parse(INVALID_V1).unwrap_err(),
$crate::error::TypeError::Uuid($crate::uuid_types::UuidError::Version)
));
}
#[test]
fn generated_uuids_should_be_unique() {
assert_ne!($Type::generate(), $Type::generate());
}
#[test]
fn serde_should_support_roundtrip() {
let id = $Type::parse(VALID).unwrap();
let json = serde_json::to_string(&id).unwrap();
assert_eq!(json, format!("\"{VALID}\""));
let back: $Type = serde_json::from_str(&json).unwrap();
assert_eq!(id, back);
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
uuid_type_tests!(job_id_tests, JobId);
uuid_type_tests!(session_id_tests, SessionId);
uuid_type_tests!(request_id_tests, RequestId);
}