ifc_lite_geometry/float_order.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! A total order for `f64` sort keys (#7674).
6//!
7//! `a.partial_cmp(b).unwrap_or(Ordering::Equal)` is not a total order once a
8//! NaN is in the slice: NaN is "equal" to everything, which is not
9//! transitive. Since Rust 1.81, `sort_by` may panic on such a comparator, and
10//! the wasm build is `panic = abort`, so one NaN from a file or a caller can
11//! trap the shared instance. `scripts/check-float-sort-comparators.mjs` keeps
12//! that spelling out of the tree.
13//!
14//! [`cmp_f64_nan_last`] is the drop-in replacement. For two numbers it returns
15//! exactly what `partial_cmp` returned, including `-0.0 == +0.0`, so a sort
16//! over finite (or infinite) keys keeps its old order byte for byte. That is
17//! why it is used instead of `f64::total_cmp`, which orders `-0.0` before
18//! `+0.0` and orders a NaN by its sign bit (x86 and wasm do not agree on the
19//! sign of a NaN produced by arithmetic). Every NaN sorts after every number
20//! and compares equal to every other NaN.
21
22use std::cmp::Ordering;
23
24/// Ascending order of `a` and `b`, with NaN after every number.
25///
26/// Use it as `xs.sort_by(|a, b| cmp_f64_nan_last(*a, *b))`. A descending sort
27/// that swaps the arguments therefore puts NaN first.
28#[inline]
29pub fn cmp_f64_nan_last(a: f64, b: f64) -> Ordering {
30 match a.partial_cmp(&b) {
31 Some(order) => order,
32 None => a.is_nan().cmp(&b.is_nan()),
33 }
34}
35
36#[cfg(test)]
37#[path = "float_order_tests.rs"]
38mod tests;