rhdl_bits/
xor.rs

1use std::ops::BitXor;
2use std::ops::BitXorAssign;
3
4use crate::bits::Bits;
5use crate::signed_bits::SignedBits;
6
7impl<const N: usize> BitXor<Bits<N>> for u128 {
8    type Output = Bits<N>;
9    fn bitxor(self, rhs: Bits<N>) -> Self::Output {
10        Bits::<N>::from(self) ^ rhs
11    }
12}
13
14impl<const N: usize> BitXor<u128> for Bits<N> {
15    type Output = Self;
16    fn bitxor(self, rhs: u128) -> Self::Output {
17        self ^ Bits::<N>::from(rhs)
18    }
19}
20
21impl<const N: usize> BitXorAssign<u128> for Bits<N> {
22    fn bitxor_assign(&mut self, rhs: u128) {
23        *self = *self ^ rhs;
24    }
25}
26
27impl<const N: usize> BitXor<SignedBits<N>> for i128 {
28    type Output = SignedBits<N>;
29    fn bitxor(self, rhs: SignedBits<N>) -> Self::Output {
30        SignedBits::<N>::from(self) ^ rhs
31    }
32}
33
34impl<const N: usize> BitXor<i128> for SignedBits<N> {
35    type Output = Self;
36    fn bitxor(self, rhs: i128) -> Self::Output {
37        self ^ SignedBits::<N>::from(rhs)
38    }
39}
40
41impl<const N: usize> BitXorAssign<i128> for SignedBits<N> {
42    fn bitxor_assign(&mut self, rhs: i128) {
43        *self = *self ^ rhs;
44    }
45}
46
47#[cfg(test)]
48mod test {
49    use super::*;
50
51    #[test]
52    fn test_xor_bits() {
53        let bits: Bits<8> = 0b1101_1010.into();
54        let result = bits ^ bits;
55        assert_eq!(result.0, 0_u128);
56        let bits: Bits<8> = 0b1101_1010.into();
57        let result = bits ^ 0b1111_0000;
58        assert_eq!(result.0, 0b0010_1010_u128);
59        let bits: Bits<8> = 0b1101_1010.into();
60        let result = 0b1111_0000 ^ bits;
61        assert_eq!(result.0, 0b0010_1010_u128);
62        let mut bits: Bits<128> = 0.into();
63        bits.set_bit(127, true);
64        let result = bits ^ bits;
65        assert_eq!(result.0, 0_u128);
66        let bits: Bits<54> = 0b1101_1010.into();
67        let result = bits ^ 1;
68        assert_eq!(result.0, 0b1101_1011_u128);
69        let result = 1 ^ bits;
70        assert_eq!(result.0, 0b1101_1011_u128);
71        let a: Bits<12> = 0b1010_1010_1010.into();
72        let b: Bits<12> = 0b0110_0100_0000.into();
73        let c: Bits<12> = 0b1100_1110_1010.into();
74        assert_eq!(a ^ b, c);
75    }
76}