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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//! Uppercase hexadecimal formatting via [`fmt::UpperHex`].
use super::U512;
use core::fmt;
/// Formats a [`U512`] as an uppercase hexadecimal string without leading
/// zeros (except for the value zero itself, which formats as `"0"`).
///
/// Supports the `#` alternate flag for a `0x` prefix, matching the
/// standard library convention for integer types.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u512::U512;
///
/// let v = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 255]);
/// assert_eq!(format!("{:X}", v), "FF");
/// assert_eq!(format!("{:#X}", v), "0xFF");
/// ```
impl fmt::UpperHex for U512 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Find the first non-zero limb scanning from MSB (index 7) down.
let mut first_nonzero = None;
let mut i = 7i32;
while i >= 0 {
if self.0[i as usize] != 0 {
first_nonzero = Some(i as usize);
break;
}
i -= 1;
}
match first_nonzero {
None => {
if f.alternate() {
f.write_str("0x0")
} else {
f.write_str("0")
}
}
Some(idx) => {
if f.alternate() {
f.write_str("0x")?;
}
write!(f, "{:X}", self.0[idx])?;
let mut j = idx;
while j > 0 {
j -= 1;
write!(f, "{:016X}", self.0[j])?;
}
Ok(())
}
}
}
}
#[cfg(test)]
mod ai_tests {
use super::*;
/// Zero formats as "0".
#[test]
fn zero() {
assert_eq!(format!("{:X}", U512::from_be_limbs([0; 8])), "0");
}
/// Zero with alternate flag formats as "0x0".
#[test]
fn zero_alternate() {
assert_eq!(format!("{:#X}", U512::from_be_limbs([0; 8])), "0x0");
}
/// Small value formats without leading zeros in uppercase.
#[test]
fn small_value() {
let v = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 255]);
assert_eq!(format!("{:X}", v), "FF");
}
/// Value spanning two limbs shows full padding on lower limb.
#[test]
fn two_limbs() {
let v = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 1, 0]);
assert_eq!(format!("{:X}", v), "10000000000000000");
}
/// MAX value fills all 128 hex digits.
#[test]
fn max_value() {
let s = format!("{:X}", U512::MAX);
assert_eq!(s.len(), 128);
assert!(s.chars().all(|c| c == 'F'));
}
/// Alternate flag adds 0x prefix.
#[test]
fn alternate_prefix() {
let v = U512::from_be_limbs([0, 0, 0, 0, 0, 0, 0, 0xAB]);
assert_eq!(format!("{:#X}", v), "0xAB");
}
/// ONE formats as "1".
#[test]
fn one() {
assert_eq!(format!("{:X}", U512::ONE), "1");
}
/// Value in the MSB limb only.
#[test]
fn msb_limb() {
let v = U512::from_be_limbs([0xCAFE, 0, 0, 0, 0, 0, 0, 0]);
let s = format!("{:X}", v);
assert!(s.starts_with("CAFE"));
assert_eq!(s.len(), 4 + 7 * 16); // 4 digits + 7 * 16 zero-padded limbs
}
}