crypto-bigint 0.7.2

Pure Rust implementation of a big integer library which has been designed from the ground-up for use in cryptographic applications. Provides constant-time, no_std-friendly implementations of modern formulas using const generics.
Documentation
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Wrapping arithmetic.

use crate::{
    Choice, CtEq, CtSelect, One, UintRef, WrappingAdd, WrappingMul, WrappingNeg, WrappingShl,
    WrappingShr, WrappingSub, Zero,
};
use core::{
    fmt,
    ops::{Add, Mul, Neg, Shl, Shr, Sub},
};

#[cfg(feature = "rand_core")]
use {crate::Random, rand_core::TryRng};

#[cfg(feature = "serde")]
use serdect::serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Provides intentionally-wrapped arithmetic on `T`.
///
/// This is analogous to [`core::num::Wrapping`] but allows this crate to
/// define trait impls for this type.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
pub struct Wrapping<T>(pub T);

impl<T: AsRef<UintRef>> AsRef<UintRef> for Wrapping<T> {
    fn as_ref(&self) -> &UintRef {
        self.0.as_ref()
    }
}

impl<T: AsMut<UintRef>> AsMut<UintRef> for Wrapping<T> {
    fn as_mut(&mut self) -> &mut UintRef {
        self.0.as_mut()
    }
}

impl<T: WrappingAdd> Add<Self> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Wrapping(self.0.wrapping_add(&rhs.0))
    }
}

impl<T: WrappingAdd> Add<&Self> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn add(self, rhs: &Self) -> Self::Output {
        Wrapping(self.0.wrapping_add(&rhs.0))
    }
}

impl<T: WrappingAdd> Add<Wrapping<T>> for &Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn add(self, rhs: Wrapping<T>) -> Self::Output {
        Wrapping(self.0.wrapping_add(&rhs.0))
    }
}

impl<T: WrappingAdd> Add<&Wrapping<T>> for &Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn add(self, rhs: &Wrapping<T>) -> Self::Output {
        Wrapping(self.0.wrapping_add(&rhs.0))
    }
}

impl<T: WrappingSub> Sub<Self> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Wrapping(self.0.wrapping_sub(&rhs.0))
    }
}

impl<T: WrappingSub> Sub<&Self> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn sub(self, rhs: &Self) -> Self::Output {
        Wrapping(self.0.wrapping_sub(&rhs.0))
    }
}

impl<T: WrappingSub> Sub<Wrapping<T>> for &Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn sub(self, rhs: Wrapping<T>) -> Self::Output {
        Wrapping(self.0.wrapping_sub(&rhs.0))
    }
}

impl<T: WrappingSub> Sub<&Wrapping<T>> for &Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn sub(self, rhs: &Wrapping<T>) -> Self::Output {
        Wrapping(self.0.wrapping_sub(&rhs.0))
    }
}

impl<T: WrappingMul> Mul<Self> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        Wrapping(self.0.wrapping_mul(&rhs.0))
    }
}

impl<T: WrappingMul> Mul<&Self> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn mul(self, rhs: &Self) -> Self::Output {
        Wrapping(self.0.wrapping_mul(&rhs.0))
    }
}

impl<T: WrappingMul> Mul<Wrapping<T>> for &Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn mul(self, rhs: Wrapping<T>) -> Self::Output {
        Wrapping(self.0.wrapping_mul(&rhs.0))
    }
}

impl<T: WrappingMul> Mul<&Wrapping<T>> for &Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn mul(self, rhs: &Wrapping<T>) -> Self::Output {
        Wrapping(self.0.wrapping_mul(&rhs.0))
    }
}

impl<T: WrappingNeg> Neg for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn neg(self) -> Self::Output {
        Wrapping(self.0.wrapping_neg())
    }
}

impl<T: WrappingNeg> Neg for &Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn neg(self) -> Self::Output {
        Wrapping(self.0.wrapping_neg())
    }
}

impl<T: WrappingShl> Shl<u32> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn shl(self, rhs: u32) -> Self::Output {
        Wrapping(self.0.wrapping_shl(rhs))
    }
}

impl<T: WrappingShl> Shl<u32> for &Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn shl(self, rhs: u32) -> Self::Output {
        Wrapping(self.0.wrapping_shl(rhs))
    }
}

impl<T: WrappingShr> Shr<u32> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn shr(self, rhs: u32) -> Self::Output {
        Wrapping(self.0.wrapping_shr(rhs))
    }
}

