//! Trailing zero bit count for [`U384`].
use super::U384;

impl U384 {
    /// Returns the number of trailing zero bits in the 384-bit value.
    ///
    /// Returns 384 for the zero value and 0 when the least significant
    /// bit is set.
    ///
    /// # Examples
    ///
    /// ```
    /// use cnfy_uint::u384::U384;
    ///
    /// assert_eq!(U384::ZERO.trailing_zeros(), 384);
    /// assert_eq!(U384::ONE.trailing_zeros(), 0);
    /// assert_eq!(U384::from_be_limbs([0, 0, 0, 0, 0, 8]).trailing_zeros(), 3);
    /// ```
    #[inline]
    pub const fn trailing_zeros(&self) -> u32 {
        let mut i = 0;
        while i < 6 {
            if self.0[i] != 0 {
                return (i as u32) * 64 + self.0[i].trailing_zeros();
            }
            i += 1;
        }
        384
    }
}

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

    /// Zero has 384 trailing zeros.
    #[test]
    fn zero() {
        assert_eq!(U384::ZERO.trailing_zeros(), 384);
    }

    /// One has 0 trailing zeros.
    #[test]
    fn one() {
        assert_eq!(U384::ONE.trailing_zeros(), 0);
    }

    /// MAX has 0 trailing zeros.
    #[test]
    fn max() {
        assert_eq!(U384::MAX.trailing_zeros(), 0);
    }

    /// Power of 2 in LSB limb.
    #[test]
    fn power_of_two_lsb() {
        let v = U384::from_be_limbs([0, 0, 0, 0, 0, 1 << 10]);
        assert_eq!(v.trailing_zeros(), 10);
    }

    /// Power of 2 in limb [4].
    #[test]
    fn power_of_two_limb4() {
        let v = U384::from_be_limbs([0, 0, 0, 0, 1, 0]);
        assert_eq!(v.trailing_zeros(), 64);
    }

    /// Power of 2 in MSB limb.
    #[test]
    fn power_of_two_msb() {
        let v = U384::from_be_limbs([1, 0, 0, 0, 0, 0]);
        assert_eq!(v.trailing_zeros(), 320);
    }

    /// MSB set has 383 trailing zeros after MSB.
    #[test]
    fn msb_set() {
        let v = U384::from_be_limbs([1 << 63, 0, 0, 0, 0, 0]);
        assert_eq!(v.trailing_zeros(), 383);
    }
}
