cnfy-uint 0.2.3

Zero-dependency 256-bit unsigned integer arithmetic for cryptographic applications
Documentation
//! Count of significant base-2^64 limbs in a [`U512`].
use super::U512;

impl U512 {
    /// Returns the number of significant base-2^64 limbs (1-8).
    ///
    /// 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::u512::U512;
    ///
    /// assert_eq!(U512::ZERO.sig_limbs(), 1);
    /// assert_eq!(U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 42]).sig_limbs(), 1);
    /// assert_eq!(U512::from_be_limbs([0, 0, 0, 0, 0, 0, 1, 0]).sig_limbs(), 2);
    /// assert_eq!(U512::from_be_limbs([1, 0, 0, 0, 0, 0, 0, 0]).sig_limbs(), 8);
    /// ```
    #[inline]
    pub const fn sig_limbs(&self) -> usize {
        if self.0[7] != 0 { return 8; }
        if self.0[6] != 0 { return 7; }
        if self.0[5] != 0 { return 6; }
        if self.0[4] != 0 { return 5; }
        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!(U512::ZERO.sig_limbs(), 1);
    }

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

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

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

    /// Value spanning all 8 limbs.
    #[test]
    fn eight_limbs() {
        assert_eq!(U512::from_be_limbs([1, 0, 0, 0, 0, 0, 0, 0]).sig_limbs(), 8);
        assert_eq!(U512::MAX.sig_limbs(), 8);
    }

    /// Each limb count from 1 to 8.
    #[test]
    fn each_count() {
        for i in 0..8 {
            let mut limbs = [0u64; 8];
            limbs[i] = 1;
            assert_eq!(U512::from_be_limbs(limbs).sig_limbs(), 8 - i);
        }
    }
}