Skip to main content

crypto_bigint/
uint.rs

1//! Big unsigned integers.
2
3#![allow(
4    clippy::needless_range_loop,
5    clippy::many_single_char_names,
6    clippy::derive_hash_xor_eq
7)]
8
9#[macro_use]
10mod macros;
11
12mod add;
13mod add_mod;
14mod cmp;
15mod encoding;
16mod from;
17mod mul;
18mod neg_mod;
19mod shr;
20mod sub;
21mod sub_mod;
22
23#[cfg(feature = "generic-array")]
24mod array;
25
26#[cfg(feature = "rand")]
27mod rand;
28
29use crate::{Concat, Encoding, Limb, Split};
30use core::fmt;
31use subtle::{Choice, ConditionallySelectable};
32
33#[cfg(feature = "zeroize")]
34use zeroize::Zeroize;
35
36/// Big unsigned integer.
37///
38/// Generic over the given number of `LIMBS`
39// TODO(tarcieri): make generic around a specified number of bits.
40#[derive(Copy, Clone, Debug, Hash)]
41pub struct UInt<const LIMBS: usize> {
42    /// Inner limb array. Stored from least significant to most significant.
43    limbs: [Limb; LIMBS],
44}
45
46impl<const LIMBS: usize> UInt<LIMBS> {
47    /// The value `0`.
48    pub const ZERO: Self = Self::from_u8(0);
49
50    /// The value `1`.
51    pub const ONE: Self = Self::from_u8(1);
52
53    /// Maximum value this [`UInt`] can express.
54    pub const MAX: Self = Self {
55        limbs: [Limb::MAX; LIMBS],
56    };
57
58    /// Const-friendly [`UInt`] constructor.
59    pub const fn new(limbs: [Limb; LIMBS]) -> Self {
60        Self { limbs }
61    }
62
63    /// Borrow the limbs of this [`UInt`].
64    // TODO(tarcieri): eventually phase this out?
65    pub const fn limbs(&self) -> &[Limb; LIMBS] {
66        &self.limbs
67    }
68
69    /// Convert this [`UInt`] into its inner limbs.
70    // TODO(tarcieri): eventually phase this out?
71    pub const fn into_limbs(self) -> [Limb; LIMBS] {
72        self.limbs
73    }
74}
75
76// TODO(tarcieri): eventually phase this out?
77impl<const LIMBS: usize> AsRef<[Limb]> for UInt<LIMBS> {
78    fn as_ref(&self) -> &[Limb] {
79        self.limbs()
80    }
81}
82
83// TODO(tarcieri): eventually phase this out?
84impl<const LIMBS: usize> AsMut<[Limb]> for UInt<LIMBS> {
85    fn as_mut(&mut self) -> &mut [Limb] {
86        &mut self.limbs
87    }
88}
89
90impl<const LIMBS: usize> ConditionallySelectable for UInt<LIMBS> {
91    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
92        let mut limbs = [Limb::ZERO; LIMBS];
93
94        for i in 0..LIMBS {
95            limbs[i] = Limb::conditional_select(&a.limbs[i], &b.limbs[i], choice);
96        }
97
98        Self { limbs }
99    }
100}
101
102impl<const LIMBS: usize> Default for UInt<LIMBS> {
103    fn default() -> Self {
104        Self::ZERO
105    }
106}
107
108impl<const LIMBS: usize> fmt::Display for UInt<LIMBS> {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        fmt::UpperHex::fmt(self, f)
111    }
112}
113
114impl<const LIMBS: usize> fmt::LowerHex for UInt<LIMBS> {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        for limb in self.limbs.iter().rev() {
117            fmt::LowerHex::fmt(limb, f)?;
118        }
119        Ok(())
120    }
121}
122
123impl<const LIMBS: usize> fmt::UpperHex for UInt<LIMBS> {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        for limb in self.limbs.iter().rev() {
126            fmt::UpperHex::fmt(limb, f)?;
127        }
128        Ok(())
129    }
130}
131
132#[cfg(feature = "zeroize")]
133#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
134impl<const LIMBS: usize> Zeroize for UInt<LIMBS> {
135    fn zeroize(&mut self) {
136        self.limbs.zeroize();
137    }
138}
139
140// TODO(tarcieri): use `const_evaluatable_checked` when stable to make generic around bits.
141impl_uint_aliases! {
142    (U64, 64, "64-bit"),
143    (U128, 128, "128-bit"),
144    (U192, 192, "192-bit"),
145    (U256, 256, "256-bit"),
146    (U384, 384, "384-bit"),
147    (U448, 448, "448-bit"),
148    (U512, 512, "512-bit"),
149    (U768, 768, "768-bit"),
150    (U896, 896, "896-bit"),
151    (U1024, 1024, "1024-bit"),
152    (U1536, 1536, "1536-bit"),
153    (U1792, 1792, "1792-bit"),
154    (U2048, 2048, "2048-bit"),
155    (U3072, 3072, "3072-bit"),
156    (U3584, 3584, "3584-bit"),
157    (U4096, 4096, "4096-bit"),
158    (U6144, 6144, "6144-bit"),
159    (U8192, 8192, "8192-bit")
160}
161
162// TODO(tarcieri): use `const_evaluatable_checked` when stable to make generic around bits.
163impl_concat! {
164    (U64, 64),
165    (U128, 128),
166    (U192, 192),
167    (U256, 256),
168    (U384, 384),
169    (U448, 448),
170    (U512, 512),
171    (U768, 768),
172    (U896, 896),
173    (U1024, 1024),
174    (U1536, 1536),
175    (U1792, 1792),
176    (U2048, 2048),
177    (U3072, 3072),
178    (U4096, 4096)
179}
180
181// TODO(tarcieri): use `const_evaluatable_checked` when stable to make generic around bits.
182impl_split! {
183    (U128, 128),
184    (U192, 192),
185    (U256, 256),
186    (U384, 384),
187    (U448, 448),
188    (U512, 512),
189    (U768, 768),
190    (U896, 896),
191    (U1024, 1024),
192    (U1536, 1536),
193    (U1792, 1792),
194    (U2048, 2048),
195    (U3072, 3072),
196    (U3584, 3584),
197    (U4096, 4096),
198    (U6144, 6144),
199    (U8192, 8192)
200}
201
202#[cfg(test)]
203mod tests {
204    use crate::{Concat, Split, U128, U64};
205    use subtle::ConditionallySelectable;
206
207    #[test]
208    #[cfg(feature = "alloc")]
209    fn display() {
210        let hex = "AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD";
211        let n = U128::from_be_hex(hex);
212
213        use alloc::string::ToString;
214        assert_eq!(hex, n.to_string());
215    }
216
217    #[test]
218    fn conditional_select() {
219        let a = U128::from_be_hex("00002222444466668888AAAACCCCEEEE");
220        let b = U128::from_be_hex("11113333555577779999BBBBDDDDFFFF");
221
222        let select_0 = U128::conditional_select(&a, &b, 0.into());
223        assert_eq!(a, select_0);
224
225        let select_1 = U128::conditional_select(&a, &b, 1.into());
226        assert_eq!(b, select_1);
227    }
228
229    #[test]
230    fn concat() {
231        let hi = U64::from_u64(0x0011223344556677);
232        let lo = U64::from_u64(0x8899aabbccddeeff);
233        assert_eq!(
234            hi.concat(&lo),
235            U128::from_be_hex("00112233445566778899aabbccddeeff")
236        );
237    }
238
239    #[test]
240    fn split() {
241        let (hi, lo) = U128::from_be_hex("00112233445566778899aabbccddeeff").split();
242        assert_eq!(hi, U64::from_u64(0x0011223344556677));
243        assert_eq!(lo, U64::from_u64(0x8899aabbccddeeff));
244    }
245}