From d0a4796df32745697a31e50411b444d8a27a2aec Mon Sep 17 00:00:00 2001 From: Vital Kalinousky Date: Tue, 1 Dec 2026 13:12:01 +0300 Subject: [PATCH] fix(data): do not panic on NaN in Quartiles::new `Quartiles::new` sorts the copied slice with `s.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap())`. For a numeric series (`T = f64`/`f32`) a single `NaN` makes `partial_cmp` return `None`, and the `unwrap()` aborts the caller's program. `NaN` is a legal `f64` and appears in real data (missing measurements, `0.0 / 0.0`, deserialised `null`), and the doc comment on `new` states no NaN precondition, so today bad data becomes a process panic instead of a plot. Sort NaN as equal, which keeps the result defined: a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal) Measured on this tree, `cargo test -p plotters --lib data::quartiles`: without the fix: test_nan_in_data_does_not_panic ... FAILED panicked at plotters/src/data/quartiles.rs:51:52 (2 passed; 1 failed) with the fix: test_nan_in_data_does_not_panic ... ok 3 passed; 0 failed Regression test added next to the existing ones in the same file. --- plotters/src/data/quartiles.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/plotters/src/data/quartiles.rs b/plotters/src/data/quartiles.rs index 78613dad..0a16eaa8 100644 --- a/plotters/src/data/quartiles.rs +++ b/plotters/src/data/quartiles.rs @@ -45,7 +45,10 @@ impl Quartiles { /// ``` pub fn new + Copy + PartialOrd>(s: &[T]) -> Self { let mut s = s.to_owned(); - s.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); + // NaN has no total order, so `partial_cmp` returns `None` for it; a numeric + // data series (where NaN means a missing measurement) must not panic the + // whole plot. Sorting NaN as equal keeps the result defined. + s.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); let lower = Quartiles::percentile_of_sorted(&s, 25_f64); let median = Quartiles::percentile_of_sorted(&s, 50_f64); @@ -102,6 +105,14 @@ impl Quartiles { mod test { use super::*; + #[test] + fn test_nan_in_data_does_not_panic() { + // Regression: `partial_cmp(..).unwrap()` aborted the caller on a single NaN. + let q = Quartiles::new(&[1.0f64, f64::NAN, 2.0]); + let values = q.values(); + assert_eq!(values.len(), 5); + } + #[test] #[should_panic] fn test_empty_input() {