Skip to content

Commit

Permalink
Merge pull request #1 from SReichelt/master
Browse files Browse the repository at this point in the history
Fix PartialOrd and Ord implementations
  • Loading branch information
stijnh committed Aug 24, 2024
2 parents d9d116c + bfe0404 commit af70258
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ macro_rules! impl_nontype {
assert_eq!(size_of::<", stringify!($prim) ,">(), size_of::<Option<", stringify!($struct) ,">>());
```",
),
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct $struct {
value: $nonzero,
Expand Down Expand Up @@ -155,6 +155,18 @@ macro_rules! impl_nontype {
}
}

impl PartialOrd for $struct {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
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())
Expand Down Expand Up @@ -219,6 +231,15 @@ mod tests {
assert_eq!(size_of::<$struct>(), size_of::<$prim>());
assert_eq!(size_of::<Option<$struct>>(), size_of::<$prim>());
assert_eq!(size_of::<Result<$struct, ()>>(), 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());
}
};
}
Expand Down

0 comments on commit af70258

Please sign in to comment.