//! Wrapping addition-assignment via the [`AddAssign`] trait.
use super::U256;
use core::ops::AddAssign;

/// Wrapping addition-assignment of two 256-bit integers, discarding overflow.
///
/// Delegates to [`U256::overflowing_add`], updating `self` in place with the
/// 256-bit result. The overflow flag is silently discarded, making this
/// modular `2^256` arithmetic.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u256::U256;
///
/// let mut a = U256::from_be_limbs([0, 0, 0, 10]);
/// a += U256::from_be_limbs([0, 0, 0, 20]);
/// assert_eq!(a, U256::from_be_limbs([0, 0, 0, 30]));
/// ```
impl AddAssign for U256 {
    #[inline]
    fn add_assign(&mut self, rhs: U256) {
        *self = self.overflowing_add(&rhs).0;
    }
}

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

    /// Small values add in place.
    #[test]
    fn small_add_assign() {
        let mut a = U256::from_be_limbs([0, 0, 0, 100]);
        a += U256::from_be_limbs([0, 0, 0, 200]);
        assert_eq!(a, U256::from_be_limbs([0, 0, 0, 300]));
    }

    /// Adding zero leaves value unchanged.
    #[test]
    fn additive_identity() {
        let mut a = U256::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0]);
        let original = a;
        a += U256::ZERO;
        assert_eq!(a, original);
    }

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

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

    /// Equivalent to Add trait.
    #[test]
    fn matches_add() {
        let a = U256::from_be_limbs([1, 2, 3, 4]);
        let b = U256::from_be_limbs([5, 6, 7, 8]);
        let mut c = a;
        c += b;
        assert_eq!(c, a + b);
    }
}
