diff --git a/src/samples_formats.rs b/src/samples_formats.rs index 480fc0b..27d48a4 100644 --- a/src/samples_formats.rs +++ b/src/samples_formats.rs @@ -51,11 +51,7 @@ unsafe impl Sample for u16 { #[inline] fn to_i16(&self) -> i16 { - if *self >= 32768 { - (*self - 32768) as i16 - } else { - (*self as i16) - 32767 - 1 - } + (*self as i16).wrapping_add(i16::MIN) } #[inline] @@ -91,11 +87,7 @@ unsafe impl Sample for i16 { #[inline] fn to_u16(&self) -> u16 { - if *self < 0 { - (*self - i16::MIN) as u16 - } else { - (*self as u16) + 32768 - } + self.wrapping_add(i16::MIN) as u16 } #[inline] @@ -106,7 +98,7 @@ unsafe impl Sample for i16 { sample.to_i16() } } - +const F32_TO_16BIT_INT_MULTIPLIER: f32 = u16::MAX as f32 * 0.5; unsafe impl Sample for f32 { const FORMAT: SampleFormat = SampleFormat::F32; @@ -126,7 +118,8 @@ unsafe impl Sample for f32 { #[inline] fn to_u16(&self) -> u16 { - (((*self + 1.0) * 0.5) * u16::MAX as f32).round() as u16 + self.mul_add(F32_TO_16BIT_INT_MULTIPLIER, F32_TO_16BIT_INT_MULTIPLIER) + .round() as u16 } #[inline]