Skip to content

Commit 2c986d3

Browse files
authored
Clamp NaN to white when converting to integer (#2381)
1 parent d6879d9 commit 2c986d3

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/color.rs

+11-4
Original file line numberDiff line numberDiff line change
@@ -436,17 +436,24 @@ impl<T: Primitive> FromPrimitive<T> for T {
436436
// Note that in to-integer-conversion we are performing rounding but NumCast::from is implemented
437437
// as truncate towards zero. We emulate rounding by adding a bias.
438438

439+
// All other special values are clamped inbetween 0.0 and 1.0 (infinities and subnormals)
440+
// NaN however always maps to NaN therefore we have to force it towards some value.
441+
// 1.0 (white) was picked as firefox and chrome choose to map NaN to that.
442+
#[inline]
443+
fn normalize_float(float: f32, max: f32) -> f32 {
444+
let clamped = if !(float < 1.0) { 1.0 } else { float.max(0.0) };
445+
(clamped * max).round()
446+
}
447+
439448
impl FromPrimitive<f32> for u8 {
440449
fn from_primitive(float: f32) -> Self {
441-
let inner = (float.clamp(0.0, 1.0) * u8::MAX as f32).round();
442-
NumCast::from(inner).unwrap()
450+
NumCast::from(normalize_float(float, u8::MAX as f32)).unwrap()
443451
}
444452
}
445453

446454
impl FromPrimitive<f32> for u16 {
447455
fn from_primitive(float: f32) -> Self {
448-
let inner = (float.clamp(0.0, 1.0) * u16::MAX as f32).round();
449-
NumCast::from(inner).unwrap()
456+
NumCast::from(normalize_float(float, u16::MAX as f32)).unwrap()
450457
}
451458
}
452459

0 commit comments

Comments
 (0)