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

impl U320 {
    /// Returns the number of bits needed to represent this value, i.e.
    /// `320 - leading_zeros()`.
    ///
    /// Returns 0 for zero, and at most 320 for the maximum value.
    ///
    /// # Examples
    ///
    /// ```
    /// use cnfy_uint::u320::U320;
    ///
    /// assert_eq!(U320::ZERO.bit_len(), 0);
    /// assert_eq!(U320::ONE.bit_len(), 1);
    /// assert_eq!(U320::MAX.bit_len(), 320);
    /// ```
    #[inline]
    pub const fn bit_len(&self) -> u32 {
        320 - self.leading_zeros()
    }
}

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

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

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

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

    /// Powers of two have bit_len = exponent + 1.
    #[test]
    fn powers_of_two() {
        assert_eq!(U320::from_be_limbs([0, 0, 0, 0, 2]).bit_len(), 2);
        assert_eq!(U320::from_be_limbs([0, 0, 0, 0, 0x100]).bit_len(), 9);
        assert_eq!(U320::from_be_limbs([0, 0, 0, 1, 0]).bit_len(), 65);
        assert_eq!(U320::from_be_limbs([0, 0, 1, 0, 0]).bit_len(), 129);
        assert_eq!(U320::from_be_limbs([0, 1, 0, 0, 0]).bit_len(), 193);
        assert_eq!(U320::from_be_limbs([1, 0, 0, 0, 0]).bit_len(), 257);
    }

    /// Consistent with leading_zeros.
    #[test]
    fn consistent_with_leading_zeros() {
        let v = U320::from_be_limbs([0, 0, 0xFF, 0, 0]);
        assert_eq!(v.bit_len() + v.leading_zeros(), 320);
    }
}
