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
//! 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]));
}
}