Skip to main content

crypto_bigint/uint/
encoding.rs

1//! Const-friendly decoding operations for [`UInt`]
2
3use super::UInt;
4use crate::{limb, Encoding, Limb};
5
6impl<const LIMBS: usize> UInt<LIMBS> {
7    /// Create a new [`UInt`] from the provided big endian bytes.
8    pub const fn from_be_slice(bytes: &[u8]) -> Self {
9        const_assert!(
10            bytes.len() == limb::BYTE_SIZE * LIMBS,
11            "bytes are not the expected size"
12        );
13
14        let mut decoder = Decoder::new();
15        let mut i = 0;
16
17        while i < limb::BYTE_SIZE * LIMBS {
18            i += 1;
19            decoder = decoder.add_byte(bytes[bytes.len() - i]);
20        }
21
22        decoder.finish()
23    }
24
25    /// Create a new [`UInt`] from the provided big endian hex string.
26    pub const fn from_be_hex(hex: &str) -> Self {
27        let bytes = hex.as_bytes();
28
29        const_assert!(
30            bytes.len() == limb::BYTE_SIZE * LIMBS * 2,
31            "hex string is not the expected size"
32        );
33
34        let mut decoder = Decoder::new();
35        let mut i = 0;
36
37        while i < limb::BYTE_SIZE * LIMBS * 2 {
38            i += 2;
39            let offset = bytes.len() - i;
40            let byte = decode_hex_byte([bytes[offset], bytes[offset + 1]]);
41            decoder = decoder.add_byte(byte);
42        }
43
44        decoder.finish()
45    }
46
47    /// Create a new [`UInt`] from the provided little endian bytes.
48    pub const fn from_le_slice(bytes: &[u8]) -> Self {
49        const_assert!(
50            bytes.len() == limb::BYTE_SIZE * LIMBS,
51            "bytes are not the expected size"
52        );
53
54        let mut decoder = Decoder::new();
55        let mut i = 0;
56
57        while i < limb::BYTE_SIZE * LIMBS {
58            decoder = decoder.add_byte(bytes[i]);
59            i += 1;
60        }
61
62        decoder.finish()
63    }
64
65    /// Create a new [`UInt`] from the provided little endian hex string.
66    pub const fn from_le_hex(hex: &str) -> Self {
67        let bytes = hex.as_bytes();
68
69        const_assert!(
70            bytes.len() == limb::BYTE_SIZE * LIMBS * 2,
71            "bytes are not the expected size"
72        );
73
74        let mut decoder = Decoder::new();
75        let mut i = 0;
76
77        while i < limb::BYTE_SIZE * LIMBS * 2 {
78            let byte = decode_hex_byte([bytes[i], bytes[i + 1]]);
79            decoder = decoder.add_byte(byte);
80            i += 2;
81        }
82
83        decoder.finish()
84    }
85
86    /// Serialize this [`UInt`] as big-endian, writing it into the provided
87    /// byte slice.
88    #[inline]
89    #[cfg_attr(docsrs, doc(cfg(feature = "generic-array")))]
90    pub(crate) fn write_be_bytes(&self, out: &mut [u8]) {
91        debug_assert_eq!(out.len(), limb::BYTE_SIZE * LIMBS);
92
93        for (src, dst) in self
94            .limbs
95            .iter()
96            .rev()
97            .cloned()
98            .zip(out.chunks_exact_mut(limb::BYTE_SIZE))
99        {
100            dst.copy_from_slice(&src.to_be_bytes());
101        }
102    }
103
104    /// Serialize this [`UInt`] as little-endian, writing it into the provided
105    /// byte slice.
106    #[inline]
107    #[cfg_attr(docsrs, doc(cfg(feature = "generic-array")))]
108    pub(crate) fn write_le_bytes(&self, out: &mut [u8]) {
109        debug_assert_eq!(out.len(), limb::BYTE_SIZE * LIMBS);
110
111        for (src, dst) in self
112            .limbs
113            .iter()
114            .cloned()
115            .zip(out.chunks_exact_mut(limb::BYTE_SIZE))
116        {
117            dst.copy_from_slice(&src.to_le_bytes());
118        }
119    }
120}
121
122#[derive(Clone, Debug)]
123struct Decoder<const LIMBS: usize> {
124    /// Limbs being decoded.
125    ///
126    /// Stored from least significant to most significant.
127    limbs: [Limb; LIMBS],
128
129    /// Current limb being decoded.
130    index: usize,
131
132    /// Total number of bytes consumed.
133    bytes: usize,
134}
135
136impl<const LIMBS: usize> Decoder<LIMBS> {
137    /// Create a new decoder.
138    pub const fn new() -> Self {
139        Self {
140            limbs: [Limb::ZERO; LIMBS],
141            index: 0,
142            bytes: 0,
143        }
144    }
145
146    /// Add a byte onto the [`UInt`] being decoded.
147    pub const fn add_byte(mut self, byte: u8) -> Self {
148        if self.bytes == limb::BYTE_SIZE {
149            const_assert!(self.index < LIMBS, "too many bytes in UInt");
150            self.index += 1;
151            self.bytes = 0;
152        }
153
154        self.limbs[self.index].0 |= (byte as limb::Inner) << (self.bytes * 8);
155        self.bytes += 1;
156        self
157    }
158
159    /// Finish decoding a [`UInt`], returning a decoded value only if we've
160    /// received the expected number of bytes.
161    pub const fn finish(self) -> UInt<LIMBS> {
162        const_assert!(self.index == LIMBS - 1, "decoded UInt is missing limbs");
163        const_assert!(
164            self.bytes == limb::BYTE_SIZE,
165            "decoded UInt is missing bytes"
166        );
167        UInt { limbs: self.limbs }
168    }
169}
170
171impl<const LIMBS: usize> Default for Decoder<LIMBS> {
172    fn default() -> Self {
173        Self::new()
174    }
175}
176
177/// Decode a single byte encoded as two hexadecimal characters.
178const fn decode_hex_byte(bytes: [u8; 2]) -> u8 {
179    let mut i = 0;
180    let mut result = 0u8;
181
182    while i < 2 {
183        result <<= 4;
184        result |= match bytes[i] {
185            b @ b'0'..=b'9' => b - b'0',
186            b @ b'a'..=b'f' => 10 + b - b'a',
187            b @ b'A'..=b'F' => 10 + b - b'A',
188            b => {
189                const_assert!(
190                    matches!(b, b'0'..=b'9' | b'a' ..= b'f' | b'A'..=b'F'),
191                    "invalid hex byte"
192                );
193                0
194            }
195        };
196
197        i += 1;
198    }
199
200    result
201}
202
203#[cfg(test)]
204mod tests {
205    use crate::Limb;
206    use hex_literal::hex;
207
208    #[cfg(feature = "alloc")]
209    use {crate::U128, alloc::format};
210
211    #[cfg(target_pointer_width = "32")]
212    use crate::U64 as UIntEx;
213
214    #[cfg(target_pointer_width = "64")]
215    use crate::U128 as UIntEx;
216
217    #[test]
218    #[cfg(target_pointer_width = "32")]
219    fn from_be_bytes() {
220        let bytes = hex!("0011223344556677");
221        let n = UIntEx::from_be_slice(&bytes);
222        assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]);
223    }
224
225    #[test]
226    #[cfg(target_pointer_width = "64")]
227    fn from_be_bytes() {
228        let bytes = hex!("00112233445566778899aabbccddeeff");
229        let n = UIntEx::from_be_slice(&bytes);
230        assert_eq!(
231            n.limbs(),
232            &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)]
233        );
234    }
235
236    #[test]
237    #[cfg(target_pointer_width = "32")]
238    fn from_le_bytes() {
239        let bytes = hex!("7766554433221100");
240        let n = UIntEx::from_le_slice(&bytes);
241        assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]);
242    }
243
244    #[test]
245    #[cfg(target_pointer_width = "64")]
246    fn from_le_bytes() {
247        let bytes = hex!("ffeeddccbbaa99887766554433221100");
248        let n = UIntEx::from_le_slice(&bytes);
249        assert_eq!(
250            n.limbs(),
251            &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)]
252        );
253    }
254
255    #[test]
256    #[cfg(target_pointer_width = "32")]
257    fn from_be_hex() {
258        let n = UIntEx::from_be_hex("0011223344556677");
259        assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]);
260    }
261
262    #[test]
263    #[cfg(target_pointer_width = "64")]
264    fn from_be_hex() {
265        let n = UIntEx::from_be_hex("00112233445566778899aabbccddeeff");
266        assert_eq!(
267            n.limbs(),
268            &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)]
269        );
270    }
271
272    #[test]
273    #[cfg(target_pointer_width = "32")]
274    fn from_le_hex() {
275        let n = UIntEx::from_le_hex("7766554433221100");
276        assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]);
277    }
278
279    #[test]
280    #[cfg(target_pointer_width = "64")]
281    fn from_le_hex() {
282        let n = UIntEx::from_le_hex("ffeeddccbbaa99887766554433221100");
283        assert_eq!(
284            n.limbs(),
285            &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)]
286        );
287    }
288
289    #[cfg(feature = "alloc")]
290    #[test]
291    fn hex_upper() {
292        let hex = "AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD";
293        let n = U128::from_be_hex(hex);
294        assert_eq!(hex, format!("{:X}", n));
295    }
296
297    #[cfg(feature = "alloc")]
298    #[test]
299    fn hex_lower() {
300        let hex = "aaaaaaaabbbbbbbbccccccccdddddddd";
301        let n = U128::from_be_hex(hex);
302        assert_eq!(hex, format!("{:x}", n));
303    }
304}