Skip to main content

crypto_bigint/uint/boxed/
bit_xor.rs

1//! [`BoxedUint`] bitwise XOR operations.
2
3use super::BoxedUint;
4use crate::{BitXor, BitXorAssign, CtOption};
5
6impl BoxedUint {
7    /// Computes bitwise `a ^ b`.
8    #[inline(always)]
9    #[must_use]
10    pub fn bitxor(&self, rhs: &Self) -> Self {
11        Self::map_limbs(self, rhs, crate::limb::Limb::bitxor)
12    }
13
14    /// Perform wrapping bitwise `XOR`.
15    ///
16    /// There's no way wrapping could ever happen.
17    /// This function exists so that all operations are accounted for in the wrapping operations
18    #[must_use]
19    pub fn wrapping_xor(&self, rhs: &Self) -> Self {
20        self.bitxor(rhs)
21    }
22
23    /// Perform checked bitwise `XOR`, returning a [`CtOption`] which `is_some` always
24    #[must_use]
25    pub fn checked_xor(&self, rhs: &Self) -> CtOption<Self> {
26        CtOption::some(self.bitxor(rhs))
27    }
28}
29
30impl BitXor for BoxedUint {
31    type Output = Self;
32
33    fn bitxor(self, rhs: Self) -> BoxedUint {
34        self.bitxor(&rhs)
35    }
36}
37
38impl BitXor<&BoxedUint> for BoxedUint {
39    type Output = BoxedUint;
40
41    fn bitxor(self, rhs: &BoxedUint) -> BoxedUint {
42        Self::bitxor(&self, rhs)
43    }
44}
45
46impl BitXor<BoxedUint> for &BoxedUint {
47    type Output = BoxedUint;
48
49    fn bitxor(self, rhs: BoxedUint) -> BoxedUint {
50        self.bitxor(&rhs)
51    }
52}
53
54impl BitXor<&BoxedUint> for &BoxedUint {
55    type Output = BoxedUint;
56
57    fn bitxor(self, rhs: &BoxedUint) -> BoxedUint {
58        self.bitxor(rhs)
59    }
60}
61
62impl BitXorAssign for BoxedUint {
63    fn bitxor_assign(&mut self, other: Self) {
64        *self = Self::bitxor(self, &other);
65    }
66}
67
68impl BitXorAssign<&BoxedUint> for BoxedUint {
69    fn bitxor_assign(&mut self, other: &Self) {
70        *self = Self::bitxor(self, other);
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use crate::U128;
77
78    #[test]
79    fn checked_xor_ok() {
80        let result = U128::ZERO.checked_xor(&U128::ONE);
81        assert_eq!(result.unwrap(), U128::ONE);
82    }
83
84    #[test]
85    fn overlapping_xor_ok() {
86        let result = U128::ZERO.wrapping_xor(&U128::ONE);
87        assert_eq!(result, U128::ONE);
88    }
89}