Commit 2c986d3 1 parent d6879d9 commit 2c986d3 Copy full SHA for 2c986d3
File tree 1 file changed +11
-4
lines changed
1 file changed +11
-4
lines changed Original file line number Diff line number Diff line change @@ -436,17 +436,24 @@ impl<T: Primitive> FromPrimitive<T> for T {
436
436
// Note that in to-integer-conversion we are performing rounding but NumCast::from is implemented
437
437
// as truncate towards zero. We emulate rounding by adding a bias.
438
438
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
+
439
448
impl FromPrimitive < f32 > for u8 {
440
449
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 ( )
443
451
}
444
452
}
445
453
446
454
impl FromPrimitive < f32 > for u16 {
447
455
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 ( )
450
457
}
451
458
}
452
459
You can’t perform that action at this time.
0 commit comments