//! Wrapping addition via the [`Add`] trait.
use super::U512;
use core::ops::Add;

/// Wrapping addition of two 512-bit integers, discarding overflow.
///
/// Delegates to [`U512::overflowing_add`], returning only the 512-bit
/// result. The overflow flag is silently discarded, making this
/// modular `2^512` arithmetic.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u512::U512;
///
/// let a = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 10]);
/// let b = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 20]);
/// assert_eq!(a + b, U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 30]));
/// ```
impl Add for U512 {
    type Output = U512;

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

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

    /// Small values add without overflow.
    #[test]
    fn small_add() {
        let a = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 100]);
        let b = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 200]);
        assert_eq!(a + b, U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 300]));
    }

    /// Adding zero is identity.
    #[test]
    fn additive_identity() {
        let a = U512::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0, 1, 2, 3, 4]);
        assert_eq!(a + U512::ZERO, a);
    }

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

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

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