#[macro_export]
macro_rules! wrapper {
(
$(#[$meta:meta])*
$name:ident $({
$(#[debug = $debug:literal])?
$(#[display = $display:literal])?
})?
) => {
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
$(#[$meta])*
pub struct $name($crate::Uuid);
impl $crate::UuidLike for $name {
#[inline]
fn random() -> Self {
Self($crate::Uuid::new_v4())
}
#[inline]
fn from_bytes(bytes: [u8; 16]) -> Self {
Self($crate::Uuid::from_bytes(bytes))
}
#[inline]
fn as_bytes(&self) -> &[u8; 16] {
self.0.as_bytes()
}
#[inline]
fn into_bytes(self) -> [u8; 16] {
self.0.into_bytes()
}
}
impl ::std::fmt::Debug for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
$crate::wrapper!(@debug; $name, f, self, $($($debug)?)?)
}
}
impl ::std::fmt::Display for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
$crate::wrapper!(@display; f, self, $($($display)?)?)
}
}
};
(@debug; $name:ident, $f:ident, $self:ident, $debug:literal) => {
write!($f, $debug, _0 = $self.0)
};
(@debug; $name:ident, $f:ident, $self:ident, ) => {
write!($f, "{}({:?})", stringify!($name), $self.0)
};
(@display; $f:ident, $self:ident, $display:literal) => {
write!($f, $display, _0 = $self.0)
};
(@display; $f:ident, $self:ident, ) => {
write!($f, "{}", $self.0)
};
}
#[cfg(test)]
mod tests {
use crate::*;
wrapper!(Basic);
wrapper! {
WithDebug {
#[debug = "CustomDebug({_0:?})"]
}
}
wrapper! {
WithDisplay {
#[display = "custom-display-{_0}"]
}
}
wrapper! {
WithDebugAndDisplay {
#[debug = "CustomDebug({_0:?})"]
#[display = "custom-display-{_0}"]
}
}
#[test]
fn basic() {
let id = Basic::from_u128(1);
insta::assert_snapshot!(id, @"00000000-0000-0000-0000-000000000001");
insta::assert_debug_snapshot!(id, @"Basic(00000000-0000-0000-0000-000000000001)");
}
#[test]
fn with_display() {
let id = WithDisplay::from_u128(2);
insta::assert_snapshot!(id, @"custom-display-00000000-0000-0000-0000-000000000002");
insta::assert_debug_snapshot!(id, @"WithDisplay(00000000-0000-0000-0000-000000000002)");
}
#[test]
fn with_debug() {
let id = WithDebug::from_u128(3);
insta::assert_snapshot!(id, @"00000000-0000-0000-0000-000000000003");
insta::assert_debug_snapshot!(id, @"CustomDebug(00000000-0000-0000-0000-000000000003)");
}
#[test]
fn with_debug_and_display() {
let id = WithDebugAndDisplay::from_u128(4);
insta::assert_snapshot!(id, @"custom-display-00000000-0000-0000-0000-000000000004");
insta::assert_debug_snapshot!(id, @"CustomDebug(00000000-0000-0000-0000-000000000004)");
}
}