1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//! 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);
}
}
}