Skip to content

Commit

Permalink
Clamp NaN to white when converting to integer (#2381)
Browse files Browse the repository at this point in the history
  • Loading branch information
FlareFlo authored Nov 19, 2024
1 parent d6879d9 commit 2c986d3
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,17 +436,24 @@ impl<T: Primitive> FromPrimitive<T> for T {
// Note that in to-integer-conversion we are performing rounding but NumCast::from is implemented
// as truncate towards zero. We emulate rounding by adding a bias.

// All other special values are clamped inbetween 0.0 and 1.0 (infinities and subnormals)
// NaN however always maps to NaN therefore we have to force it towards some value.
// 1.0 (white) was picked as firefox and chrome choose to map NaN to that.
#[inline]
fn normalize_float(float: f32, max: f32) -> f32 {
let clamped = if !(float < 1.0) { 1.0 } else { float.max(0.0) };
(clamped * max).round()
}

impl FromPrimitive<f32> for u8 {
fn from_primitive(float: f32) -> Self {
let inner = (float.clamp(0.0, 1.0) * u8::MAX as f32).round();
NumCast::from(inner).unwrap()
NumCast::from(normalize_float(float, u8::MAX as f32)).unwrap()
}
}

impl FromPrimitive<f32> for u16 {
fn from_primitive(float: f32) -> Self {
let inner = (float.clamp(0.0, 1.0) * u16::MAX as f32).round();
NumCast::from(inner).unwrap()
NumCast::from(normalize_float(float, u16::MAX as f32)).unwrap()
}
}

Expand Down

0 comments on commit 2c986d3

Please sign in to comment.