legit-hashes 0.2.1

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! IEEE-754 single precision in integer arithmetic, for `pdq-v1`.
//!
//! Rust's `f32` operations round to single precision after every operation on almost every target,
//! but not all: on 32-bit x86 without SSE2, such as `i586`, they run on the x87 unit and can keep
//! extra precision between operations (rust-lang/rust#114479). A definition that must give the
//! same bits everywhere can't rely on them, so `pdq-v1` computes with [`StrictF32`]: the four
//! operations it needs, each the correctly rounded result IEEE-754 defines, rounding to nearest
//! with ties to even, computed from the bit patterns with integer arithmetic. Comparisons and
//! conversions from small integers are exact on every target, so they use `f32` itself.

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;

/// An `f32`, held as its bit pattern, whose arithmetic is IEEE-754 single precision on every
/// target.
#[derive(Debug, Clone, Copy)]
pub(crate) struct StrictF32(u32);

impl StrictF32 {
    /// Positive zero.
    pub(crate) const ZERO: Self = Self(0);

    /// The value of `value`.
    pub(crate) const fn new(value: f32) -> Self {
        Self(value.to_bits())
    }

    /// The value as an `f32`.
    pub(crate) const fn get(self) -> f32 {
        f32::from_bits(self.0)
    }

    /// The value of a small integer, which `f32` holds exactly.
    pub(crate) fn from_u16(value: u16) -> Self {
        Self::new(f32::from(value))
    }

    /// The value truncated toward zero, for a value whose integer part fits an `i32`.
    pub(crate) fn truncate(self) -> i32 {
        // Converting an exact `f32` to an integer involves no rounding of the value...
        self.get() as i32
    }

    const fn is_nan(self) -> bool {
        self.0 & !SIGN > INFINITY
    }

    const fn is_infinite(self) -> bool {
        self.0 & !SIGN == INFINITY
    }

    /// The sign, and the value as an integer significand times a power of two: `m ยท 2^e`, with `m`
    /// below `2^24`. A finite value only.
    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())
    }
}

/// The `f32` nearest `ยฑm ยท 2^e`, ties to even: `m` is nonzero and below `2^62`.
#[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;
    // The exponent of the last bit kept: 24 bits for a normal result, down to 2^-149 below...
    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 {
        // Far below half the smallest step, so it rounds to zero...
        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 {
        // Subnormal: `last` is -149, and the bits are the significand...
        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 {
            // Zero plus zero is negative only when both are...
            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 {
            // `big` is normal, and `small` is below a quarter of its last bit: the sum rounds to
            // `big`...
            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 {
            // An exact zero is positive when rounding to nearest...
            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);
        }
        // Normalise both significands to 24 bits, so the quotient has 26 or 27...
        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;
        // ...then one more bit, set when anything remains: it decides ties and nothing else.
        let sticky = u64::from(numerator % b != 0);
        round(sign != 0, quotient << 1 | sticky, ea - eb - 27)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Assert the strict result has the bits of the native one, which is IEEE-754 on this target.
    #[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()
                );
            }
        }
    }

    /// A seeded stream of 64-bit numbers.
    #[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)
        }
    }

    // These tests compare with the target's own `f32`, so they prove the strict arithmetic only
    // where that is IEEE-754: everywhere but x86 without SSE2.
    #[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);
        // Operands a few steps apart, so sums cancel and quotients sit near 1; and operands near
        // the ends of the range, so results overflow or turn subnormal...
        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),
            );
        }
        // ...and the values PDQ works with: levels, their sums and means, and the DCT matrix.
        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() {
        // 2^24 + 1 is halfway between 2^24 and 2^24 + 2: it rounds to the even one, 2^24...
        let big = StrictF32::new(16_777_216.0);
        assert_eq!((big + StrictF32::new(1.0)).get(), 16_777_216.0);
        // ...and 2^24 + 3 to 2^24 + 4.
        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);
    }
}