Skip to content

Commit 46c9670

Browse files
committed
Optimize ord implementation
1 parent f4ca84b commit 46c9670

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

src/lib.rs

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -116,25 +116,37 @@ impl<T: FloatCore> PartialOrd for OrderedFloat<T> {
116116
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
117117
Some(self.cmp(other))
118118
}
119+
120+
fn lt(&self, other: &Self) -> bool {
121+
!(self >= other)
122+
}
123+
124+
fn le(&self, other: &Self) -> bool {
125+
other >= self
126+
}
127+
128+
fn gt(&self, other: &Self) -> bool {
129+
!(other >= self)
130+
}
131+
132+
fn ge(&self, other: &Self) -> bool {
133+
// We consider all NaNs equal, and NaN is the largest possible
134+
// value. Thus if self is NaN we always return true. Otherwise
135+
// self >= other is correct. If other is also not NaN it is trivially
136+
// correct, and if it is we note that nothing can be greater or
137+
// equal to NaN except NaN itself, which we already handled earlier.
138+
self.0.is_nan() | (self.0 >= other.0)
139+
}
119140
}
120141

121142
impl<T: FloatCore> Ord for OrderedFloat<T> {
122143
fn cmp(&self, other: &Self) -> Ordering {
123-
let lhs = &self.0;
124-
let rhs = &other.0;
125-
match lhs.partial_cmp(rhs) {
126-
Some(ordering) => ordering,
127-
None => {
128-
if lhs.is_nan() {
129-
if rhs.is_nan() {
130-
Ordering::Equal
131-
} else {
132-
Ordering::Greater
133-
}
134-
} else {
135-
Ordering::Less
136-
}
137-
}
144+
if self < other {
145+
Ordering::Less
146+
} else if self > other {
147+
Ordering::Greater
148+
} else {
149+
Ordering::Equal
138150
}
139151
}
140152
}

0 commit comments

Comments
 (0)