//! Count of significant base-2^64 limbs in a [`U256`].
use super::U256;

impl U256 {
    /// Returns the number of significant base-2^64 limbs (1–4).
    ///
    /// Scans the big-endian limbs from the most significant position and
    /// returns how many limbs are needed to represent this value. A zero
    /// value returns 1, matching the convention that at least one digit
    /// is always significant.
    ///
    /// # Examples
    ///
    /// ```
    /// use cnfy_uint::u256::U256;
    ///
    /// assert_eq!(U256::ZERO.sig_limbs(), 1);
    /// assert_eq!(U256::from_be_limbs([0, 0, 0, 42]).sig_limbs(), 1);
    /// assert_eq!(U256::from_be_limbs([0, 0, 1, 0]).sig_limbs(), 2);
    /// assert_eq!(U256::from_be_limbs([1, 0, 0, 0]).sig_limbs(), 4);
    /// ```
    #[inline]
    pub const fn sig_limbs(&self) -> usize {
        if self.0[3] != 0 {
            return 4;
        }
        if self.0[2] != 0 {
            return 3;
        }
        if self.0[1] != 0 {
            return 2;
        }
        1
    }
}

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

    /// Zero has 1 significant limb.
    #[test]
    fn zero() {
        assert_eq!(U256::ZERO.sig_limbs(), 1);
    }

    /// Small value fits in 1 limb.
    #[test]
    fn one_limb() {
        assert_eq!(U256::from_be_limbs([0, 0, 0, 42]).sig_limbs(), 1);
        assert_eq!(U256::from_be_limbs([0, 0, 0, u64::MAX]).sig_limbs(), 1);
    }

    /// Value spanning 2 limbs.
    #[test]
    fn two_limbs() {
        assert_eq!(U256::from_be_limbs([0, 0, 1, 0]).sig_limbs(), 2);
        assert_eq!(
            U256::from_be_limbs([0, 0, u64::MAX, u64::MAX]).sig_limbs(),
            2
        );
    }

    /// Value spanning 3 limbs.
    #[test]
    fn three_limbs() {
        assert_eq!(U256::from_be_limbs([0, 1, 0, 0]).sig_limbs(), 3);
    }

    /// Value spanning all 4 limbs.
    #[test]
    fn four_limbs() {
        assert_eq!(U256::from_be_limbs([1, 0, 0, 0]).sig_limbs(), 4);
        assert_eq!(U256::from_be_limbs([u64::MAX; 4]).sig_limbs(), 4);
    }
}
