1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//! Wrapping addition via the [`Add`] trait.
use super::U256;
use core::ops::Add;
/// Wrapping addition of two 256-bit integers, discarding overflow.
///
/// Delegates to [`U256::overflowing_add`], returning only the 256-bit
/// result. The overflow flag is silently discarded, making this
/// modular `2^256` arithmetic — consistent with how primitive types
/// behave under `wrapping_add`.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u256::U256;
///
/// let a = U256::from_be_limbs([0, 0, 0, 10]);
/// let b = U256::from_be_limbs([0, 0, 0, 20]);
/// assert_eq!(a + b, U256::from_be_limbs([0, 0, 0, 30]));
/// ```
impl Add for U256 {
type Output = U256;
#[inline]
fn add(self, rhs: U256) -> U256 {
self.overflowing_add(&rhs).0
}
}
#[cfg(test)]
mod ai_tests {
use super::*;
/// Small values add without overflow.
#[test]
fn small_add() {
let a = U256::from_be_limbs([0, 0, 0, 100]);
let b = U256::from_be_limbs([0, 0, 0, 200]);
assert_eq!(a + b, U256::from_be_limbs([0, 0, 0, 300]));
}
/// Adding zero is identity.
#[test]
fn additive_identity() {
let a = U256::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0]);
assert_eq!(a + U256::ZERO, a);
}
/// MAX + 1 wraps to zero.
#[test]
fn overflow_wraps() {
assert_eq!(U256::MAX + U256::ONE, U256::ZERO);
}
/// Carry propagates across all limbs.
#[test]
fn carry_propagation() {
let a = U256::from_be_limbs([0, 0, 0, u64::MAX]);
let b = U256::from_be_limbs([0, 0, 0, 1]);
assert_eq!(a + b, U256::from_be_limbs([0, 0, 1, 0]));
}
/// Addition is commutative.
#[test]
fn commutative() {
let a = U256::from_be_limbs([1, 2, 3, 4]);
let b = U256::from_be_limbs([5, 6, 7, 8]);
assert_eq!(a + b, b + a);
}
}