vouch-core 4.2.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
//! The few `f64` operations the core needs that live in `std`, not `core`.
//!
//! With `std` each one calls the standard method, so nothing changes there.
//! Without `std` they are written out here. All five are exact operations
//! (IEEE 754 requires a correctly rounded square root), so the software
//! versions give the same bits as the standard ones; the tests below check
//! that against `std` on a large spread of inputs.
//!
//! Functions that need transcendental math (`powf`, `acos`, `sin`, `cosh`)
//! have no exact definition to copy, so they stay in the `std` build and their
//! callers refuse in a `no_std` build instead of computing a different value.

#[allow(unused_imports)]
use crate::prelude::*;

/// Square root.
#[cfg(feature = "std")]
#[inline]
pub(crate) fn sqrt(x: f64) -> f64 {
    x.sqrt()
}

/// Square root.
#[cfg(not(feature = "std"))]
#[inline]
pub(crate) fn sqrt(x: f64) -> f64 {
    soft_sqrt(x)
}

/// Round toward zero.
#[cfg(feature = "std")]
#[inline]
pub(crate) fn trunc(x: f64) -> f64 {
    x.trunc()
}

/// Round toward zero.
#[cfg(not(feature = "std"))]
#[inline]
pub(crate) fn trunc(x: f64) -> f64 {
    soft_trunc(x)
}

/// The fractional part, `x - trunc(x)`.
#[cfg(feature = "std")]
#[inline]
pub(crate) fn fract(x: f64) -> f64 {
    x.fract()
}

/// The fractional part, `x - trunc(x)`.
#[cfg(not(feature = "std"))]
#[inline]
pub(crate) fn fract(x: f64) -> f64 {
    x - soft_trunc(x)
}

/// Round toward negative infinity.
#[cfg(feature = "std")]
#[inline]
pub(crate) fn floor(x: f64) -> f64 {
    x.floor()
}

/// Round toward negative infinity.
#[cfg(not(feature = "std"))]
#[inline]
pub(crate) fn floor(x: f64) -> f64 {
    soft_floor(x)
}

/// `x` to a small integer power.
#[cfg(feature = "std")]
#[inline]
pub(crate) fn powi(x: f64, n: i32) -> f64 {
    x.powi(n)
}

/// `x` to a small integer power.
#[cfg(not(feature = "std"))]
#[inline]
pub(crate) fn powi(x: f64, n: i32) -> f64 {
    soft_powi(x, n)
}

/// Correctly rounded square root (round half to even) from integer
/// arithmetic.
#[cfg_attr(feature = "std", allow(dead_code))]
pub(crate) fn soft_sqrt(x: f64) -> f64 {
    if x.is_nan() || x == 0.0 || x == f64::INFINITY {
        return x; // NaN, +0, -0 and +inf are their own square roots.
    }
    if x < 0.0 {
        return f64::NAN;
    }
    let bits = x.to_bits();
    let field = ((bits >> 52) & 0x7ff) as i32;
    let frac = bits & ((1u64 << 52) - 1);
    // x = m * 2^e with m a 53-bit integer (top bit at bit 52).
    let (mut m, mut e) = if field == 0 {
        (frac, -1074)
    } else {
        (frac | (1u64 << 52), field - 1075)
    };
    while m < (1u64 << 52) {
        m <<= 1;
        e -= 1;
    }
    // Make the exponent even, so sqrt(2^e) is exact.
    if e & 1 != 0 {
        m <<= 1;
        e -= 1;
    }
    // m is in [2^52, 2^54), so r = isqrt(m * 2^52) is in [2^52, 2^53).
    let big = (m as u128) << 52;
    let mut r = isqrt_u128(big);
    let rem = big - r * r;
    // The true root is r + f with 0 <= f < 1. Round up when f > 1/2, which is
    // rem > r; f is never exactly 1/2 for an integer radicand.
    if rem > r {
        r += 1;
    }
    let mut p = (e - 52) / 2;
    if r == (1u128 << 53) {
        r >>= 1;
        p += 1;
    }
    // The root of a positive finite double is always a normal number.
    let field = (p + 52 + 1023) as u64;
    f64::from_bits((field << 52) | ((r as u64) & ((1u64 << 52) - 1)))
}

/// Floor of the square root of a 128-bit integer (bit by bit).
fn isqrt_u128(n: u128) -> u128 {
    let mut rem = n;
    let mut root: u128 = 0;
    let mut bit: u128 = 1u128 << 126;
    while bit > rem {
        bit >>= 2;
    }
    while bit != 0 {
        if rem >= root + bit {
            rem -= root + bit;
            root = (root >> 1) + bit;
        } else {
            root >>= 1;
        }
        bit >>= 2;
    }
    root
}

