use core::fmt;
use core::ops::{Add, AddAssign, Div, Mul, Sub};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct QValue<S, const FRAC: u32>(S);
pub type Q16_16 = QValue<i32, 16>;
pub type Q8_8 = QValue<i16, 8>;
impl<S: fmt::Display, const FRAC: u32> fmt::Display for QValue<S, FRAC> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
pub trait Scalar:
Copy
+ Default
+ PartialOrd
+ Add<Output = Self>
+ AddAssign
+ Sub<Output = Self>
+ Mul<Output = Self>
+ Div<Output = Self>
{
const ZERO: Self;
const ONE: Self;
fn pow2_neg(n: u32) -> Self;
fn div_int(self, n: i32) -> Self;
fn mul_round_toward_zero(self, rhs: Self) -> Self {
self * rhs
}
fn mul_round_nearest(self, rhs: Self) -> Self {
self * rhs
}
}
#[deprecated(
since = "0.2.0",
note = "renamed to `Scalar`, which covers f32 and f64 as well as the Q formats"
)]
pub trait Fixed: Scalar {}
#[allow(deprecated)]
impl<T: Scalar> Fixed for T {}
macro_rules! impl_fixed_float {
($t:ty) => {
impl Scalar for $t {
const ZERO: Self = 0.0;
const ONE: Self = 1.0;
fn pow2_neg(n: u32) -> Self {
let mut x: $t = 1.0;
for _ in 0..n.min(1100) {
x *= 0.5;
}
x
}
fn div_int(self, n: i32) -> Self {
self / (n as $t)
}
}
};
}
impl_fixed_float!(f32);
impl_fixed_float!(f64);
pub trait Sqrt {
fn sqrt(self) -> Self;
}
macro_rules! impl_qvalue {
($s:ty, $wide:ty) => {
impl<const FRAC: u32> QValue<$s, FRAC> {
const FORMAT_OK: () = assert!(
FRAC >= 1 && FRAC < <$s>::BITS,
"QValue needs at least 1 fractional bit and fewer than the storage width"
);
pub const FRACTIONAL_BITS: u32 = FRAC;
pub const FIXED_BITS: u32 = <$s>::BITS - FRAC;
pub const ZERO: Self = Self::from_raw(0);
pub const ONE: Self = Self::from_int(1);
pub const fn from_raw(raw: $s) -> Self {
let () = Self::FORMAT_OK;
Self(raw)
}
pub const fn from_int(n: i32) -> Self {
let () = Self::FORMAT_OK;
Self(((n as u32) << FRAC) as $s)
}
pub const fn pow2_neg(n: u32) -> Self {
if n > FRAC {
return Self::from_raw(0);
}
Self::from_raw((1 as $s) << (FRAC - n))
}
pub const fn raw(self) -> $s {
self.0
}
pub fn to_f64(self) -> f64 {
let () = Self::FORMAT_OK;
f64::from(self.0) / f64::from(1u32 << FRAC)
}
pub fn from_f64_trunc(x: f64) -> Self {
Self::from_raw((x * f64::from(1u32 << FRAC)) as $s)
}
pub fn mul_round_toward_zero(self, rhs: Self) -> Self {
let () = Self::FORMAT_OK;
let product = <$wide>::from(self.0) * <$wide>::from(rhs.0);
let bias = (product >> (<$wide>::BITS - 1)) & ((1 << FRAC) - 1);
Self(((product + bias) >> FRAC) as $s)
}
pub fn mul_round_nearest(self, rhs: Self) -> Self {
let () = Self::FORMAT_OK;
let product = <$wide>::from(self.0) * <$wide>::from(rhs.0);
let sign = product >> (<$wide>::BITS - 1);
Self(((product + (1 << (FRAC - 1)) + sign) >> FRAC) as $s)
}
pub const fn div_int(self, n: i32) -> Self {
if n == 0 {
return Self::div_by_zero(self.0);
}
Self((self.0 as i64 / n as i64) as $s)
}
pub const fn is_within_zero_tolerance(self) -> bool {
let () = Self::FORMAT_OK;
let shift = if FRAC > 7 { FRAC - 7 } else { 1 };
let tolerance = (1 as $s) << shift;
self.0 == 0 || (self.0 < tolerance && self.0 > -tolerance)
}
const fn div_by_zero(dividend: $s) -> Self {
if dividend > 0 {
Self(<$s>::MAX)
} else if dividend < 0 {
Self(<$s>::MIN)
} else {
Self(0)
}
}
}
impl<const FRAC: u32> Add for QValue<$s, FRAC> {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Self(self.0.wrapping_add(rhs.0))
}
}
impl<const FRAC: u32> AddAssign for QValue<$s, FRAC> {
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs;
}
}
impl<const FRAC: u32> Sub for QValue<$s, FRAC> {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
Self(self.0.wrapping_sub(rhs.0))
}
}
impl<const FRAC: u32> Mul for QValue<$s, FRAC> {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
let () = Self::FORMAT_OK;
let product = <$wide>::from(self.0) * <$wide>::from(rhs.0);
Self((product >> FRAC) as $s)
}
}
impl<const FRAC: u32> Div for QValue<$s, FRAC> {
type Output = Self;
fn div(self, rhs: Self) -> Self {
let () = Self::FORMAT_OK;
if rhs.0 == 0 {
return Self::div_by_zero(self.0);
}
let dividend = <$wide>::from(self.0) * ((1 as $wide) << FRAC);
Self((dividend / <$wide>::from(rhs.0)) as $s)
}
}
impl<const FRAC: u32> Sqrt for QValue<$s, FRAC> {
fn sqrt(self) -> Self {
let () = Self::FORMAT_OK;
if self.0 <= 0 {
return Self(0);
}
let n = <$wide>::from(self.0) << FRAC;
let mut x = n;
let mut y = (x + 1) / 2;
while y < x {
x = y;
y = (x + n.checked_div(x).unwrap_or(0)) / 2;
}
Self(x as $s)
}
}
impl<const FRAC: u32> Scalar for QValue<$s, FRAC> {
const ZERO: Self = Self::ZERO;
const ONE: Self = Self::ONE;
fn pow2_neg(n: u32) -> Self {
Self::pow2_neg(n)
}
fn div_int(self, n: i32) -> Self {
self.div_int(n)
}
fn mul_round_toward_zero(self, rhs: Self) -> Self {
self.mul_round_toward_zero(rhs)
}
fn mul_round_nearest(self, rhs: Self) -> Self {
self.mul_round_nearest(rhs)
}
}
};
}
impl_qvalue!(i32, i64);
impl_qvalue!(i16, i32);
#[cfg(test)]
mod tests {
use super::*;
fn check_floor_root(raw: i64, frac: u32, root: i64) {
let n = raw << frac;
assert!(
root * root <= n && (root + 1) * (root + 1) > n,
"raw {raw}: root {root}"
);
}
#[test]
fn sqrt_every_q8_8_value() {
for raw in i16::MIN..=i16::MAX {
let r = i64::from(Q8_8::from_raw(raw).sqrt().raw());
if raw <= 0 {
assert_eq!(r, 0);
} else {
check_floor_root(i64::from(raw), 8, r);
}
}
assert_eq!(Q8_8::from_int(4).sqrt(), Q8_8::from_int(2));
}
#[test]
fn sqrt_q16_16_sample_and_edges() {
let mut x: u32 = 1;
let edges = [1, 2, 3, 65_535, 65_536, 65_537, i32::MAX - 1, i32::MAX];
for raw in edges.into_iter().chain((0..100_000).map(|_| {
x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(x >> 1) as i32
})) {
check_floor_root(
i64::from(raw),
16,
i64::from(Q16_16::from_raw(raw).sqrt().raw()),
);
}
assert_eq!(Q16_16::from_int(9).sqrt(), Q16_16::from_int(3));
assert_eq!(Q16_16::from_int(-9).sqrt(), Q16_16::ZERO);
let _ = QValue::<i32, 31>::from_raw(i32::MAX).sqrt();
let _ = QValue::<i16, 15>::from_raw(i16::MAX).sqrt();
}
#[test]
fn constants() {
assert_eq!(Q16_16::ONE.raw(), 65536);
assert_eq!(Q16_16::from_int(-1).raw(), -65536);
assert_eq!(Q16_16::pow2_neg(2).raw(), 16384);
assert_eq!(Q8_8::ONE.raw(), 256);
assert_eq!(Q8_8::from_int(-1).raw(), -256);
assert_eq!(Q8_8::pow2_neg(4).raw(), 16);
assert_eq!((Q8_8::FIXED_BITS, Q8_8::FRACTIONAL_BITS), (8, 8));
}
#[test]
fn from_int_truncates_the_fixed_part() {
assert_eq!(Q8_8::from_int(200), Q8_8::from_int(-56));
assert_eq!(Q8_8::from_int(127).raw(), 127 * 256);
}
#[test]
fn multiply_truncates_toward_negative_infinity() {
let r = Q16_16::from_raw(-1) * Q16_16::pow2_neg(1);
assert_eq!(r.raw(), -1);
let r = Q16_16::from_raw(1) * Q16_16::pow2_neg(1);
assert_eq!(r.raw(), 0);
assert_eq!((Q8_8::from_raw(-1) * Q8_8::pow2_neg(1)).raw(), -1);
assert_eq!((Q8_8::from_raw(1) * Q8_8::pow2_neg(1)).raw(), 0);
}
#[test]
fn multiply_wraps_to_the_storage_width() {
let r = Q8_8::from_int(100) * Q8_8::from_int(2);
assert_eq!(r, Q8_8::from_int(-56));
}
#[test]
fn divide_truncates_toward_zero_and_saturates_on_zero() {
assert_eq!((Q16_16::from_raw(-3) / Q16_16::from_int(2)).raw(), -1);
assert_eq!((Q16_16::ONE / Q16_16::ZERO).raw(), i32::MAX);
assert_eq!((Q16_16::from_int(-1) / Q16_16::ZERO).raw(), i32::MIN);
assert_eq!((Q16_16::ZERO / Q16_16::ZERO).raw(), 0);
assert_eq!((Q8_8::from_raw(-3) / Q8_8::from_int(2)).raw(), -1);
assert_eq!((Q8_8::ONE / Q8_8::ZERO).raw(), i16::MAX);
assert_eq!((Q8_8::from_int(-1) / Q8_8::ZERO).raw(), i16::MIN);
assert_eq!(Q8_8::ONE.div_int(0).raw(), i16::MAX);
}
#[test]
fn pow2_neg_range() {
assert_eq!(Q16_16::pow2_neg(16).raw(), 1);
assert_eq!(Q16_16::pow2_neg(0), Q16_16::ONE);
assert_eq!(Q8_8::pow2_neg(8).raw(), 1);
}
#[test]
fn pow2_neg_below_resolution_truncates_to_zero() {
for n in [17, 20, 32, 63, 64, u32::MAX] {
assert_eq!(
Q16_16::pow2_neg(core::hint::black_box(n)),
Q16_16::ZERO,
"n = {n}"
);
}
assert_eq!(Q8_8::pow2_neg(9), Q8_8::ZERO);
}
#[test]
fn add_wraps() {
let r = Q16_16::from_raw(i32::MAX) + Q16_16::from_raw(1);
assert_eq!(r.raw(), i32::MIN);
let r = Q8_8::from_raw(i16::MAX) + Q8_8::from_raw(1);
assert_eq!(r.raw(), i16::MIN);
}
#[test]
fn zero_tolerance() {
assert!(Q16_16::from_raw(511).is_within_zero_tolerance());
assert!(Q16_16::from_raw(-511).is_within_zero_tolerance());
assert!(!Q16_16::from_raw(512).is_within_zero_tolerance());
assert!(Q8_8::from_raw(1).is_within_zero_tolerance());
assert!(Q8_8::from_raw(-1).is_within_zero_tolerance());
assert!(!Q8_8::from_raw(2).is_within_zero_tolerance());
assert!(!Q8_8::from_raw(-2).is_within_zero_tolerance());
}
}