Skip to content

Commit 3dad4c3

Browse files
committed
Speed up clamping by taking NaN into account for upper bound
1 parent 0b90da4 commit 3dad4c3

File tree

1 file changed

+5
-10
lines changed

1 file changed

+5
-10
lines changed

src/color.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -389,25 +389,20 @@ impl<T: Primitive> FromPrimitive<T> for T {
389389
// NaN however always maps to NaN therefore we have to force it towards some value.
390390
// 1.0 (white) was picked as firefox and chrome choose to map NaN to that.
391391
#[inline]
392-
fn sanitize_nan(i: f32) -> f32 {
393-
if i.is_nan() {
394-
1.0
395-
} else {
396-
i
397-
}
392+
fn normalize_float(float: f32, max: f32) -> f32 {
393+
let clamped = if !(float < 1.0) { 1.0 } else { float.max(0.0) };
394+
(clamped * max).round()
398395
}
399396

400397
impl FromPrimitive<f32> for u8 {
401398
fn from_primitive(float: f32) -> Self {
402-
let inner = (sanitize_nan(float).clamp(0.0, 1.0) * u8::MAX as f32).round();
403-
NumCast::from(inner).unwrap()
399+
NumCast::from(normalize_float(float, u8::MAX as f32)).unwrap()
404400
}
405401
}
406402

407403
impl FromPrimitive<f32> for u16 {
408404
fn from_primitive(float: f32) -> Self {
409-
let inner = (sanitize_nan(float).clamp(0.0, 1.0) * u16::MAX as f32).round();
410-
NumCast::from(inner).unwrap()
405+
NumCast::from(normalize_float(float, u16::MAX as f32)).unwrap()
411406
}
412407
}
413408

0 commit comments

Comments
 (0)