Skip to main content

crypto_bigint/int/
bit_xor.rs

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