From 64dd15fcb941c096af93956e73492a062dd40bcd Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Wed, 8 Jan 2025 21:05:51 +0000 Subject: [PATCH] feat: add newtype macro --- src/lib.rs | 1 + src/newtype.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/newtype.rs diff --git a/src/lib.rs b/src/lib.rs index 8337712..e6cae35 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,2 @@ // +mod newtype; diff --git a/src/newtype.rs b/src/newtype.rs new file mode 100644 index 0000000..e5c2f99 --- /dev/null +++ b/src/newtype.rs @@ -0,0 +1,56 @@ +// +#[macro_export] +macro_rules! newtype { + ($name:ident, $docs:literal) => { + #[doc = $docs] + #[derive( + Clone, + Copy, + Default, + Debug, + derive_more::Display, + derive_more::From, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + derive_more::AsRef, + derive_more::Constructor, + serde::Serialize, + serde::Deserialize, + )] + pub struct $name; + }; + ($name:ident, $type:ty $(, $derive:ty)*, $docs:literal) => { + #[doc = $docs] + #[derive( + Clone, + Debug, + derive_more::From, + PartialEq, + Eq, + derive_more::AsRef, + derive_more::Deref, + serde::Serialize, + serde::Deserialize, + $($derive),* + )] + pub struct $name($type); + impl $name { + pub fn new(value: impl Into<$type>) -> Self { + Self(value.into()) + } + #[allow(clippy::missing_const_for_fn)] + #[must_use] + pub fn peel(self) -> $type { + self.0 + } + } + impl From<$name> for $type { + fn from(value: $name) -> $type { + value.peel() + } + } + }; +}