cnfy-uint 0.2.3

Zero-dependency 256-bit unsigned integer arithmetic for cryptographic applications
Documentation
//! Bitwise AND via the [`BitAnd`] trait.
use super::U384;
use core::ops::BitAnd;

/// Computes the bitwise AND of two 384-bit integers, producing a
/// result where each bit is set only if both corresponding input bits
/// are set.
///
/// Applied independently to each of the six `u64` limbs.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u384::U384;
///
/// let a = U384::from_be_limbs([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
/// let b = U384::from_be_limbs([0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F]);
/// assert_eq!(a & b, U384::from_be_limbs([0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F]));
/// ```
impl BitAnd for U384 {
    type Output = U384;

    #[inline]
    fn bitand(self, rhs: U384) -> U384 {
        U384([
            self.0[0] & rhs.0[0],
            self.0[1] & rhs.0[1],
            self.0[2] & rhs.0[2],
            self.0[3] & rhs.0[3],
            self.0[4] & rhs.0[4],
            self.0[5] & rhs.0[5],
        ])
    }
}

#[cfg(test)]
mod ai_tests {
    use super::*;

    /// AND with self is identity.
    #[test]
    fn self_identity() {
        let a = U384::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0, 0x1111, 0x2222]);
        assert_eq!(a & a, a);
    }

    /// AND with zero is zero.
    #[test]
    fn and_zero() {
        let a = U384::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0, 0x1111, 0x2222]);
        assert_eq!(a & U384::ZERO, U384::ZERO);
    }

    /// AND with MAX is identity.
    #[test]
    fn and_max() {
        let a = U384::from_be_limbs([0x1234, 0x5678, 0x9ABC, 0xDEF0, 0x1111, 0x2222]);
        assert_eq!(a & U384::MAX, a);
    }

    /// AND is commutative.
    #[test]
    fn commutative() {
        let a = U384::from_be_limbs([1, 2, 3, 4, 5, 6]);
        let b = U384::from_be_limbs([7, 8, 9, 10, 11, 12]);
        assert_eq!(a & b, b & a);
    }

    /// Masking extracts specific bits.
    #[test]
    fn mask() {
        let a = U384::from_be_limbs([0xFF00, 0, 0, 0, 0, 0]);
        let mask = U384::from_be_limbs([0x0F00, 0, 0, 0, 0, 0]);
        assert_eq!(a & mask, U384::from_be_limbs([0x0F00, 0, 0, 0, 0, 0]));
    }
}