cnfy-uint 0.2.3

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

/// Wrapping addition of two 320-bit integers, discarding overflow.
///
/// Delegates to [`U320::overflowing_add`] and returns only the wrapped
/// result. The result wraps on overflow (modular 2^320 arithmetic).
///
/// # Examples
///
/// ```
/// use cnfy_uint::u320::U320;
///
/// let a = U320::from_be_limbs([0, 0, 0, 0, 10]);
/// let b = U320::from_be_limbs([0, 0, 0, 0, 20]);
/// assert_eq!(a + b, U320::from_be_limbs([0, 0, 0, 0, 30]));
/// ```
impl Add for U320 {
    type Output = U320;

    #[inline]
    fn add(self, rhs: U320) -> U320 {
        self.overflowing_add(&rhs).0
    }
}

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

    /// Adding two small values.
    #[test]
    fn small_add() {
        let a = U320::from_be_limbs([0, 0, 0, 0, 10]);
        let b = U320::from_be_limbs([0, 0, 0, 0, 20]);
        assert_eq!(a + b, U320::from_be_limbs([0, 0, 0, 0, 30]));
    }

    /// Adding zero is identity.
    #[test]
    fn add_zero() {
        let a = U320::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0, 0x1111]);
        assert_eq!(a + U320::ZERO, a);
    }

    /// Addition is commutative.
    #[test]
    fn commutative() {
        let a = U320::from_be_limbs([1, 2, 3, 4, 5]);
        let b = U320::from_be_limbs([5, 4, 3, 2, 1]);
        assert_eq!(a + b, b + a);
    }

    /// MAX + 1 wraps to zero.
    #[test]
    fn overflow_wraps() {
        assert_eq!(U320::MAX + U320::ONE, U320::ZERO);
    }

    /// Carry propagation across limbs.
    #[test]
    fn carry_propagation() {
        let a = U320::from_be_limbs([0, 0, 0, 0, u64::MAX]);
        let b = U320::ONE;
        assert_eq!(a + b, U320::from_be_limbs([0, 0, 0, 1, 0]));
    }
}