//! Bit length computation for [`U384`].
use super::U384;

impl U384 {
    /// Returns the minimum number of bits needed to represent the value,
    /// defined as `384 - leading_zeros()`.
    ///
    /// Returns 0 for the zero value.
    ///
    /// # Examples
    ///
    /// ```
    /// use cnfy_uint::u384::U384;
    ///
    /// assert_eq!(U384::ZERO.bit_len(), 0);
    /// assert_eq!(U384::ONE.bit_len(), 1);
    /// assert_eq!(U384::MAX.bit_len(), 384);
    /// ```
    #[inline]
    pub const fn bit_len(&self) -> u32 {
        384 - self.leading_zeros()
    }
}

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

    /// Zero has bit length 0.
    #[test]
    fn zero() {
        assert_eq!(U384::ZERO.bit_len(), 0);
    }

    /// One has bit length 1.
    #[test]
    fn one() {
        assert_eq!(U384::ONE.bit_len(), 1);
    }

    /// MAX has bit length 384.
    #[test]
    fn max() {
        assert_eq!(U384::MAX.bit_len(), 384);
    }

    /// Powers of two have bit_len = exponent + 1.
    #[test]
    fn powers_of_two() {
        // 2^63 is in limb [5]
        let v = U384::from_be_limbs([0, 0, 0, 0, 0, 1 << 63]);
        assert_eq!(v.bit_len(), 64);

        // 2^64 is in limb [4]
        let v = U384::from_be_limbs([0, 0, 0, 0, 1, 0]);
        assert_eq!(v.bit_len(), 65);

        // 2^383 is MSB of limb [0]
        let v = U384::from_be_limbs([1 << 63, 0, 0, 0, 0, 0]);
        assert_eq!(v.bit_len(), 384);
    }

    /// 255 (0xFF) has bit length 8.
    #[test]
    fn byte_value() {
        let v = U384::from_be_limbs([0, 0, 0, 0, 0, 0xFF]);
        assert_eq!(v.bit_len(), 8);
    }
}
