From bfe040451399b11ec594d993497f86a151e5691b Mon Sep 17 00:00:00 2001 From: Sebastian Reichelt Date: Sat, 24 Aug 2024 16:36:16 +0200 Subject: [PATCH] Fixed PartialOrd and Ord implementations to match primitive type. --- src/lib.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index c8c02cd..2111519 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -110,7 +110,7 @@ macro_rules! impl_nontype { assert_eq!(size_of::<", stringify!($prim) ,">(), size_of::>()); ```", ), - #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] + #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[repr(transparent)] pub struct $struct { value: $nonzero, @@ -155,6 +155,18 @@ macro_rules! impl_nontype { } } + impl PartialOrd for $struct { + fn partial_cmp(&self, other: &Self) -> Option { + self.get().partial_cmp(&other.get()) + } + } + + impl Ord for $struct { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { + self.get().cmp(&other.get()) + } + } + impl fmt::Debug for $struct { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, concat!(stringify!($struct), "({:?})"), self.get()) @@ -219,6 +231,15 @@ mod tests { assert_eq!(size_of::<$struct>(), size_of::<$prim>()); assert_eq!(size_of::>(), size_of::<$prim>()); assert_eq!(size_of::>(), size_of::<$prim>()); + + // test equality + assert_eq!(x, x); + assert_ne!(x, $struct::new(42).unwrap()); + + // test order + assert!(x <= x); + assert!(!(x < x)); + assert!($struct::new(1).unwrap() < $struct::new(2).unwrap()); } }; }