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
//! 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);
}
}