#![allow(clippy::integer_division)]
use std::fmt;
use std::iter::Sum;
use std::ops::{Add, Sub};
pub const SCALE: i128 = 1_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
pub struct Fixed6(i128);
impl Fixed6 {
pub const ZERO: Self = Self(0);
pub const ONE: Self = Self(SCALE);
#[must_use]
pub const fn from_scaled(raw: i128) -> Self {
Self(raw)
}
#[must_use]
pub const fn from_integer(n: i64) -> Self {
Self(n as i128 * SCALE)
}
#[must_use]
pub const fn to_scaled(self) -> i128 {
self.0
}
#[must_use]
pub fn mul_div(self, numerator: Self, denominator: Self) -> Self {
if denominator.0 == 0 {
return Self::ZERO;
}
Self(self.0.saturating_mul(numerator.0) / denominator.0)
}
#[must_use]
pub fn times(self, other: Self) -> Self {
Self(self.0.saturating_mul(other.0) / SCALE)
}
#[must_use]
pub fn ratio(self, other: Self) -> Self {
if other.0 == 0 {
return Self::ZERO;
}
Self(self.0.saturating_mul(SCALE) / other.0)
}
#[must_use]
pub fn min(self, other: Self) -> Self {
if self.0 <= other.0 { self } else { other }
}
#[must_use]
pub const fn is_zero(self) -> bool {
self.0 == 0
}
#[must_use]
pub fn halve_fractional(self, numerator: u64, denominator: u64) -> Self {
if denominator == 0 || self.0 == 0 {
return self;
}
let whole = numerator / denominator;
let mut value = self.0;
for _ in 0..whole.min(127) {
value /= 2;
}
if whole >= 127 {
return Self(0);
}
let remainder = numerator % denominator;
if remainder == 0 {
return Self(value);
}
let frac = i128::from(remainder);
let den = i128::from(denominator);
Self(value - (value * frac) / (den * 2))
}
}
impl Add for Fixed6 {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(self.0.saturating_add(other.0))
}
}
impl Sub for Fixed6 {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self(self.0.saturating_sub(other.0))
}
}
impl Sum for Fixed6 {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self::ZERO, Add::add)
}
}
impl fmt::Display for Fixed6 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let negative = self.0 < 0;
let magnitude = self.0.unsigned_abs();
let whole = magnitude / SCALE.unsigned_abs();
let frac = magnitude % SCALE.unsigned_abs();
if negative {
write!(f, "-")?;
}
write!(f, "{whole}.{frac:06}")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mul_div_keeps_the_scale() {
let two = Fixed6::from_integer(2);
let three = Fixed6::from_integer(3);
assert_eq!(two.mul_div(two, three).to_string(), "1.333333");
let small = Fixed6::from_scaled(3);
assert_eq!(
small.mul_div(Fixed6::from_integer(1000), Fixed6::from_integer(3)),
Fixed6::from_scaled(1000)
);
}
#[test]
fn truncates_toward_zero_rather_than_rounding() {
let one = Fixed6::ONE;
let three = Fixed6::from_integer(3);
assert_eq!(one.ratio(three).to_string(), "0.333333");
let two = Fixed6::from_integer(2);
assert_eq!(two.ratio(three).to_string(), "0.666666");
}
#[test]
fn division_by_zero_yields_zero() {
assert_eq!(Fixed6::ONE.ratio(Fixed6::ZERO), Fixed6::ZERO);
assert_eq!(Fixed6::ONE.mul_div(Fixed6::ONE, Fixed6::ZERO), Fixed6::ZERO);
}
#[test]
fn display_is_stable_to_six_places() {
assert_eq!(Fixed6::ZERO.to_string(), "0.000000");
assert_eq!(Fixed6::ONE.to_string(), "1.000000");
assert_eq!(Fixed6::from_scaled(1).to_string(), "0.000001");
assert_eq!(Fixed6::from_scaled(-1).to_string(), "-0.000001");
}
#[test]
fn halving_is_exact_on_whole_periods() {
let one = Fixed6::ONE;
assert_eq!(one.halve_fractional(0, 10), one);
assert_eq!(one.halve_fractional(10, 10).to_string(), "0.500000");
assert_eq!(one.halve_fractional(20, 10).to_string(), "0.250000");
assert_eq!(one.halve_fractional(1000, 10), Fixed6::ZERO);
}
#[test]
fn addition_saturates_rather_than_wrapping() {
let big = Fixed6::from_scaled(i128::MAX);
assert_eq!(big + big, Fixed6::from_scaled(i128::MAX));
}
}