Skip to content

C0032 float-partial-cmp-unwrap

Rule: Floats are ordered with total_cmp, not partial_cmp that panics on NaN.

Code C0032 (stable, never reused)
Id float-partial-cmp-unwrap
Category code
Source spirit_level
Fix by hand

Level per tier

Tier Level Reason
small warn partial_cmp(..).unwrap() panics on the first NaN; total_cmp orders every float
small-workspace warn partial_cmp(..).unwrap() panics on the first NaN; total_cmp orders every float
medium warn partial_cmp(..).unwrap() panics on the first NaN; total_cmp orders every float
big warn partial_cmp(..).unwrap() panics on the first NaN; total_cmp orders every float
ai off
embedded off
ui off
egui off
units-strict off
units-paranoid off

Parameters

Name Type Default Meaning
methods list of strings ["unwrap", "expect"] methods on the partial_cmp result that panic on None

Why

a.partial_cmp(&b).unwrap() panics when either value is NaN. In a sort comparator, a NaN that reaches the data takes the program down far from where it was made. f32::total_cmp and f64::total_cmp order every value, NaN included, and never panic.

// panics on the first NaN
xs.sort_by(|a, b| a.partial_cmp(b).unwrap());

// orders every value
xs.sort_by(|a, b| a.total_cmp(b));

Where a NaN means a broken invariant (a control loop's current), the check belongs before the comparison: assert!(i_q.is_finite(), "i_q finite").

The lint reads the source without types, so it assumes the values are floats: partial_cmp on another PartialOrd type is reported too. Test code is not checked.

How to fix

Call total_cmp. For a type that wraps floats, implement Ord through total_cmp, or compare a key with sort_by(|a, b| a.x.total_cmp(&b.x)).

Configure

[lints.float-partial-cmp-unwrap]
level = "deny"
methods = ["unwrap", "expect"]
reason = "why this project wants it at this level"

Allow one finding in the code with // spirit-level: allow(float-partial-cmp-unwrap) <reason> (waivers); the code works there too, as in [lints.C0032].