use core::ops::Mul;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Qfx<const F: u32> {
integer: u32,
fraction: u32,
}
impl<const F: u32> Qfx<F> {
#[inline]
pub const fn from_parts(integer: u32, fraction: u32) -> Self {
Self { integer, fraction }
}
#[inline]
pub fn from_f32(value: f32) -> Self {
let integer = value as u32;
let fraction = ((value - integer as f32) * (1u32 << F) as f32) as u32;
Self { integer, fraction }
}
#[inline]
pub const fn integer_part(self) -> u32 {
self.integer
}
#[inline]
pub const fn fraction_part(self) -> u32 {
self.fraction
}
}
macro_rules! impl_mul_unsigned {
($narrow:ty, $wide:ty) => {
impl<const F: u32> Mul<$narrow> for Qfx<F> {
type Output = $narrow;
#[allow(clippy::suspicious_arithmetic_impl)]
#[inline]
fn mul(self, v: $narrow) -> $narrow {
let v = v as $wide;
let whole = v.wrapping_mul(self.integer as $wide);
let frac = (v.wrapping_mul(self.fraction as $wide)) >> F;
whole.wrapping_add(frac) as $narrow
}
}
impl<const F: u32> Mul<Qfx<F>> for $narrow {
type Output = $narrow;
#[inline]
fn mul(self, q: Qfx<F>) -> $narrow {
q * self
}
}
};
}
macro_rules! impl_mul_signed {
($narrow:ty, $wide:ty) => {
impl<const F: u32> Mul<$narrow> for Qfx<F> {
type Output = $narrow;
#[allow(clippy::suspicious_arithmetic_impl)]
#[inline]
fn mul(self, v: $narrow) -> $narrow {
let v = v as $wide;
let whole = v.wrapping_mul(self.integer as $wide);
let frac = (v.wrapping_mul(self.fraction as $wide)) >> F;
whole.wrapping_add(frac) as $narrow
}
}
impl<const F: u32> Mul<Qfx<F>> for $narrow {
type Output = $narrow;
#[inline]
fn mul(self, q: Qfx<F>) -> $narrow {
q * self
}
}
};
}
impl_mul_unsigned!(u16, u32);
impl_mul_unsigned!(u32, u64);
impl_mul_signed!(i16, i32);
impl_mul_signed!(i32, i64);
pub type Q44 = Qfx<4>;
pub type Q62 = Qfx<6>;
pub type Q88 = Qfx<8>;
pub type Q124 = Qfx<12>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn multiplies_like_a_ratio() {
let one_point_five = Q88::from_parts(1, 128);
assert_eq!(one_point_five * 100u32, 150);
assert_eq!(100u32 * one_point_five, 150);
assert_eq!(one_point_five * 100u16, 150);
assert_eq!(one_point_five * 100i32, 150);
assert_eq!(one_point_five * 100i16, 150);
}
#[test]
fn integer_only_ratio_is_plain_multiplication() {
let three = Q44::from_parts(3, 0);
for v in 0u16..=1000 {
assert_eq!(three * v, v.wrapping_mul(3));
}
}
#[test]
fn from_f32_quantizes_into_parts() {
let q = Q88::from_f32(2.5);
assert_eq!(q.integer_part(), 2);
assert_eq!(q.fraction_part(), 128); assert_eq!(q * 4u32, 10);
}
}