/// Round toward zero by clearing the fraction bits.
#[cfg_attr(feature = "std", allow(dead_code))]
pub(crate) fn soft_trunc(x: f64) -> f64 {
    let bits = x.to_bits();
    let e = ((bits >> 52) & 0x7ff) as i32 - 1023;
    if e >= 52 {
        return x; // already an integer, or inf / NaN
    }
    if e < 0 {
        return f64::from_bits(bits & (1u64 << 63)); // |x| < 1: a signed zero
    }
    let mask = (1u64 << (52 - e)) - 1;
    f64::from_bits(bits & !mask)
}

/// Round toward negative infinity from [`soft_trunc`]: a negative number
/// with a fractional part goes one lower (exact, since it is below 2^52).
#[cfg_attr(feature = "std", allow(dead_code))]
pub(crate) fn soft_floor(x: f64) -> f64 {
    let t = soft_trunc(x);
    if x < t {
        t - 1.0
    } else {
        t
    }
}

/// Integer power by repeated squaring, the same sequence of multiplications
/// as the `powi` the compiler uses (compiler-rt `__powidf2`).
#[cfg_attr(feature = "std", allow(dead_code))]
pub(crate) fn soft_powi(mut a: f64, n: i32) -> f64 {
    let recip = n < 0;
    let mut b = n;
    let mut r = 1.0;
    loop {
        if b & 1 != 0 {
            r *= a;
        }
        b /= 2;
        if b == 0 {
            break;
        }
        a *= a;
    }
    if recip {
        1.0 / r
    } else {
        r
    }
}

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

    /// A small deterministic generator, so the spread of inputs is the same
    /// on every run.
    fn xorshift(state: &mut u64) -> u64 {
        let mut x = *state;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        *state = x;
        x
    }

    fn samples() -> Vec<f64> {
        let mut out = vec![
            0.0,
            -0.0,
            1.0,
            2.0,
            0.25,
            0.5,
            3.0,
            1e-300,
            1e300,
            f64::MIN_POSITIVE,
            f64::MAX,
            f64::EPSILON,
            5e-324,
            1.5e-320,
            4503599627370495.5,
            4503599627370496.0,
            -4503599627370495.5,
            0.9999999999999999,
            -0.9999999999999999,
            123456.789,
            -123456.789,
            6378137.0,
            398600.4418e9,
            f64::INFINITY,
            f64::NEG_INFINITY,
        ];
        let mut s = 0x9e37_79b9_7f4a_7c15u64;
        for _ in 0..200_000 {
            let bits = xorshift(&mut s);
            let x = f64::from_bits(bits);
            if !x.is_nan() {
                out.push(x);
            }
            // Ordinary magnitudes too, where the robot geometry lives.
            out.push((xorshift(&mut s) as f64 / u64::MAX as f64 - 0.5) * 1e8);
        }
        out
    }

    #[test]
    fn soft_sqrt_matches_std_bit_for_bit() {
        for x in samples() {
            let want = x.sqrt();
            let got = soft_sqrt(x);
            if want.is_nan() {
                assert!(got.is_nan(), "sqrt({x:e})");
            } else {
                assert_eq!(got.to_bits(), want.to_bits(), "sqrt({x:e})");
            }
        }
    }

    #[test]
    fn soft_trunc_and_fract_match_std_bit_for_bit() {
        for x in samples() {
            assert_eq!(soft_trunc(x).to_bits(), x.trunc().to_bits(), "trunc({x:e})");
            let (got, want) = (x - soft_trunc(x), x.fract());
            if want.is_nan() {
                assert!(got.is_nan());
            } else {
                assert_eq!(got.to_bits(), want.to_bits(), "fract({x:e})");
            }
        }
        assert!(soft_trunc(f64::NAN).is_nan());
    }

    #[test]
    fn soft_floor_matches_std_bit_for_bit() {
        for x in samples() {
            assert_eq!(soft_floor(x).to_bits(), x.floor().to_bits(), "floor({x:e})");
        }
        assert!(soft_floor(f64::NAN).is_nan());
    }

    #[test]
    fn soft_powi_matches_std_for_the_powers_used() {
        for x in samples() {
            for n in [2, 3] {
                let (got, want) = (soft_powi(x, n), x.powi(n));
                if want.is_nan() {
                    assert!(got.is_nan());
                } else {
                    assert_eq!(got.to_bits(), want.to_bits(), "powi({x:e}, {n})");
                }
            }
        }
    }
}