Skip to content

Commit

Permalink
Fix soundness bug in NotNan::partial_cmp.
Browse files Browse the repository at this point in the history
Ill-behaved FloatCore implementations for user types could have where
`x.partial_cmp(&x) == None` even when `x.is_nan() == false`.  This crate
will now panic in those cases, rather than execute undefined behavior.

Fixes #150.
  • Loading branch information
mbrubeck committed Jun 29, 2024
1 parent 8eb3455 commit 02b92c7
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use core::cmp::Ordering;
use core::convert::TryFrom;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::hint::unreachable_unchecked;
use core::iter::{Product, Sum};
use core::num::FpCategory;
use core::ops::{
Expand Down Expand Up @@ -1163,9 +1162,11 @@ impl Borrow<f64> for NotNan<f64> {
#[allow(clippy::derive_ord_xor_partial_ord)]
impl<T: FloatCore> Ord for NotNan<T> {
fn cmp(&self, other: &NotNan<T>) -> Ordering {
// Can't use unreachable_unchecked because unsafe code can't depend on FloatCore impl.
// https://github.com/reem/rust-ordered-float/issues/150
match self.partial_cmp(other) {
Some(ord) => ord,
None => unsafe { unreachable_unchecked() },
None => unreachable!(),
}
}
}
Expand Down

0 comments on commit 02b92c7

Please sign in to comment.