impl<T: WrappingShr> Shr<u32> for &Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline]
    fn shr(self, rhs: u32) -> Self::Output {
        Wrapping(self.0.wrapping_shr(rhs))
    }
}

impl<T> CtEq for Wrapping<T>
where
    T: CtEq,
{
    #[inline]
    fn ct_eq(&self, other: &Self) -> Choice {
        CtEq::ct_eq(&self.0, &other.0)
    }
}

impl<T> CtSelect for Wrapping<T>
where
    T: CtSelect,
{
    #[inline]
    fn ct_select(&self, other: &Self, choice: Choice) -> Self {
        Self(self.0.ct_select(&other.0, choice))
    }
}

impl<T: Zero> Zero for Wrapping<T> {
    #[inline]
    fn zero() -> Self {
        Wrapping(T::zero())
    }
}

impl<T: One> One for Wrapping<T> {
    #[inline]
    fn one() -> Self {
        Wrapping(T::one())
    }
}

impl<T: num_traits::Zero + WrappingAdd> num_traits::Zero for Wrapping<T> {
    #[inline]
    fn zero() -> Self {
        Wrapping(T::zero())
    }

    #[inline]
    fn is_zero(&self) -> bool {
        self.0.is_zero()
    }
}

impl<T: num_traits::One + WrappingMul + PartialEq> num_traits::One for Wrapping<T> {
    #[inline]
    fn one() -> Self {
        Wrapping(T::one())
    }

    #[inline]
    fn is_one(&self) -> bool {
        self.0.is_one()
    }
}

impl<T: fmt::Display> fmt::Display for Wrapping<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(feature = "rand_core")]
impl<T: Random> Random for Wrapping<T> {
    fn try_random_from_rng<R: TryRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
        Ok(Wrapping(Random::try_random_from_rng(rng)?))
    }
}

#[cfg(feature = "serde")]
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Wrapping<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Self(T::deserialize(deserializer)?))
    }
}

#[cfg(feature = "serde")]
impl<T: Serialize> Serialize for Wrapping<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.0.serialize(serializer)
    }
}

#[cfg(feature = "subtle")]
impl<T> subtle::ConditionallySelectable for Wrapping<T>
where
    T: Copy,
    Self: CtSelect,
{
    #[inline]
    fn conditional_select(a: &Self, b: &Self, choice: subtle::Choice) -> Self {
        a.ct_select(b, choice.into())
    }
}

#[cfg(feature = "subtle")]
impl<T> subtle::ConstantTimeEq for Wrapping<T>
where
    Self: CtEq,
{
    #[inline]
    fn ct_eq(&self, other: &Self) -> subtle::Choice {
        CtEq::ct_eq(self, other).into()
    }
}

#[cfg(test)]
mod tests {
    use super::Wrapping;
    use crate::{
        Choice, CtEq, CtSelect, Limb, WrappingAdd, WrappingMul, WrappingNeg, WrappingShl,
        WrappingShr, WrappingSub,
    };

    // FIXME Could use itertools combinations or an equivalent iterator
    const INPUTS: &[(Limb, Limb)] = &[
        (Limb::ZERO, Limb::ZERO),
        (Limb::ZERO, Limb::ONE),
        (Limb::ZERO, Limb::MAX),
        (Limb::ONE, Limb::ZERO),
        (Limb::ONE, Limb::ONE),
        (Limb::ONE, Limb::MAX),
        (Limb::MAX, Limb::ZERO),
        (Limb::MAX, Limb::ONE),
        (Limb::MAX, Limb::MAX),
    ];

