Skip to content

Commit 20d8033

Browse files
authored
Merge pull request #155 from tisonkun/num-cmp
feat: optionally integrate with num-cmp
2 parents f3cd47c + f89a933 commit 20d8033

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ proptest = { version = "1.0.0", optional = true }
2525
speedy = { version = "0.8.3", optional = true, default-features = false }
2626
bytemuck = { version = "1.12.2", optional = true, default-features = false }
2727
borsh = { version = "1.2.0", optional = true, default-features = false }
28+
num-cmp = { version = "0.1.0", optional = true }
2829

2930
[dev-dependencies]
3031
serde_test = "1.0"

src/lib.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,66 @@ fn canonicalize_signed_zero<T: FloatCore>(x: T) -> T {
7979
#[repr(transparent)]
8080
pub struct OrderedFloat<T>(pub T);
8181

82+
#[cfg(feature = "num-cmp")]
83+
mod impl_num_cmp {
84+
use super::OrderedFloat;
85+
use core::cmp::Ordering;
86+
use num_cmp::NumCmp;
87+
use num_traits::float::FloatCore;
88+
89+
impl<T, U> NumCmp<U> for OrderedFloat<T>
90+
where
91+
T: FloatCore + NumCmp<U>,
92+
U: Copy,
93+
{
94+
fn num_cmp(self, other: U) -> Option<Ordering> {
95+
NumCmp::num_cmp(self.0, other)
96+
}
97+
98+
fn num_eq(self, other: U) -> bool {
99+
NumCmp::num_eq(self.0, other)
100+
}
101+
102+
fn num_ne(self, other: U) -> bool {
103+
NumCmp::num_ne(self.0, other)
104+
}
105+
106+
fn num_lt(self, other: U) -> bool {
107+
NumCmp::num_lt(self.0, other)
108+
}
109+
110+
fn num_gt(self, other: U) -> bool {
111+
NumCmp::num_gt(self.0, other)
112+
}
113+
114+
fn num_le(self, other: U) -> bool {
115+
NumCmp::num_le(self.0, other)
116+
}
117+
118+
fn num_ge(self, other: U) -> bool {
119+
NumCmp::num_ge(self.0, other)
120+
}
121+
}
122+
123+
#[test]
124+
pub fn test_num_cmp() {
125+
let f = OrderedFloat(1.0);
126+
127+
assert_eq!(NumCmp::num_cmp(f, 1.0), Some(Ordering::Equal));
128+
assert_eq!(NumCmp::num_cmp(f, -1.0), Some(Ordering::Greater));
129+
assert_eq!(NumCmp::num_cmp(f, 2.0), Some(Ordering::Less));
130+
131+
assert!(NumCmp::num_eq(f, 1));
132+
assert!(NumCmp::num_ne(f, -1));
133+
assert!(NumCmp::num_lt(f, 100));
134+
assert!(NumCmp::num_gt(f, 0));
135+
assert!(NumCmp::num_le(f, 1));
136+
assert!(NumCmp::num_le(f, 2));
137+
assert!(NumCmp::num_ge(f, 1));
138+
assert!(NumCmp::num_ge(f, -1));
139+
}
140+
}
141+
82142
impl<T: FloatCore> OrderedFloat<T> {
83143
/// Get the value out.
84144
#[inline]

0 commit comments

Comments
 (0)