use std::cmp::Ordering;
use std::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign};
const SIGN: u32 = 0x8000_0000;
const INFINITY: u32 = 0x7f80_0000;
const NAN: u32 = 0x7fc0_0000;
#[derive(Debug, Clone, Copy)]
pub(crate) struct StrictF32(u32);
impl StrictF32 {
pub(crate) const ZERO: Self = Self(0);
pub(crate) const fn new(value: f32) -> Self {
Self(value.to_bits())
}
pub(crate) const fn get(self) -> f32 {
f32::from_bits(self.0)
}
pub(crate) fn from_u16(value: u16) -> Self {
Self::new(f32::from(value))
}
pub(crate) fn truncate(self) -> i32 {
self.get() as i32
}
const fn is_nan(self) -> bool {
self.0 & !SIGN > INFINITY
}
const fn is_infinite(self) -> bool {
self.0 & !SIGN == INFINITY
}
const fn unpack(self) -> (bool, u64, i32) {
let sign = self.0 & SIGN != 0;
let biased = ((self.0 >> 23) & 0xff) as i32;
let fraction = (self.0 & 0x7f_ffff) as u64;
if biased == 0 {
(sign, fraction, -149)
} else {
(sign, fraction | 1 << 23, biased - 150)
}
}
}
impl PartialEq for StrictF32 {
fn eq(&self, other: &Self) -> bool {
self.get() == other.get()
}
}
impl PartialOrd for StrictF32 {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.get().partial_cmp(&other.get())
}
}
#[inline]
fn round(negative: bool, m: u64, e: i32) -> StrictF32 {
let sign = if negative { SIGN } else { 0 };
let length = 64 - m.leading_zeros() as i32;
let mut last = (e + length - 1 - 23).max(-149);
let shift = last - e;
let mut kept = if shift <= 0 {
m << -shift
} else if shift > 63 {
0
} else {
let kept = m >> shift;
let dropped = m & ((1 << shift) - 1);
let half = 1 << (shift - 1);
if dropped > half || (dropped == half && kept & 1 == 1) {
kept + 1
} else {
kept
}
};
if kept == 1 << 24 {
kept >>= 1;
last += 1;
}
if kept == 0 {
return StrictF32(sign);
}
if kept < 1 << 23 {
return StrictF32(sign | kept as u32);
}
let biased = last + 150;
if biased >= 255 {
return StrictF32(sign | INFINITY);
}
StrictF32(sign | (biased as u32) << 23 | (kept as u32 & 0x7f_ffff))
}
impl Add for StrictF32 {
type Output = Self;
#[inline]
fn add(self, other: Self) -> Self {
if self.is_nan() || other.is_nan() {
return Self(NAN);
}
if self.is_infinite() {
let opposite = other.is_infinite() && (self.0 ^ other.0) & SIGN != 0;
return if opposite { Self(NAN) } else { self };
}
if other.is_infinite() {
return other;
}
let (a, b) = (self.unpack(), other.unpack());
if a.1 == 0 {
return if b.1 == 0 { Self(self.0 & other.0) } else { other };
}
if b.1 == 0 {
return self;
}
let (big, small, big_value) = if a.2 >= b.2 { (a, b, self) } else { (b, a, other) };
let gap = big.2 - small.2;
if gap >= 26 {
return big_value;
}
let signed = |(negative, m, _): (bool, u64, i32), shift: i32| {
let magnitude = (m << shift) as i64;
if negative { -magnitude } else { magnitude }
};
let sum = signed(big, gap) + signed(small, 0);
if sum == 0 {
return Self::ZERO;
}
round(sum < 0, sum.unsigned_abs(), small.2)
}
}
impl Sub for StrictF32 {
type Output = Self;
#[inline]
fn sub(self, other: Self) -> Self {
self + Self(other.0 ^ SIGN)
}
}
impl AddAssign for StrictF32 {
fn add_assign(&mut self, other: Self) {
*self = *self + other;
}
}
impl SubAssign for StrictF32 {
fn sub_assign(&mut self, other: Self) {
*self = *self - other;
}
}
impl Mul for StrictF32 {
type Output = Self;
#[inline]
fn mul(self, other: Self) -> Self {
if self.is_nan() || other.is_nan() {
return Self(NAN);
}
let sign = (self.0 ^ other.0) & SIGN;
let zero = |value: Self| value.0 & !SIGN == 0;
if self.is_infinite() || other.is_infinite() {
return if zero(self) || zero(other) {
Self(NAN)
} else {
Self(sign | INFINITY)
};
}
let (a, b) = (self.unpack(), other.unpack());
if a.1 == 0 || b.1 == 0 {
return Self(sign);
}
round(sign != 0, a.1 * b.1, a.2 + b.2)
}
}
impl Div for StrictF32 {
type Output = Self;
#[inline]
fn div(self, other: Self) -> Self {
if self.is_nan() || other.is_nan() {
return Self(NAN);
}
let sign = (self.0 ^ other.0) & SIGN;
if self.is_infinite() {
return if other.is_infinite() {
Self(NAN)
} else {
Self(sign | INFINITY)
};
}
if other.is_infinite() {
return Self(sign);
}
let (a, b) = (self.unpack(), other.unpack());
if b.1 == 0 {
return if a.1 == 0 { Self(NAN) } else { Self(sign | INFINITY) };
}
if a.1 == 0 {
return Self(sign);
}
let normalise = |(_, m, e): (bool, u64, i32)| {
let shift = m.leading_zeros() as i32 - 40;
(m << shift, e - shift)
};
let ((a, ea), (b, eb)) = (normalise(a), normalise(b));
let numerator = a << 26;
let quotient = numerator / b;
let sticky = u64::from(numerator % b != 0);
round(sign != 0, quotient << 1 | sticky, ea - eb - 27)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(all(target_arch = "x86", not(target_feature = "sse2"))))]
fn check(a: f32, b: f32) {
let (x, y) = (StrictF32::new(a), StrictF32::new(b));
for (name, strict, native) in [
("+", x + y, a + b),
("-", x - y, a - b),
("*", x * y, a * b),
("/", x / y, a / b),
] {
if native.is_nan() {
assert!(strict.get().is_nan(), "{a:e} {name} {b:e}");
} else {
assert_eq!(
strict.0,
native.to_bits(),
"{a:e} ({:08x}) {name} {b:e} ({:08x})",
a.to_bits(),
b.to_bits()
);
}
}
}
#[cfg(not(all(target_arch = "x86", not(target_feature = "sse2"))))]
struct Stream(u64);
#[cfg(not(all(target_arch = "x86", not(target_feature = "sse2"))))]
impl Stream {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
}
#[cfg(not(all(target_arch = "x86", not(target_feature = "sse2"))))]
#[test]
fn every_operation_matches_ieee_754_on_random_bit_patterns() {
let mut stream = Stream(1);
for _ in 0..300_000 {
let bits = stream.next();
check(f32::from_bits(bits as u32), f32::from_bits((bits >> 32) as u32));
}
}
#[cfg(not(all(target_arch = "x86", not(target_feature = "sse2"))))]
#[test]
fn every_operation_matches_ieee_754_on_close_and_awkward_operands() {
let mut stream = Stream(2);
for _ in 0..300_000 {
let bits = stream.next();
let a = bits as u32;
let near = a.wrapping_add((bits >> 40) as u32 % 64).wrapping_sub(32) ^ ((bits >> 39) as u32 & SIGN);
check(f32::from_bits(a), f32::from_bits(near));
let exponent = |shift: u32| ((bits >> shift) as u32 % 256) << 23;
let small = (a & 0x807f_ffff) | exponent(32).min(40 << 23);
let large = (a.rotate_left(7) & 0x807f_ffff) | exponent(48).max(200 << 23);
check(f32::from_bits(small), f32::from_bits(large));
check(
f32::from_bits(small),
f32::from_bits(small.rotate_left(3) & 0x80ff_ffff),
);
}
for _ in 0..300_000 {
let bits = stream.next();
let level = (bits % 256) as f32 * 0.587 + ((bits >> 8) % 256) as f32;
let window = ((bits >> 16) % 600) as f32;
let small = f32::from_bits(0x3c00_0000 | (bits >> 32) as u32 & 0x03ff_ffff);
check(level, window);
check(level, small);
check(level * 100.0, 255.0);
}
let special = [
0.0,
-0.0,
1.0,
-1.0,
f32::MIN_POSITIVE,
f32::from_bits(1),
f32::from_bits(0x807f_ffff),
f32::MAX,
-f32::MAX,
f32::INFINITY,
f32::NEG_INFINITY,
f32::NAN,
1.0 + f32::EPSILON,
0.5 - f32::EPSILON / 4.0,
3.0,
255.0,
];
for a in special {
for b in special {
check(a, b);
}
}
}
#[test]
fn ties_round_to_even() {
let big = StrictF32::new(16_777_216.0);
assert_eq!((big + StrictF32::new(1.0)).get(), 16_777_216.0);
assert_eq!((big + StrictF32::new(3.0)).get(), 16_777_220.0);
assert_eq!((StrictF32::new(1.0) / StrictF32::new(3.0)).0, 0x3eaa_aaab);
assert_eq!((StrictF32::new(0.1) * StrictF32::new(3.0)).0, 0x3e99_999a);
assert_eq!(StrictF32::new(2.5).truncate(), 2);
assert_eq!(StrictF32::new(-2.5).truncate(), -2);
assert!(StrictF32::new(-1.0) < StrictF32::ZERO);
assert_eq!(StrictF32::new(-0.0), StrictF32::ZERO);
}
}