Skip to content

Commit 0d22301

Browse files
orlpmbrubeck
authored andcommitted
Optimize ord implementation
1 parent 6d2f2d2 commit 0d22301

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
@@ -111,25 +111,37 @@ impl<T: Float> PartialOrd for OrderedFloat<T> {
111111
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
112112
Some(self.cmp(other))
113113
}
114+
115+
fn lt(&self, other: &Self) -> bool {
116+
!(self >= other)
117+
}
118+
119+
fn le(&self, other: &Self) -> bool {
120+
other >= self
121+
}
122+
123+
fn gt(&self, other: &Self) -> bool {
124+
!(other >= self)
125+
}
126+
127+
fn ge(&self, other: &Self) -> bool {
128+
// We consider all NaNs equal, and NaN is the largest possible
129+
// value. Thus if self is NaN we always return true. Otherwise
130+
// self >= other is correct. If other is also not NaN it is trivially
131+
// correct, and if it is we note that nothing can be greater or
132+
// equal to NaN except NaN itself, which we already handled earlier.
133+
self.0.is_nan() | (self.0 >= other.0)
134+
}
114135
}
115136

116137
impl<T: Float> Ord for OrderedFloat<T> {
117138
fn cmp(&self, other: &Self) -> Ordering {
118-
let lhs = &self.0;
119-
let rhs = &other.0;
120-
match lhs.partial_cmp(rhs) {
121-
Some(ordering) => ordering,
122-
None => {
123-
if lhs.is_nan() {
124-
if rhs.is_nan() {
125-
Ordering::Equal
126-
} else {
127-
Ordering::Greater
128-
}
129-
} else {
130-
Ordering::Less
131-
}
132-
}
139+
if self < other {
140+
Ordering::Less
141+
} else if self > other {
142+
Ordering::Greater
143+
} else {
144+
Ordering::Equal
133145
}
134146
}
135147
}

0 commit comments

Comments
 (0)