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
71
72
73
74
75
76
77
//! Bitwise XOR via the [`BitXor`] trait.
use super::U256;
use core::ops::BitXor;
/// Computes the bitwise exclusive OR of two 256-bit integers, producing
/// a result where each bit is set if exactly one of the corresponding
/// input bits is set.
///
/// Applied independently to each of the four `u64` limbs.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u256::U256;
///
/// let a = U256::from_be_limbs([0xFF, 0, 0, 0]);
/// let b = U256::from_be_limbs([0x0F, 0, 0, 0]);
/// assert_eq!(a ^ b, U256::from_be_limbs([0xF0, 0, 0, 0]));
/// ```
impl BitXor for U256 {
type Output = U256;
#[inline]
fn bitxor(self, rhs: U256) -> U256 {
U256([
self.0[0] ^ rhs.0[0],
self.0[1] ^ rhs.0[1],
self.0[2] ^ rhs.0[2],
self.0[3] ^ rhs.0[3],
])
}
}
#[cfg(test)]
mod ai_tests {
use super::*;
/// XOR with self is zero.
#[test]
fn self_cancellation() {
let a = U256::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0]);
assert_eq!(a ^ a, U256::ZERO);
}
/// XOR with zero is identity.
#[test]
fn xor_zero() {
let a = U256::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0]);
assert_eq!(a ^ U256::ZERO, a);
}
/// XOR with MAX flips all bits.
#[test]
fn xor_max() {
let a = U256::from_be_limbs([0, 0, 0, 0xFF]);
assert_eq!(
a ^ U256::MAX,
U256::from_be_limbs([u64::MAX, u64::MAX, u64::MAX, u64::MAX ^ 0xFF]),
);
}
/// Double XOR is identity.
#[test]
fn double_xor() {
let a = U256::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0]);
let b = U256::from_be_limbs([0xAAAA, 0xBBBB, 0xCCCC, 0xDDDD]);
assert_eq!((a ^ b) ^ b, a);
}
/// XOR 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);
}
}