Skip to content

Commit

Permalink
feat: optionally integrate with num-cmp
Browse files Browse the repository at this point in the history
Signed-off-by: tison <wander4096@gmail.com>
  • Loading branch information
tisonkun committed Sep 25, 2024
1 parent f3cd47c commit f89a933
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ proptest = { version = "1.0.0", optional = true }
speedy = { version = "0.8.3", optional = true, default-features = false }
bytemuck = { version = "1.12.2", optional = true, default-features = false }
borsh = { version = "1.2.0", optional = true, default-features = false }
num-cmp = { version = "0.1.0", optional = true }

[dev-dependencies]
serde_test = "1.0"
Expand Down
60 changes: 60 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,66 @@ fn canonicalize_signed_zero<T: FloatCore>(x: T) -> T {
#[repr(transparent)]
pub struct OrderedFloat<T>(pub T);

#[cfg(feature = "num-cmp")]
mod impl_num_cmp {
use super::OrderedFloat;
use core::cmp::Ordering;
use num_cmp::NumCmp;
use num_traits::float::FloatCore;

impl<T, U> NumCmp<U> for OrderedFloat<T>
where
T: FloatCore + NumCmp<U>,
U: Copy,
{
fn num_cmp(self, other: U) -> Option<Ordering> {
NumCmp::num_cmp(self.0, other)
}

fn num_eq(self, other: U) -> bool {
NumCmp::num_eq(self.0, other)
}

fn num_ne(self, other: U) -> bool {
NumCmp::num_ne(self.0, other)
}

fn num_lt(self, other: U) -> bool {
NumCmp::num_lt(self.0, other)
}

fn num_gt(self, other: U) -> bool {
NumCmp::num_gt(self.0, other)
}

fn num_le(self, other: U) -> bool {
NumCmp::num_le(self.0, other)
}

fn num_ge(self, other: U) -> bool {
NumCmp::num_ge(self.0, other)
}
}

#[test]
pub fn test_num_cmp() {
let f = OrderedFloat(1.0);

assert_eq!(NumCmp::num_cmp(f, 1.0), Some(Ordering::Equal));
assert_eq!(NumCmp::num_cmp(f, -1.0), Some(Ordering::Greater));
assert_eq!(NumCmp::num_cmp(f, 2.0), Some(Ordering::Less));

assert!(NumCmp::num_eq(f, 1));
assert!(NumCmp::num_ne(f, -1));
assert!(NumCmp::num_lt(f, 100));
assert!(NumCmp::num_gt(f, 0));
assert!(NumCmp::num_le(f, 1));
assert!(NumCmp::num_le(f, 2));
assert!(NumCmp::num_ge(f, 1));
assert!(NumCmp::num_ge(f, -1));
}
}

impl<T: FloatCore> OrderedFloat<T> {
/// Get the value out.
#[inline]
Expand Down

0 comments on commit f89a933

Please sign in to comment.