Skip to main content

crypto_bigint/uint/boxed/
encoding.rs

1//! Const-friendly decoding operations for [`BoxedUint`].
2
3use super::BoxedUint;
4use crate::{CtEq, CtOption, DecodeError, Encoding, Limb, Word, bitlen, uint::encoding};
5use alloc::{boxed::Box, string::String, vec::Vec};
6
7#[cfg(feature = "serde")]
8mod serde;
9
10impl BoxedUint {
11    /// Create a new [`BoxedUint`] from the provided big endian bytes.
12    ///
13    /// The `bits_precision` argument represents the precision of the resulting integer, which is
14    /// fixed as this type is not arbitrary-precision.
15    ///
16    /// The new [`BoxedUint`] will be created with `bits_precision` rounded up to a multiple of
17    /// [`Limb::BITS`].
18    ///
19    /// # Errors
20    /// - Returns [`DecodeError::InputSize`] if the length of `bytes` is larger than
21    ///   `bits_precision` (rounded up to a multiple of 8).
22    /// - Returns [`DecodeError::Precision`] if the size of the decoded integer is larger than
23    ///   `bits_precision`.
24    pub fn from_be_slice(bytes: &[u8], bits_precision: u32) -> Result<Self, DecodeError> {
25        if bytes.len() > bitlen::to_bytes(bits_precision) {
26            return Err(DecodeError::InputSize);
27        }
28
29        Ok(Self::from_be_slice_truncated(bytes, bits_precision))
30    }
31
32    /// Create a new [`BoxedUint`] from the provided big endian bytes, zero padding if necessary,
33    /// and truncating to the least significant bytes in the event the given amount of data exceeds
34    /// `bits_precision`.
35    #[must_use]
36    #[allow(clippy::missing_panics_doc, reason = "should not panic in practice")]
37    pub fn from_be_slice_truncated(bytes: &[u8], bits_precision: u32) -> Self {
38        let mut ret = Self::zero_with_precision(bits_precision);
39        encoding::fill_limbs_from_be_slice_truncated(bytes, &mut ret.limbs, bits_precision)
40            .expect("should fit in requested precision");
41        ret
42    }
43
44    /// Create a new [`BoxedUint`] from the provided big endian bytes, automatically selecting its
45    /// precision based on the size of the input.
46    ///
47    /// This method is variable-time with respect to all subsequent operations since it chooses the
48    /// limb count based on the input size, and is therefore only suitable for public inputs.
49    ///
50    /// When working with secret values, use [`BoxedUint::from_be_slice`].
51    #[must_use]
52    pub fn from_be_slice_vartime(bytes: &[u8]) -> Self {
53        Self::from_be_slice_truncated(bytes, bitlen::from_bytes(bytes.len()))
54    }
55
56    /// Create a new [`BoxedUint`] from the provided little endian bytes.
57    ///
58    /// The `bits_precision` argument represents the precision of the resulting integer, which is
59    /// fixed as this type is not arbitrary-precision.
60    ///
61    /// The new [`BoxedUint`] will be created with `bits_precision`
62    /// rounded up to a multiple of [`Limb::BITS`].
63    ///
64    /// # Errors
65    /// - Returns [`DecodeError::InputSize`] if the length of `bytes` is larger than
66    ///   `bits_precision` (rounded up to a multiple of 8).
67    /// - Returns [`DecodeError::Precision`] if the size of the decoded integer is larger than
68    ///   `bits_precision`.
69    pub fn from_le_slice(bytes: &[u8], bits_precision: u32) -> Result<Self, DecodeError> {
70        if bytes.len() > bitlen::to_bytes(bits_precision) {
71            return Err(DecodeError::InputSize);
72        }
73
74        Ok(Self::from_le_slice_truncated(bytes, bits_precision))
75    }
76
77    /// Create a new [`BoxedUint`] from the provided little endian bytes, zero padding if necessary,
78    /// and truncating to the least significant bytes in the event the given amount of data exceeds
79    /// `bits_precision`.
80    #[must_use]
81    #[allow(clippy::missing_panics_doc, reason = "should not panic in practice")]
82    pub fn from_le_slice_truncated(bytes: &[u8], bits_precision: u32) -> Self {
83        let mut ret = Self::zero_with_precision(bits_precision);
84        encoding::fill_limbs_from_le_slice_truncated(bytes, &mut ret.limbs, bits_precision)
85            .expect("should fit in requested precision");
86        ret
87    }
88
89    /// Create a new [`BoxedUint`] from the provided little endian bytes, automatically selecting
90    /// its precision based on the size of the input.
91    ///
92    /// This method is variable-time with respect to all subsequent operations since it chooses the
93    /// limb count based on the input size, and is therefore only suitable for public inputs.
94    ///
95    /// When working with secret values, use [`BoxedUint::from_le_slice`].
96    #[must_use]
97    pub fn from_le_slice_vartime(bytes: &[u8]) -> Self {
98        Self::from_le_slice_truncated(bytes, bitlen::from_bytes(bytes.len()))
99    }
100
101    /// Serialize this [`BoxedUint`] as big-endian.
102    #[inline]
103    #[must_use]
104    pub fn to_be_bytes(&self) -> Box<[u8]> {
105        let mut out = vec![0u8; self.limbs.len() * Limb::BYTES];
106
107        for (src, dst) in self
108            .limbs
109            .iter()
110            .rev()
111            .cloned()
112            .zip(out.chunks_exact_mut(Limb::BYTES))
113        {
114            dst.copy_from_slice(&src.0.to_be_bytes());
115        }
116
117        out.into()
118    }
119
120    /// Serialize this [`BoxedUint`] as big-endian without leading zeroes.
121    #[inline]
122    #[must_use]
123    #[allow(clippy::integer_division_remainder_used, reason = "vartime")]
124    pub fn to_be_bytes_trimmed_vartime(&self) -> Box<[u8]> {
125        let zeroes = self.leading_zeros() as usize / 8;
126        (&self.to_be_bytes()[zeroes..]).into()
127    }
128
129    /// Serialize this [`BoxedUint`] as little-endian.
130    #[inline]
131    #[must_use]
132    pub fn to_le_bytes(&self) -> Box<[u8]> {
133        let mut out = vec![0u8; self.limbs.len() * Limb::BYTES];
134
135        for (src, dst) in self
136            .limbs
137            .iter()
138            .cloned()
139            .zip(out.chunks_exact_mut(Limb::BYTES))
140        {
141            dst.copy_from_slice(&src.0.to_le_bytes());
142        }
143
144        out.into()
145    }
146
147    /// Serialize this [`BoxedUint`] as little-endian without trailing zeroes.
148    #[inline]
149    #[must_use]
150    #[allow(clippy::integer_division_remainder_used, reason = "vartime")]
151    pub fn to_le_bytes_trimmed_vartime(&self) -> Box<[u8]> {
152        let zeroes = self.leading_zeros() as usize / 8;
153        let bytes = self.to_le_bytes();
154        (&bytes[..bytes.len() - zeroes]).into()
155    }
156
157    /// Create a new [`BoxedUint`] from the provided big endian hex string.
158    ///
159    /// # Panics
160    /// - if hex string is not the expected size
161    #[must_use]
162    pub fn from_be_hex(hex: &str, bits_precision: u32) -> CtOption<Self> {
163        let nlimbs = bitlen::to_limbs(bits_precision);
164        let bytes = hex.as_bytes();
165
166        assert_eq!(
167            bytes.len(),
168            Limb::BYTES * nlimbs * 2,
169            "hex string is not the expected size"
170        );
171
172        let mut res = vec![Limb::ZERO; nlimbs];
173        let mut buf = [0u8; Limb::BYTES];
174        let mut i = 0;
175        let mut err = 0;
176
177        while i < nlimbs {
178            let mut j = 0;
179            while j < Limb::BYTES {
180                let offset = (i * Limb::BYTES + j) * 2;
181                let (result, byte_err) =
182                    encoding::decode_hex_byte([bytes[offset], bytes[offset + 1]]);
183                err |= byte_err;
184                buf[j] = result;
185                j += 1;
186            }
187            res[nlimbs - i - 1] = Limb(Word::from_be_bytes(buf));
188            i += 1;
189        }
190
191        CtOption::new(Self { limbs: res.into() }, err.ct_eq(&0))
192    }
193
194    /// Create a new [`BoxedUint`] from a big-endian string in a given base.
195    ///
196    /// The string may begin with a `+` character, and may use underscore
197    /// characters to separate digits.
198    ///
199    /// # Errors
200    /// - Returns [`DecodeError::InvalidDigit`] if the input value contains non-digit characters or
201    ///   digits outside of the range `0..radix`.
202    ///
203    /// # Panics
204    /// - if `radix` is not in the range from 2 to 36.
205    pub fn from_str_radix_vartime(src: &str, radix: u32) -> Result<Self, DecodeError> {
206        let mut dec = VecDecodeByLimb::default();
207        encoding::radix_decode_str(src, radix, &mut dec)?;
208        Ok(Self::from(dec.limbs))
209    }
210
211    /// Create a new [`BoxedUint`] from a big-endian string in a given base,
212    /// with a given precision.
213    ///
214    /// The string may begin with a `+` character, and may use underscore
215    /// characters to separate digits.
216    ///
217    /// The `bits_precision` argument represents the precision of the resulting integer, which is
218    /// fixed as this type is not arbitrary-precision.
219    ///
220    /// The new [`BoxedUint`] will be created with `bits_precision` rounded up to a multiple
221    /// of [`Limb::BITS`].
222    ///
223    /// # Errors
224    /// - Returns [`DecodeError::InputSize`] if the length of `bytes` is larger than
225    ///   `bits_precision` (rounded up to a multiple of 8).
226    /// - Returns [`DecodeError::InvalidDigit`] if the input value contains non-digit characters or
227    ///   digits are outside the range `0..radix`.
228    /// - Returns [`DecodeError::Precision`] if the size of the decoded integer is larger than
229    ///   `bits_precision`.
230    ///
231    /// # Panics
232    /// - if `radix` is not in the range from 2 to 36.
233    pub fn from_str_radix_with_precision_vartime(
234        src: &str,
235        radix: u32,
236        bits_precision: u32,
237    ) -> Result<Self, DecodeError> {
238        let mut ret = Self::zero_with_precision(bits_precision);
239        encoding::radix_decode_str(
240            src,
241            radix,
242            &mut encoding::SliceDecodeByLimb::new(&mut ret.limbs),
243        )?;
244        if bits_precision < ret.bit_width() {
245            return Err(DecodeError::Precision);
246        }
247        Ok(ret)
248    }
249
250    /// Format a [`BoxedUint`] as a string in a given base.
251    ///
252    /// # Panics
253    /// - if `radix` is not in the range from 2 to 36.
254    #[must_use]
255    pub fn to_string_radix_vartime(&self, radix: u32) -> String {
256        encoding::radix_encode_limbs_to_string(radix, &self.limbs)
257    }
258}
259
260impl Encoding for BoxedUint {
261    type Repr = Box<[u8]>;
262
263    fn from_be_bytes(bytes: Self::Repr) -> Self {
264        Self::from_be_slice_vartime(&bytes)
265    }
266
267    fn from_le_bytes(bytes: Self::Repr) -> Self {
268        Self::from_le_slice_vartime(&bytes)
269    }
270
271    fn from_be_slice_truncated(bytes: &[u8], bits_precision: u32) -> Self {
272        Self::from_be_slice_truncated(bytes, bits_precision)
273    }
274
275    fn from_le_slice_truncated(bytes: &[u8], bits_precision: u32) -> Self {
276        Self::from_le_slice_truncated(bytes, bits_precision)
277    }
278
279    fn to_be_bytes(&self) -> Self::Repr {
280        Self::to_be_bytes(self)
281    }
282
283    fn to_le_bytes(&self) -> Self::Repr {
284        Self::to_le_bytes(self)
285    }
286}
287
288/// Decoder target producing a Vec<Limb>
289#[derive(Default)]
290struct VecDecodeByLimb {
291    limbs: Vec<Limb>,
292}
293
294impl encoding::DecodeByLimb for VecDecodeByLimb {
295    #[inline]
296    fn limbs_mut(&mut self) -> &mut [Limb] {
297        self.limbs.as_mut_slice()
298    }
299
300    #[inline]
301    fn push_limb(&mut self, limb: Limb) -> bool {
302        self.limbs.push(limb);
303        true
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::{BoxedUint, DecodeError};
310    use crate::Limb;
311    use hex_literal::hex;
312
313    cpubits::cpubits! {
314        32 => {
315            #[test]
316            fn from_be_slice_eq() {
317                let bytes = hex!("0011223344556677");
318                let n = BoxedUint::from_be_slice(&bytes, 64).unwrap();
319                assert_eq!(n.as_limbs(), &[Limb(0x44556677), Limb(0x00112233)]);
320            }
321
322            #[test]
323            fn from_be_slice_short() {
324                let bytes = hex!("0011223344556677");
325                let n = BoxedUint::from_be_slice(&bytes, 128).unwrap();
326                assert_eq!(
327                    n.as_limbs(),
328                    &[Limb(0x44556677), Limb(0x00112233), Limb::ZERO, Limb::ZERO]
329                );
330            }
331
332            #[test]
333            fn from_be_slice_not_word_sized() {
334                let bytes = hex!("112233445566778899aabbccddeeff");
335                let n = BoxedUint::from_be_slice(&bytes, 127).unwrap();
336                assert_eq!(
337                    n.as_limbs(),
338                    &[
339                        Limb(0xccddeeff),
340                        Limb(0x8899aabb),
341                        Limb(0x44556677),
342                        Limb(0x00112233)
343                    ]
344                );
345                assert_eq!(n.bits_precision(), 128);
346            }
347
348            #[test]
349            fn from_le_slice_eq() {
350                let bytes = hex!("7766554433221100");
351                let n = BoxedUint::from_le_slice(&bytes, 64).unwrap();
352                assert_eq!(n.as_limbs(), &[Limb(0x44556677), Limb(0x00112233)]);
353            }
354
355            #[test]
356            fn from_le_slice_short() {
357                let bytes = hex!("7766554433221100");
358                let n = BoxedUint::from_le_slice(&bytes, 128).unwrap();
359                assert_eq!(
360                    n.as_limbs(),
361                    &[Limb(0x44556677), Limb(0x00112233), Limb::ZERO, Limb::ZERO]
362                );
363            }
364
365            #[test]
366            fn from_le_slice_not_word_sized() {
367                let bytes = hex!("ffeeddccbbaa998877665544332211");
368                let n = BoxedUint::from_le_slice(&bytes, 127).unwrap();
369                assert_eq!(
370                    n.as_limbs(),
371                    &[
372                        Limb(0xccddeeff),
373                        Limb(0x8899aabb),
374                        Limb(0x44556677),
375                        Limb(0x00112233)
376                    ]
377                );
378                assert_eq!(n.bits_precision(), 128);
379            }
380        }
381        64 => {
382            #[test]
383            #[should_panic]
384            fn from_be_hex_short() {
385                let hex = "00112233445566778899aabbccddee";
386                let _ = BoxedUint::from_be_hex(hex, 128).unwrap();
387            }
388
389            #[test]
390            fn from_be_slice_eq() {
391                let bytes = hex!("00112233445566778899aabbccddeeff");
392                let n = BoxedUint::from_be_slice(&bytes, 128).unwrap();
393                assert_eq!(
394                    n.as_limbs(),
395                    &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)]
396                );
397            }
398
399            #[test]
400            fn from_be_slice_short() {
401                let bytes = hex!("00112233445566778899aabbccddeeff");
402                let n = BoxedUint::from_be_slice(&bytes, 256).unwrap();
403                assert_eq!(
404                    n.as_limbs(),
405                    &[
406                        Limb(0x8899aabbccddeeff),
407                        Limb(0x0011223344556677),
408                        Limb::ZERO,
409                        Limb::ZERO
410                    ]
411                );
412            }
413
414            #[test]
415            fn from_be_slice_not_word_sized() {
416                let bytes = hex!("112233445566778899aabbccddeeff");
417                let n = BoxedUint::from_be_slice(&bytes, 127).unwrap();
418                assert_eq!(
419                    n.as_limbs(),
420                    &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)]
421                );
422                assert_eq!(n.bits_precision(), 128);
423            }
424
425            #[test]
426            fn from_le_slice_eq() {
427                let bytes = hex!("ffeeddccbbaa99887766554433221100");
428                let n = BoxedUint::from_le_slice(&bytes, 128).unwrap();
429                assert_eq!(
430                    n.as_limbs(),
431                    &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)]
432                );
433            }
434
435            #[test]
436            fn from_le_slice_short() {
437                let bytes = hex!("ffeeddccbbaa99887766554433221100");
438                let n = BoxedUint::from_le_slice(&bytes, 256).unwrap();
439                assert_eq!(
440                    n.as_limbs(),
441                    &[
442                        Limb(0x8899aabbccddeeff),
443                        Limb(0x0011223344556677),
444                        Limb::ZERO,
445                        Limb::ZERO
446                    ]
447                );
448            }
449
450            #[test]
451            fn from_le_slice_not_word_sized() {
452                let bytes = hex!("ffeeddccbbaa998877665544332211");
453                let n = BoxedUint::from_le_slice(&bytes, 127).unwrap();
454                assert_eq!(
455                    n.as_limbs(),
456                    &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)]
457                );
458                assert_eq!(n.bits_precision(), 128);
459            }
460        }
461    }
462
463    #[test]
464    fn from_be_slice_too_long() {
465        let bytes = hex!("00112233445566778899aabbccddeeff");
466        assert_eq!(
467            BoxedUint::from_be_slice(&bytes, 64),
468            Err(DecodeError::InputSize)
469        );
470    }
471
472    #[test]
473    fn from_be_slice_non_multiple_precision() {
474        let bytes = hex!("0f112233445566778899aabbccddeeff");
475        let n = BoxedUint::from_be_slice(&bytes, 121).unwrap();
476        assert_eq!(n.bit_width(), 121);
477    }
478
479    #[test]
480    fn from_be_slice_rejects_value_exceeding_precision() {
481        assert_eq!(
482            BoxedUint::from_be_slice(&[0x01, 0x00], 8),
483            Err(DecodeError::InputSize)
484        );
485    }
486
487    #[test]
488    fn from_be_slice_truncated_exact_fit() {
489        let bytes = [0u8; 32];
490        let n = BoxedUint::from_be_slice_truncated(&bytes, 256);
491        assert_eq!(&*n.to_be_bytes(), &bytes);
492    }
493
494    #[test]
495    fn from_be_slice_truncated_truncates_to_lsb() {
496        let n = BoxedUint::from_be_slice_truncated(&[0xDE, 0xAD, 0xBE, 0xEF], 16);
497        let out = n.to_be_bytes();
498        assert_eq!(&out[(out.len() - 2)..], &[0xBE, 0xEF]);
499    }
500
501    #[test]
502    fn from_be_slice_truncated_zero_pads_short_input() {
503        let n = BoxedUint::from_be_slice_truncated(&[0x42], 32);
504        assert_eq!(n.to_be_bytes().last(), Some(&0x42));
505        assert!(n.to_be_bytes().iter().rev().skip(1).all(|&b| b == 0));
506    }
507
508    #[test]
509    fn from_be_slice_truncated_top_byte_masked() {
510        let n = BoxedUint::from_be_slice_truncated(&[0xFF, 0xFF], 12);
511        assert!(n.bit_width() <= 12);
512    }
513
514    #[test]
515    fn from_le_slice_truncated_exact_fit() {
516        let bytes = [0u8; 32];
517        let n = BoxedUint::from_le_slice_truncated(&bytes, 256);
518        assert_eq!(&*n.to_le_bytes(), &bytes);
519    }
520
521    #[test]
522    fn from_le_slice_truncated_truncates_to_lsb() {
523        let n = BoxedUint::from_le_slice_truncated(&[0xEF, 0xBE, 0xAD, 0xDE], 16);
524        assert_eq!(&n.to_le_bytes()[..2], &[0xEF, 0xBE]);
525    }
526
527    #[test]
528    fn from_le_slice_truncated_top_byte_masked() {
529        let n = BoxedUint::from_le_slice_truncated(&[0xFF, 0xFF], 12);
530        assert!(n.bit_width() <= 12,);
531    }
532
533    #[test]
534    fn from_be_slice_vartime() {
535        let bytes = hex!(
536            "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111F"
537        );
538        let uint = BoxedUint::from_be_slice_vartime(&bytes);
539        assert_eq!(&*uint.to_be_bytes_trimmed_vartime(), bytes.as_slice());
540    }
541
542    #[test]
543    fn from_le_slice_too_long() {
544        let bytes = hex!("ffeeddccbbaa99887766554433221100");
545        assert_eq!(
546            BoxedUint::from_be_slice(&bytes, 64),
547            Err(DecodeError::InputSize)
548        );
549    }
550
551    #[test]
552    fn from_le_slice_non_multiple_precision() {
553        let bytes = hex!("ffeeddccbbaa998877665544332211ff");
554        let n = BoxedUint::from_le_slice(&bytes, 121).unwrap();
555        assert_eq!(n.bit_width(), 121);
556    }
557
558    #[test]
559    fn from_le_slice_vartime() {
560        let bytes = hex!(
561            "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111F"
562        );
563        let uint = BoxedUint::from_le_slice_vartime(&bytes);
564        assert_eq!(&*uint.to_le_bytes_trimmed_vartime(), bytes.as_slice());
565    }
566
567    #[test]
568    fn to_be_bytes() {
569        let bytes = hex!("00112233445566778899aabbccddeeff");
570        let n = BoxedUint::from_be_slice(&bytes, 128).unwrap();
571        assert_eq!(bytes.as_slice(), &*n.to_be_bytes());
572    }
573
574    #[test]
575    fn to_be_bytes_trimmed_vartime() {
576        let bytes = hex!("ff112233445566778899aabbccddeeff");
577        let n = BoxedUint::from_be_slice(&bytes, 128).unwrap();
578        assert_eq!(&bytes, &*n.to_be_bytes_trimmed_vartime());
579
580        let bytes = hex!("00112233445566778899aabbccddeeff");
581        let n = BoxedUint::from_be_slice(&bytes, 128).unwrap();
582        assert_eq!(&bytes.as_slice()[1..], &*n.to_be_bytes_trimmed_vartime());
583
584        let bytes: &[u8] = b"";
585        let n = BoxedUint::from_be_slice(bytes, 128).unwrap();
586        assert_eq!(
587            hex!("00000000000000000000000000000000"),
588            n.to_be_bytes().as_ref()
589        );
590        assert_eq!(bytes, n.to_be_bytes_trimmed_vartime().as_ref());
591
592        let bytes = hex!("00012233445566778899aabbccddeeff");
593        let n = BoxedUint::from_be_slice(&bytes, 128).unwrap();
594        assert_eq!(&bytes.as_slice()[1..], &*n.to_be_bytes_trimmed_vartime());
595
596        let bytes = hex!("00000000000000000000000000000001");
597        let n = BoxedUint::from_be_slice(&bytes, 128).unwrap();
598        assert_eq!(bytes, n.to_be_bytes().as_ref());
599        assert_eq!(&bytes.as_slice()[15..], &*n.to_be_bytes_trimmed_vartime());
600    }
601
602    #[test]
603    fn to_le_bytes() {
604        let bytes = hex!("ffeeddccbbaa99887766554433221100");
605        let n = BoxedUint::from_le_slice(&bytes, 128).unwrap();
606        assert_eq!(bytes.as_slice(), &*n.to_le_bytes());
607    }
608
609    #[test]
610    fn to_le_bytes_trimmed_vartime() {
611        let bytes = hex!("ffeeddccbbaa998877665544332211ff");
612        let n = BoxedUint::from_le_slice(&bytes, 128).unwrap();
613        assert_eq!(bytes.as_slice(), &*n.to_le_bytes_trimmed_vartime());
614
615        let bytes = hex!("ffeeddccbbaa99887766554433221100");
616        let n = BoxedUint::from_le_slice(&bytes, 128).unwrap();
617        assert_eq!(&bytes.as_slice()[..15], &*n.to_le_bytes_trimmed_vartime());
618
619        let bytes = hex!("ff000000000000000000000000000000");
620        let n = BoxedUint::from_le_slice(&bytes, 128).unwrap();
621        assert_eq!(&bytes.as_slice()[..1], &*n.to_le_bytes_trimmed_vartime());
622
623        let bytes = hex!("01000000000000000000000000000000");
624        let n = BoxedUint::from_le_slice(&bytes, 128).unwrap();
625        assert_eq!(&bytes.as_slice()[..1], &*n.to_le_bytes_trimmed_vartime());
626
627        let bytes = hex!("00000000000000000000000000000000");
628        let n = BoxedUint::from_le_slice(&bytes, 128).unwrap();
629        assert_eq!(b"", &*n.to_le_bytes_trimmed_vartime());
630    }
631
632    #[test]
633    fn from_str_radix_invalid() {
634        assert_eq!(
635            BoxedUint::from_str_radix_vartime("?", 10,),
636            Err(DecodeError::InvalidDigit)
637        );
638        assert_eq!(
639            BoxedUint::from_str_radix_with_precision_vartime(
640                "ffffffffffffffff_ffffffffffffffff_f",
641                16,
642                128
643            ),
644            Err(DecodeError::InputSize)
645        );
646        assert_eq!(
647            BoxedUint::from_str_radix_with_precision_vartime("1111111111111111", 2, 10),
648            Err(DecodeError::Precision)
649        );
650    }
651
652    #[test]
653    fn from_str_radix_10() {
654        let dec = "+340_282_366_920_938_463_463_374_607_431_768_211_455";
655        let res = BoxedUint::from_str_radix_vartime(dec, 10).expect("error decoding");
656        assert_eq!(res, BoxedUint::max(128));
657    }
658
659    #[test]
660    fn from_str_radix_16() {
661        let hex = "fedcba9876543210fedcba9876543210";
662        let res = BoxedUint::from_str_radix_vartime(hex, 16).expect("error decoding");
663        assert_eq!(hex, format!("{res:x}"));
664    }
665
666    #[test]
667    fn from_str_radix_zero() {
668        for radix in [2, 10, 16, 36] {
669            for src in ["0", "00", "+0", "0_0"] {
670                let res = BoxedUint::from_str_radix_vartime(src, radix).expect("error decoding");
671                assert_eq!(res, BoxedUint::zero());
672                assert_eq!(res.bit_width_vartime(), 0);
673                assert_eq!(res.to_string_radix_vartime(radix), "0");
674            }
675        }
676    }
677
678    #[test]
679    #[cfg(feature = "rand_core")]
680    fn encode_radix_round_trip() {
681        use crate::RandomBits;
682        use rand_core::SeedableRng;
683        let mut rng = chacha20::ChaCha8Rng::seed_from_u64(1);
684
685        let rounds = if cfg!(miri) { 10 } else { 100 };
686        let bits = if cfg!(miri) { 256 } else { 4096 };
687        for _ in 0..rounds {
688            let uint = BoxedUint::random_bits(&mut rng, bits);
689            for radix in 2..=36 {
690                let enc = uint.to_string_radix_vartime(radix);
691                let res = BoxedUint::from_str_radix_vartime(&enc, radix).expect("decoding error");
692                assert_eq!(
693                    res, uint,
694                    "round trip failure: radix {radix} encoded {uint} as {enc}"
695                );
696            }
697        }
698    }
699}