From 3e46bfdc2906bac2edf914250d01dfb62c93f9f4 Mon Sep 17 00:00:00 2001 From: Martin Bruse Date: Thu, 19 Sep 2024 13:51:02 +0200 Subject: [PATCH] Added test of ToU8ForWriting. Found a bug. --- jxl/src/image.rs | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/jxl/src/image.rs b/jxl/src/image.rs index 0803be3..d81f46d 100644 --- a/jxl/src/image.rs +++ b/jxl/src/image.rs @@ -189,7 +189,7 @@ pub mod debug_tools { impl ToU8ForWriting for u16 { fn to_u8_for_writing(self) -> u8 { - (self as u32 * 255 / 65535) as u8 + (self as u32 >> 8) as u8 } } @@ -201,7 +201,7 @@ pub mod debug_tools { impl ToU8ForWriting for u32 { fn to_u8_for_writing(self) -> u8 { - (self as f32 / (2.0f32.powi(32) - 1.0)).to_u8_for_writing() + (self >> 24) as u8 } } @@ -255,4 +255,38 @@ mod test { assert!(image.as_rect().to_pgm().starts_with(b"P5\n32 32\n255\n")); Ok(()) } + + #[cfg(feature = "debug_tools")] + #[test] + fn to_u8() { + use super::debug_tools::ToU8ForWriting; + let mut want_u8 = 0u8; + let mut source_u16 = 0x00ffu16; + for _ in 0..256 { + assert!(source_u16.to_u8_for_writing() == want_u8); + want_u8 = want_u8.wrapping_add(1); + source_u16 = source_u16.wrapping_add(0x0100); + } + want_u8 = 0; + let mut source_f32 = 1f32 / 512f32; + for _ in 0..256 { + assert!(source_f32.to_u8_for_writing() == want_u8); + want_u8 = want_u8.wrapping_add(1); + source_f32 = source_f32 + (1f32 / 256f32); + } + want_u8 = 0; + let mut source_u32 = 0x00ffffffu32; + for _ in 0..256 { + assert!(source_u32.to_u8_for_writing() == want_u8); + want_u8 = want_u8.wrapping_add(1); + source_u32 = source_u32.wrapping_add(0x01000000); + } + want_u8 = 0; + let mut source_f16 = half::f16::from_f32(1f32 / 512f32); + for _ in 0..256 { + assert!(source_f16.to_u8_for_writing() == want_u8); + want_u8 = want_u8.wrapping_add(1); + source_f16 = source_f16 + half::f16::from_f32(1f32 / 256f32); + } + } }