cnfy-uint 0.2.3

Zero-dependency 256-bit unsigned integer arithmetic for cryptographic applications
Documentation
//! Wrapping subtraction via the [`Sub`] trait.
use super::U384;
use core::ops::Sub;

/// Wrapping subtraction of two 384-bit integers, wrapping on underflow.
///
/// Delegates to [`U384::overflowing_sub`], returning only the 384-bit
/// result. The underflow flag is silently discarded, making this
/// modular `2^384` arithmetic.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u384::U384;
///
/// let a = U384::from_be_limbs([0, 0, 0, 0, 0, 10]);
/// let b = U384::from_be_limbs([0, 0, 0, 0, 0, 3]);
/// assert_eq!(a - b, U384::from_be_limbs([0, 0, 0, 0, 0, 7]));
/// ```
impl Sub for U384 {
    type Output = U384;

    #[inline]
    fn sub(self, rhs: U384) -> U384 {
        self.overflowing_sub(&rhs).0
    }
}

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

    /// Small values subtract without underflow.
    #[test]
    fn small_sub() {
        let a = U384::from_be_limbs([0, 0, 0, 0, 0, 10]);
        let b = U384::from_be_limbs([0, 0, 0, 0, 0, 3]);
        assert_eq!(a - b, U384::from_be_limbs([0, 0, 0, 0, 0, 7]));
    }

    /// Subtracting zero is identity.
    #[test]
    fn subtractive_identity() {
        let a = U384::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0, 0x1111, 0x2222]);
        assert_eq!(a - U384::ZERO, a);
    }

    /// Self minus self is zero.
    #[test]
    fn self_cancellation() {
        let a = U384::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0, 0x1111, 0x2222]);
        assert_eq!(a - a, U384::ZERO);
    }

    /// 0 - 1 wraps to MAX.
    #[test]
    fn underflow_wraps() {
        assert_eq!(U384::ZERO - U384::ONE, U384::MAX);
    }

    /// Borrow propagates across all limbs.
    #[test]
    fn borrow_propagation() {
        let a = U384::from_be_limbs([1, 0, 0, 0, 0, 0]);
        let b = U384::from_be_limbs([0, 0, 0, 0, 0, 1]);
        assert_eq!(
            a - b,
            U384::from_be_limbs([0, u64::MAX, u64::MAX, u64::MAX, u64::MAX, u64::MAX]),
        );
    }
}