    #[test]
    fn wrapping_new() {
        assert_eq!(Wrapping::<Limb>::default().0, Limb::default());
        assert_eq!(<Wrapping<Limb> as crate::Zero>::zero().0, Limb::ZERO);
        assert_eq!(<Wrapping<Limb> as crate::One>::one().0, Limb::ONE);
        assert_eq!(<Wrapping<Limb> as num_traits::Zero>::zero().0, Limb::ZERO);
        assert_eq!(<Wrapping<Limb> as num_traits::One>::one().0, Limb::ONE);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn wrapping_format() {
        for a in [Limb::ZERO, Limb::ONE, Limb::MAX] {
            assert_eq!(format!("{}", Wrapping(a)), format!("{}", a));
            assert_eq!(format!("{:?}", Wrapping(a)), format!("Wrapping({:?})", a));
            assert_eq!(format!("{:b}", Wrapping(a)), format!("{:b}", a));
            assert_eq!(format!("{:o}", Wrapping(a)), format!("{:o}", a));
            assert_eq!(format!("{:x}", Wrapping(a)), format!("{:x}", a));
            assert_eq!(format!("{:X}", Wrapping(a)), format!("{:X}", a));
        }
    }
    #[test]
    fn wrapping_eq_select() {
        let pairs: &[(Limb, Limb, bool)] = &[
            (Limb::ZERO, Limb::ZERO, true),
            (Limb::ZERO, Limb::ONE, false),
            (Limb::ONE, Limb::ZERO, false),
            (Limb::ONE, Limb::ONE, true),
        ];

        for (a, b, eq) in pairs {
            assert_eq!(a.ct_eq(b).to_bool(), *eq);
            assert!(a.ct_select(b, Choice::FALSE).ct_eq(a).to_bool());
            assert!(a.ct_select(b, Choice::TRUE).ct_eq(b).to_bool());
            #[cfg(feature = "subtle")]
            assert_eq!(bool::from(subtle::ConstantTimeEq::ct_eq(a, b)), *eq);
            #[cfg(feature = "subtle")]
            assert!(
                subtle::ConditionallySelectable::conditional_select(
                    a,
                    b,
                    subtle::Choice::from(0u8)
                )
                .ct_eq(a)
                .to_bool()
            );
            #[cfg(feature = "subtle")]
            assert!(
                subtle::ConditionallySelectable::conditional_select(
                    a,
                    b,
                    subtle::Choice::from(1u8)
                )
                .ct_eq(b)
                .to_bool()
            );
        }
    }

    #[allow(clippy::op_ref)]
    #[test]
    fn wrapping_add() {
        for (a, b) in INPUTS {
            let expect = WrappingAdd::wrapping_add(a, b);
            assert_eq!((Wrapping(*a) + Wrapping(*b)).0, expect);
            assert_eq!((&Wrapping(*a) + Wrapping(*b)).0, expect);
            assert_eq!((Wrapping(*a) + &Wrapping(*b)).0, expect);
            assert_eq!((&Wrapping(*a) + &Wrapping(*b)).0, expect);
        }
    }

    #[allow(clippy::op_ref)]
    #[test]
    fn wrapping_sub() {
        for (a, b) in INPUTS {
            let expect = WrappingSub::wrapping_sub(a, b);
            assert_eq!((Wrapping(*a) - Wrapping(*b)).0, expect);
            assert_eq!((&Wrapping(*a) - Wrapping(*b)).0, expect);
            assert_eq!((Wrapping(*a) - &Wrapping(*b)).0, expect);
            assert_eq!((&Wrapping(*a) - &Wrapping(*b)).0, expect);
        }
    }

    #[allow(clippy::op_ref)]
    #[test]
    fn wrapping_mul() {
        for (a, b) in INPUTS {
            let expect = WrappingMul::wrapping_mul(a, b);
            assert_eq!((Wrapping(*a) * Wrapping(*b)).0, expect);
            assert_eq!((&Wrapping(*a) * Wrapping(*b)).0, expect);
            assert_eq!((Wrapping(*a) * &Wrapping(*b)).0, expect);
            assert_eq!((&Wrapping(*a) * &Wrapping(*b)).0, expect);
        }
    }

    #[allow(clippy::op_ref)]
    #[test]
    fn wrapping_neg() {
        assert_eq!(
            (-Wrapping(Limb::ZERO)).0,
            WrappingNeg::wrapping_neg(&Limb::ZERO)
        );
        assert_eq!(
            (-&Wrapping(Limb::ONE)).0,
            WrappingNeg::wrapping_neg(&Limb::ONE)
        );
        assert_eq!(
            (-Wrapping(Limb::MAX)).0,
            WrappingNeg::wrapping_neg(&Limb::MAX)
        );
    }

    #[allow(clippy::op_ref)]
    #[test]
    fn wrapping_shift() {
        for a in [Limb::ZERO, Limb::ONE, Limb::MAX] {
            assert_eq!((Wrapping(a) << 1).0, WrappingShl::wrapping_shl(&a, 1));
            assert_eq!((&Wrapping(a) << 2).0, WrappingShl::wrapping_shl(&a, 2));
            assert_eq!((Wrapping(a) >> 1).0, WrappingShr::wrapping_shr(&a, 1));
            assert_eq!((&Wrapping(a) >> 2).0, WrappingShr::wrapping_shr(&a, 2));
        }
    }
}