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
//! Serialization of a [`U384`] into a 48-byte big-endian array.
use super::U384;
impl U384 {
/// Returns the 48-byte big-endian representation of this value.
///
/// Byte `[0]` is the most significant and byte `[47]` is the least
/// significant. Each limb is serialized via `u64::to_be_bytes`,
/// reading from MSB (internal index 5) down to LSB (internal index 0).
///
/// This is functionally identical to `Into<[u8; 48]>` but available
/// as a `const fn` method on `&self`.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u384::U384;
///
/// let v = U384::from_be_limbs([0, 0, 0, 0, 0, 1]);
/// let bytes = v.to_be_bytes();
/// assert_eq!(bytes[47], 1);
/// assert_eq!(bytes[0], 0);
/// ```
#[inline]
pub const fn to_be_bytes(&self) -> [u8; 48] {
let w0 = self.0[5].to_be_bytes();
let w1 = self.0[4].to_be_bytes();
let w2 = self.0[3].to_be_bytes();
let w3 = self.0[2].to_be_bytes();
let w4 = self.0[1].to_be_bytes();
let w5 = self.0[0].to_be_bytes();
[
w0[0], w0[1], w0[2], w0[3], w0[4], w0[5], w0[6], w0[7],
w1[0], w1[1], w1[2], w1[3], w1[4], w1[5], w1[6], w1[7],
w2[0], w2[1], w2[2], w2[3], w2[4], w2[5], w2[6], w2[7],
w3[0], w3[1], w3[2], w3[3], w3[4], w3[5], w3[6], w3[7],
w4[0], w4[1], w4[2], w4[3], w4[4], w4[5], w4[6], w4[7],
w5[0], w5[1], w5[2], w5[3], w5[4], w5[5], w5[6], w5[7],
]
}
}
#[cfg(test)]
mod ai_tests {
use super::*;
/// Round-trip: from_be_bytes then to_be_bytes returns the original.
#[test]
fn round_trip() {
let mut bytes = [0u8; 48];
bytes[0] = 0xAB;
bytes[23] = 0xCD;
bytes[47] = 0xEF;
let v = U384::from_be_bytes(bytes);
assert_eq!(v.to_be_bytes(), bytes);
}
/// Zero produces all-zero bytes.
#[test]
fn zero() {
assert_eq!(U384::ZERO.to_be_bytes(), [0u8; 48]);
}
/// MAX produces all-0xFF bytes.
#[test]
fn max() {
assert_eq!(U384::MAX.to_be_bytes(), [0xFF; 48]);
}
/// Byte 47 holds the LSB of the lowest limb.
#[test]
fn lsb_position() {
let v = U384::from_be_limbs([0, 0, 0, 0, 0, 0x42]);
let bytes = v.to_be_bytes();
assert_eq!(bytes[47], 0x42);
assert_eq!(bytes[46], 0);
}
/// Matches the Into<[u8; 48]> implementation.
#[test]
fn matches_into() {
let v = U384::from_be_limbs([0xDEADBEEF, 0x12345678, 0xCAFEBABE, 0x42, 0xFF, 0x99]);
let into_bytes: [u8; 48] = v.into();
assert_eq!(v.to_be_bytes(), into_bytes);
}
}