Skip to main content

crypto_bigint/uint/boxed/
bit_or.rs

1//! [`BoxedUint`] bitwise OR operations.
2
3use crate::{BitOr, BitOrAssign, BoxedUint, CtOption, Limb};
4
5impl BoxedUint {
6    /// Computes bitwise `a | b`.
7    #[inline(always)]
8    #[must_use]
9    pub fn bitor(&self, rhs: &Self) -> Self {
10        Self::map_limbs(self, rhs, Limb::bitor)
11    }
12
13    /// Perform wrapping bitwise `OR`.
14    ///
15    /// There's no way wrapping could ever happen.
16    /// This function exists so that all operations are accounted for in the wrapping operations
17    #[must_use]
18    pub fn wrapping_or(&self, rhs: &Self) -> Self {
19        self.bitor(rhs)
20    }
21
22    /// Perform checked bitwise `OR`, returning a [`CtOption`] which `is_some` always
23    #[must_use]
24    pub fn checked_or(&self, rhs: &Self) -> CtOption<Self> {
25        CtOption::some(self.bitor(rhs))
26    }
27}
28
29impl BitOr for BoxedUint {
30    type Output = Self;
31
32    fn bitor(self, rhs: Self) -> BoxedUint {
33        self.bitor(&rhs)
34    }
35}
36
37impl BitOr<&BoxedUint> for BoxedUint {
38    type Output = BoxedUint;
39
40    #[allow(clippy::needless_borrow)]
41    fn bitor(self, rhs: &BoxedUint) -> BoxedUint {
42        (&self).bitor(rhs)
43    }
44}
45
46impl BitOr<BoxedUint> for &BoxedUint {
47    type Output = BoxedUint;
48
49    fn bitor(self, rhs: BoxedUint) -> BoxedUint {
50        self.bitor(&rhs)
51    }
52}
53
54impl BitOr<&BoxedUint> for &BoxedUint {
55    type Output = BoxedUint;
56
57    fn bitor(self, rhs: &BoxedUint) -> BoxedUint {
58        self.bitor(rhs)
59    }
60}
61
62impl BitOrAssign for BoxedUint {
63    fn bitor_assign(&mut self, other: Self) {
64        Self::bitor_assign(self, &other);
65    }
66}
67
68impl BitOrAssign<&BoxedUint> for BoxedUint {
69    fn bitor_assign(&mut self, other: &Self) {
70        if other.limbs.len() > self.limbs.len() {
71            self.resize_in_place_unchecked(other.bits_precision());
72        }
73
74        for (a, b) in self.limbs.iter_mut().zip(other.limbs.iter()) {
75            *a |= *b;
76        }
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use crate::{BitOrAssign, BoxedUint, Limb};
83
84    #[test]
85    fn bitor_assign_preserves_wider_rhs_limbs() {
86        let mut lhs = BoxedUint::zero_with_precision(Limb::BITS);
87        let rhs = BoxedUint::max(Limb::BITS * 2);
88        let expected = lhs.bitor(&rhs);
89
90        lhs.bitor_assign(&rhs);
91
92        assert_eq!(lhs, expected);
93    }
94}