Repository navigation
Description
Motivation
When clamping floats to an interval [min, max], what to do with NaN depends on the use case. While f32::clamp and SimdFloat::clamp propagate NaN, this isn't always desirable. Especially when the result must be inside the interval [min, max] (no NaN allowed), clamp is the wrong tool. In scalar code, one can then use f32::min/max to map NaN to either min or max. E.g. x.max(0.0).min(1.0) will map NaN to 0.
Unfortunately, this is currently impossible to implement in fearless_simd without using custom kernels. The result for signalling NaNs is unspecified for both max and max_precise (similar for min). I tried to fix this, but it seems that the fix is unlikely to get in (#441).
This is a problem since mapping NaN to the minimum or maximum of the clamping interval is a rather common use case.
Suggestion
Add the following new APIs:
trait SimdFloat {
fn clamp_with(self, min: Self, max: Self, nan: ClampNaN) -> Self;
}
enum ClampNaN {
Propagate,
ToMin,
ToMax
}I hope the semantics are clear. Imparticular, x.clamp_with(min, max, ClampNaN::Propagate) is equivalent to x.clamp(min, max).
The implementation of this function would look somewhat like this:
#[inline(always)]
fn clamp_with(self, min: Self, max: Self, nan: ClampNaN) -> Self {
match nan {
Propagate => self.clamp(min, max),
ToMin => platformat_specific_to_min,
ToMax => platformat_specific_to_max,
}
}Since NaN handling will typically be an inlinable constant, the match will typically disappear, leaving only the raw operation. And the raw operations are also very efficient to implement. Just like clamp, the to-min and to-max variants can be implemented with just 2 instructions each on x86 and WASM. Only Neon will need 3 instructions, one more to handle sNaN correctly.
Alternatives
- Instead of a combined
clamp_with+ NaN-handling enum, add 2 methodsclamp_nan_to_{min,max}with the semantics described above. - Change the semantics of
{max,min}_preciseto handle all NaNs (Handle sNaNs in{min,max}_preciseon Neon #441). However, user code likex.max_precise(min).min_precise(max)would be less efficient thanclamp_withon all platforms.
Activity
Shnatsel commentedon Nov 25, 2026
Making clamp_nan a
constargument is also an option from the API perspective.RunDevelopment commentedon Nov 25, 2026
Having it
constin some way would be ideal, butfn clamp_with<const NAN: ClampNaN>(...)is unstable IIRC. What do you mean exactly?Shnatsel commentedon Nov 25, 2026
I think we can put a
boolin there if we have only two options. If we want to have the relaxed variant too then it no longer works without gross hacks like named constants plus a<const NAN: u8>argument.RunDevelopment commentedon Nov 25, 2026
Yikes. I think
boolis pretty hacky too. You tell me whatx.clamp_with::<true>(min, max)does.Plus, I hope we won't need relaxed variants. That whole sNaN ordeal in #441 is giving me a headach, but I still have hope that we can find a good solution.