Skip to main content

crypto_bigint/
traits.rs

1//! Traits provided by this crate
2
3pub use core::ops::{
4    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
5    Mul, MulAssign, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign,
6};
7pub use ctutils::{CtAssign, CtEq, CtGt, CtLt, CtNeg, CtSelect};
8pub use num_traits::{
9    ConstOne, ConstZero, WrappingAdd, WrappingMul, WrappingNeg, WrappingShl, WrappingShr,
10    WrappingSub,
11};
12
13use crate::{
14    Choice, CtOption, Limb, NonZero, Odd, Reciprocal, UintRef,
15    modular::{MontyParams, Retrieve},
16    primitives::u32_bits,
17};
18use core::fmt::{self, Debug};
19
20#[cfg(feature = "rand_core")]
21use rand_core::{Rng, TryRng};
22
23/// Bit counting and bit operations.
24pub trait BitOps {
25    /// Precision of this integer in bits.
26    #[must_use]
27    fn bits_precision(&self) -> u32;
28
29    /// `floor(log2(self.bits_precision()))`.
30    #[must_use]
31    fn log2_bits(&self) -> u32 {
32        u32_bits(self.bits_precision()) - 1
33    }
34
35    /// Precision of this integer in bytes.
36    #[must_use]
37    fn bytes_precision(&self) -> usize;
38
39    /// Get the value of the bit at position `index`, as a truthy or falsy `Choice`.
40    /// Returns the falsy value for indices out of range.
41    #[must_use]
42    fn bit(&self, index: u32) -> Choice;
43
44    /// Sets the bit at `index` to 0 or 1 depending on the value of `bit_value`.
45    fn set_bit(&mut self, index: u32, bit_value: Choice);
46
47    /// Returns the minimum number of bits required to represent `self`.
48    ///
49    /// Returns zero if `self` is zero.
50    #[must_use]
51    #[allow(deprecated)]
52    fn bit_width(&self) -> u32 {
53        // Preserve overrides in existing implementations of this trait.
54        self.bits()
55    }
56
57    /// Deprecated alias for [`Self::bit_width`].
58    #[deprecated(since = "0.7.11", note = "please use `bit_width` instead")]
59    #[must_use]
60    fn bits(&self) -> u32 {
61        self.bits_precision() - self.leading_zeros()
62    }
63
64    /// Calculate the number of trailing zeros in the binary representation of this number.
65    #[must_use]
66    fn trailing_zeros(&self) -> u32;
67
68    /// Calculate the number of trailing ones in the binary representation of this number.
69    #[must_use]
70    fn trailing_ones(&self) -> u32;
71
72    /// Calculate the number of leading zeros in the binary representation of this number.
73    #[must_use]
74    fn leading_zeros(&self) -> u32;
75
76    /// Returns `true` if the bit at position `index` is set, `false` otherwise.
77    ///
78    /// # Remarks
79    /// This operation is variable time with respect to `index` only.
80    #[must_use]
81    fn bit_vartime(&self, index: u32) -> bool;
82
83    /// Returns the minimum number of bits required to represent `self`, in variable time
84    /// with respect to `self`.
85    ///
86    /// Returns zero if `self` is zero.
87    #[must_use]
88    #[allow(deprecated)]
89    fn bit_width_vartime(&self) -> u32 {
90        // Preserve overrides in existing implementations of this trait.
91        self.bits_vartime()
92    }
93
94    /// Deprecated alias for [`Self::bit_width_vartime`].
95    #[deprecated(since = "0.7.11", note = "please use `bit_width_vartime` instead")]
96    #[must_use]
97    fn bits_vartime(&self) -> u32 {
98        self.bit_width()
99    }
100
101    /// Sets the bit at `index` to 0 or 1 depending on the value of `bit_value`,
102    /// variable time in `self`.
103    fn set_bit_vartime(&mut self, index: u32, bit_value: bool);
104
105    /// Calculate the number of leading zeros in the binary representation of this number.
106    #[must_use]
107    fn leading_zeros_vartime(&self) -> u32 {
108        self.bits_precision() - self.bit_width_vartime()
109    }
110
111    /// Calculate the number of trailing zeros in the binary representation of this number in
112    /// variable-time with respect to `self`.
113    #[must_use]
114    fn trailing_zeros_vartime(&self) -> u32 {
115        self.trailing_zeros()
116    }
117
118    /// Calculate the number of trailing ones in the binary representation of this number,
119    /// variable time in `self`.
120    #[must_use]
121    fn trailing_ones_vartime(&self) -> u32 {
122        self.trailing_ones()
123    }
124}
125
126/// Integers whose representation takes a bounded amount of space.
127pub trait Bounded {
128    /// Size of this integer in bits.
129    const BITS: u32;
130
131    /// Size of this integer in bytes.
132    const BYTES: usize;
133}
134
135/// Integer trait: represents common functionality of integer types provided by this crate.
136pub trait Integer:
137    'static
138    + sealed::Sealed
139    + Add<Output = Self>
140    + for<'a> Add<&'a Self, Output = Self>
141    + AddAssign<Self>
142    + for<'a> AddAssign<&'a Self>
143    + AsRef<[Limb]>
144    + AsMut<[Limb]>
145    + BitAnd<Output = Self>
146    + for<'a> BitAnd<&'a Self, Output = Self>
147    + BitAndAssign
148    + for<'a> BitAndAssign<&'a Self>
149    + BitOr<Output = Self>
150    + for<'a> BitOr<&'a Self, Output = Self>
151    + BitOrAssign
152    + for<'a> BitOrAssign<&'a Self>
153    + BitXor<Output = Self>
154    + for<'a> BitXor<&'a Self, Output = Self>
155    + BitXorAssign
156    + for<'a> BitXorAssign<&'a Self>
157    + CheckedAdd
158    + CheckedSub
159    + CheckedMul
160    + CheckedDiv
161    + CheckedSquareRoot<Output = Self>
162    + Clone
163    + CtAssign
164    + CtEq
165    + CtGt
166    + CtLt
167    + CtSelect
168    + Debug
169    + Default
170    + DivAssign<NonZero<Self>>
171    + for<'a> DivAssign<&'a NonZero<Self>>
172    + Eq
173    + fmt::LowerHex
174    + fmt::UpperHex
175    + fmt::Binary
176    + Mul<Output = Self>
177    + for<'a> Mul<&'a Self, Output = Self>
178    + MulAssign<Self>
179    + for<'a> MulAssign<&'a Self>
180    + Not<Output = Self>
181    + One
182    + Ord
183    + Rem<NonZero<Self>, Output = Self>
184    + for<'a> Rem<&'a NonZero<Self>, Output = Self>
185    + RemAssign<NonZero<Self>>
186    + for<'a> RemAssign<&'a NonZero<Self>>
187    + Send
188    + Sized
189    + Shl<u32, Output = Self>
190    + ShlAssign<u32>
191    + ShlVartime
192    + Shr<u32, Output = Self>
193    + ShrAssign<u32>
194    + ShrVartime
195    + Sub<Output = Self>
196    + for<'a> Sub<&'a Self, Output = Self>
197    + SubAssign<Self>
198    + for<'a> SubAssign<&'a Self>
199    + Sync
200    + WrappingAdd
201    + WrappingSub
202    + WrappingMul
203    + WrappingNeg
204    + WrappingShl
205    + WrappingShr
206    + Zero
207{
208    /// Borrow the raw limbs used to represent this integer.
209    #[must_use]
210    fn as_limbs(&self) -> &[Limb];
211
212    /// Mutably borrow the raw limbs used to represent this integer.
213    #[must_use]
214    fn as_mut_limbs(&mut self) -> &mut [Limb];
215
216    /// Number of limbs in this integer.
217    #[must_use]
218    fn nlimbs(&self) -> usize;
219
220    /// Is this integer value an odd number?
221    ///
222    /// # Returns
223    ///
224    /// If odd, returns `Choice(1)`. Otherwise, returns `Choice(0)`.
225    #[must_use]
226    fn is_odd(&self) -> Choice {
227        self.as_ref()
228            .first()
229            .copied()
230            .map_or(Choice::FALSE, Limb::is_odd)
231    }
232
233    /// Is this integer value an even number?
234    ///
235    /// # Returns
236    ///
237    /// If even, returns `Choice(1)`. Otherwise, returns `Choice(0)`.
238    #[must_use]
239    fn is_even(&self) -> Choice {
240        !self.is_odd()
241    }
242}
243
244/// Signed [`Integer`]s.
245pub trait Signed:
246    Div<NonZero<Self>, Output = CtOption<Self>>
247    + for<'a> Div<&'a NonZero<Self>, Output = CtOption<Self>>
248    + From<i8>
249    + From<i16>
250    + From<i32>
251    + From<i64>
252    + Gcd<Output = Self::Unsigned>
253    + Integer // + CtNeg TODO(tarcieri)
254{
255    /// Corresponding unsigned integer type.
256    type Unsigned: Unsigned;
257
258    /// The sign and magnitude of this [`Signed`].
259    #[must_use]
260    fn abs_sign(&self) -> (Self::Unsigned, Choice);
261
262    /// The magnitude of this [`Signed`].
263    #[must_use]
264    fn abs(&self) -> Self::Unsigned {
265        self.abs_sign().0
266    }
267
268    /// Whether this [`Signed`] is negative (and non-zero), as a [`Choice`].
269    #[must_use]
270    fn is_negative(&self) -> Choice;
271
272    /// Whether this [`Signed`] is positive (and non-zero), as a [`Choice`].
273    #[must_use]
274    fn is_positive(&self) -> Choice;
275}
276
277/// Unsigned [`Integer`]s.
278pub trait Unsigned:
279    AsRef<UintRef>
280    + AsMut<UintRef>
281    + AddMod<Output = Self>
282    + BitOps
283    + Div<NonZero<Self>, Output = Self>
284    + for<'a> Div<&'a NonZero<Self>, Output = Self>
285    + DivRemLimb
286    + FloorSquareRoot<Output = Self>
287    + From<u8>
288    + From<u16>
289    + From<u32>
290    + From<u64>
291    + From<Limb>
292    + Gcd<Output = Self>
293    + Integer
294    + MulMod<Output = Self>
295    + NegMod<Output = Self>
296    + RemLimb
297    + SquareMod<Output = Self>
298    + SubMod<Output = Self>
299{
300    /// Borrow the limbs of this unsigned integer as a [`UintRef`].
301    #[must_use]
302    fn as_uint_ref(&self) -> &UintRef;
303
304    /// Mutably borrow the limbs of this unsigned integer as a [`UintRef`].
305    fn as_mut_uint_ref(&mut self) -> &mut UintRef;
306
307    /// Returns an integer with the first limb set to `limb`, and the same precision as `other`.
308    #[must_use]
309    fn from_limb_like(limb: Limb, other: &Self) -> Self;
310}
311
312/// [`Unsigned`] integers with an associated [`MontyForm`].
313pub trait UnsignedWithMontyForm: Unsigned {
314    /// The corresponding Montgomery representation,
315    /// optimized for the performance of modular operations at the price of a conversion overhead.
316    type MontyForm: MontyForm<Integer = Self>;
317}
318
319/// Support for upgrading `UintRef`-compatible references into `Unsigned`.
320pub trait ToUnsigned: AsRef<UintRef> + AsMut<UintRef> {
321    /// The corresponding owned `Unsigned` type.
322    type Unsigned: Unsigned;
323
324    /// Convert from a reference into an owned instance.
325    fn to_unsigned(&self) -> Self::Unsigned;
326
327    /// Convert from a reference into an owned instance representing zero.
328    fn to_unsigned_zero(&self) -> Self::Unsigned {
329        let mut res = self.to_unsigned();
330        res.set_zero();
331        res
332    }
333}
334
335impl<T: Unsigned> ToUnsigned for T {
336    type Unsigned = T;
337
338    fn to_unsigned(&self) -> Self::Unsigned {
339        self.clone()
340    }
341
342    fn to_unsigned_zero(&self) -> Self::Unsigned {
343        T::zero_like(self)
344    }
345}
346
347/// Zero values: additive identity element for `Self`.
348pub trait Zero: CtEq + Sized {
349    /// Returns the additive identity element of `Self`, `0`.
350    #[must_use]
351    fn zero() -> Self;
352
353    /// Determine if this value is equal to `0`.
354    ///
355    /// # Returns
356    ///
357    /// If zero, returns `Choice(1)`. Otherwise, returns `Choice(0)`.
358    #[inline]
359    #[must_use]
360    fn is_zero(&self) -> Choice {
361        self.ct_eq(&Self::zero())
362    }
363
364    /// Set `self` to its additive identity, i.e. `Self::zero`.
365    #[inline]
366    fn set_zero(&mut self) {
367        *self = Zero::zero();
368    }
369
370    /// Return the value `0` with the same precision as `other`.
371    #[must_use]
372    fn zero_like(other: &Self) -> Self
373    where
374        Self: Clone,
375    {
376        let mut ret = other.clone();
377        ret.set_zero();
378        ret
379    }
380}
381
382/// One values: multiplicative identity element for `Self`.
383pub trait One: CtEq + Sized {
384    /// Returns the multiplicative identity element of `Self`, `1`.
385    #[must_use]
386    fn one() -> Self;
387
388    /// Determine if this value is equal to `1`.
389    ///
390    /// # Returns
391    ///
392    /// If one, returns `Choice(1)`. Otherwise, returns `Choice(0)`.
393    #[inline]
394    #[must_use]
395    fn is_one(&self) -> Choice {
396        self.ct_eq(&Self::one())
397    }
398
399    /// Set `self` to its multiplicative identity, i.e. `Self::one`.
400    #[inline]
401    fn set_one(&mut self) {
402        *self = One::one();
403    }
404
405    /// Return the value `0` with the same precision as `other`.
406    #[must_use]
407    fn one_like(_other: &Self) -> Self {
408        One::one()
409    }
410}
411
412/// Trait for associating constant values with a type.
413pub trait Constants: ConstZero + ConstOne {
414    /// Maximum value this integer can express.
415    const MAX: Self;
416}
417
418/// Fixed-width [`Integer`]s.
419pub trait FixedInteger: Bounded + Constants + Copy + Integer {
420    /// The number of limbs used on this platform.
421    const LIMBS: usize;
422}
423
424/// Compute the greatest common divisor of two integers.
425pub trait Gcd<Rhs = Self>: Sized {
426    /// Output type.
427    type Output;
428
429    /// Compute the greatest common divisor of `self` and `rhs`.
430    #[must_use]
431    fn gcd(&self, rhs: &Rhs) -> Self::Output;
432
433    /// Compute the greatest common divisor of `self` and `rhs` in variable time.
434    #[must_use]
435    fn gcd_vartime(&self, rhs: &Rhs) -> Self::Output;
436}
437
438/// Compute the extended greatest common divisor of two integers.
439pub trait Xgcd<Rhs = Self>: Sized {
440    /// Output type.
441    type Output;
442
443    /// Compute the extended greatest common divisor of `self` and `rhs`.
444    #[must_use]
445    fn xgcd(&self, rhs: &Rhs) -> Self::Output;
446
447    /// Compute the extended greatest common divisor of `self` and `rhs` in variable time.
448    #[must_use]
449    fn xgcd_vartime(&self, rhs: &Rhs) -> Self::Output;
450}
451
452/// Compute the least common multiple of two integers.
453pub trait Lcm<Rhs = Self>: Sized {
454    /// Output type.
455    type Output;
456
457    /// Compute the least common multiple of `self` and `rhs`.
458    #[must_use]
459    fn lcm(&self, rhs: &Rhs) -> Self::Output;
460
461    /// Compute the least common multiple of `self` and `rhs` in variable time.
462    #[must_use]
463    fn lcm_vartime(&self, rhs: &Rhs) -> Self::Output;
464}
465
466/// Random number generation support.
467#[cfg(feature = "rand_core")]
468pub trait Random: Sized {
469    /// Generate a random value.
470    ///
471    /// If `rng` is a CSRNG, the generation is cryptographically secure as well.
472    ///
473    /// # Errors
474    /// - Returns `R::Error` in the event the RNG experienced an internal failure.
475    fn try_random_from_rng<R: TryRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error>;
476
477    /// Generate a random value.
478    ///
479    /// If `rng` is a CSRNG, the generation is cryptographically secure as well.
480    #[must_use]
481    fn random_from_rng<R: Rng + ?Sized>(rng: &mut R) -> Self {
482        let Ok(out) = Self::try_random_from_rng(rng);
483        out
484    }
485
486    /// Randomly generate a value of this type using the system's ambient cryptographically secure
487    /// random number generator.
488    ///
489    /// # Errors
490    /// Returns [`getrandom::Error`] in the event the system's ambient RNG experiences an internal
491    /// failure.
492    #[cfg(feature = "getrandom")]
493    fn try_random() -> Result<Self, getrandom::Error> {
494        Self::try_random_from_rng(&mut getrandom::SysRng)
495    }
496
497    /// Randomly generate a value of this type using the system's ambient cryptographically secure
498    /// random number generator.
499    ///
500    /// # Panics
501    /// This method will panic in the event the system's ambient RNG experiences an internal
502    /// failure.
503    ///
504    /// This shouldn't happen on most modern operating systems.
505    #[cfg(feature = "getrandom")]
506    #[must_use]
507    fn random() -> Self {
508        Self::try_random().expect("RNG failure")
509    }
510}
511
512/// Possible errors of the methods in [`RandomBits`] trait.
513#[cfg(feature = "rand_core")]
514#[derive(Debug)]
515pub enum RandomBitsError<T> {
516    /// An error of the internal RNG library.
517    RandCore(T),
518    /// The requested `bits_precision` does not match the size of the integer
519    /// corresponding to the type (in the cases where this is set in compile time).
520    BitsPrecisionMismatch {
521        /// The requested precision.
522        bits_precision: u32,
523        /// The compile-time size of the integer.
524        integer_bits: u32,
525    },
526    /// The requested `bit_length` is larger than `bits_precision`.
527    BitLengthTooLarge {
528        /// The requested bit length of the random number.
529        bit_length: u32,
530        /// The requested precision.
531        bits_precision: u32,
532    },
533}
534
535#[cfg(feature = "rand_core")]
536impl<T> fmt::Display for RandomBitsError<T>
537where
538    T: fmt::Display,
539{
540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541        match self {
542            Self::RandCore(err) => write!(f, "{err}"),
543            Self::BitsPrecisionMismatch {
544                bits_precision,
545                integer_bits,
546            } => write!(
547                f,
548                concat![
549                    "The requested `bits_precision` ({}) does not match ",
550                    "the size of the integer corresponding to the type ({})"
551                ],
552                bits_precision, integer_bits
553            ),
554            Self::BitLengthTooLarge {
555                bit_length,
556                bits_precision,
557            } => write!(
558                f,
559                "The requested `bit_length` ({bit_length}) is larger than `bits_precision` ({bits_precision}).",
560            ),
561        }
562    }
563}
564
565#[cfg(feature = "rand_core")]
566impl<T> core::error::Error for RandomBitsError<T> where T: Debug + fmt::Display {}
567
568/// Random bits generation support.
569#[cfg(feature = "rand_core")]
570pub trait RandomBits: Sized {
571    /// Generate a random value in range `[0, 2^bit_length)`.
572    ///
573    /// A wrapper for [`RandomBits::try_random_bits`] that panics on error.
574    #[must_use]
575    fn random_bits<R: TryRng + ?Sized>(rng: &mut R, bit_length: u32) -> Self {
576        Self::try_random_bits(rng, bit_length).expect("try_random_bits() failed")
577    }
578
579    /// Generate a random value in range `[0, 2^bit_length)`.
580    ///
581    /// This method is variable time wrt `bit_length`.
582    ///
583    /// If `rng` is a CSRNG, the generation is cryptographically secure as well.
584    ///
585    /// # Errors
586    /// - Returns `R::Error` in the event the RNG experienced an internal failure.
587    fn try_random_bits<R: TryRng + ?Sized>(
588        rng: &mut R,
589        bit_length: u32,
590    ) -> Result<Self, RandomBitsError<R::Error>>;
591
592    /// Generate a random value in range `[0, 2^bit_length)`,
593    /// returning an integer with the closest available size to `bits_precision`
594    /// (if the implementing type supports runtime sizing).
595    ///
596    /// A wrapper for [`RandomBits::try_random_bits_with_precision`] that panics on error.
597    #[must_use]
598    #[track_caller]
599    fn random_bits_with_precision<R: TryRng + ?Sized>(
600        rng: &mut R,
601        bit_length: u32,
602        bits_precision: u32,
603    ) -> Self {
604        Self::try_random_bits_with_precision(rng, bit_length, bits_precision)
605            .expect("try_random_bits_with_precision() failed")
606    }
607
608    /// Generate a random value in range `[0, 2^bit_length)`,
609    /// returning an integer with the closest available size to `bits_precision`
610    /// (if the implementing type supports runtime sizing).
611    ///
612    /// This method is variable time wrt `bit_length`.
613    ///
614    /// If `rng` is a CSRNG, the generation is cryptographically secure as well.
615    ///
616    /// # Errors
617    /// - Returns `R::Error` in the event the RNG experienced an internal failure.
618    fn try_random_bits_with_precision<R: TryRng + ?Sized>(
619        rng: &mut R,
620        bit_length: u32,
621        bits_precision: u32,
622    ) -> Result<Self, RandomBitsError<R::Error>>;
623}
624
625/// Modular random number generation support.
626#[cfg(feature = "rand_core")]
627pub trait RandomMod: Sized + Zero {
628    /// Generate a random number which is less than a given `modulus`.
629    ///
630    /// This uses rejection sampling.
631    ///
632    /// As a result, it runs in variable time that depends in part on
633    /// `modulus`. If the generator `rng` is cryptographically secure (for
634    /// example, it implements `CryptoRng`), then this is guaranteed not to
635    /// leak anything about the output value aside from it being less than
636    /// `modulus`.
637    #[must_use]
638    fn random_mod_vartime<R: Rng + ?Sized>(rng: &mut R, modulus: &NonZero<Self>) -> Self {
639        let Ok(out) = Self::try_random_mod_vartime(rng, modulus);
640        out
641    }
642
643    /// Generate a random number which is less than a given `modulus`.
644    ///
645    /// This uses rejection sampling.
646    ///
647    /// As a result, it runs in variable time that depends in part on
648    /// `modulus`. If the generator `rng` is cryptographically secure (for
649    /// example, it implements `CryptoRng`), then this is guaranteed not to
650    /// leak anything about the output value aside from it being less than
651    /// `modulus`.
652    ///
653    /// # Errors
654    /// - Returns `R::Error` in the event the RNG experienced an internal failure.
655    fn try_random_mod_vartime<R: TryRng + ?Sized>(
656        rng: &mut R,
657        modulus: &NonZero<Self>,
658    ) -> Result<Self, R::Error>;
659
660    /// Generate a random number which is less than a given `modulus`.
661    ///
662    /// This uses rejection sampling.
663    ///
664    /// As a result, it runs in variable time that depends in part on
665    /// `modulus`. If the generator `rng` is cryptographically secure (for
666    /// example, it implements `CryptoRng`), then this is guaranteed not to
667    /// leak anything about the output value aside from it being less than
668    /// `modulus`.
669    #[deprecated(since = "0.7.0", note = "please use `random_mod_vartime` instead")]
670    #[must_use]
671    fn random_mod<R: Rng + ?Sized>(rng: &mut R, modulus: &NonZero<Self>) -> Self {
672        Self::random_mod_vartime(rng, modulus)
673    }
674
675    /// Generate a random number which is less than a given `modulus`.
676    ///
677    /// This uses rejection sampling.
678    ///
679    /// As a result, it runs in variable time that depends in part on
680    /// `modulus`. If the generator `rng` is cryptographically secure (for
681    /// example, it implements `CryptoRng`), then this is guaranteed not to
682    /// leak anything about the output value aside from it being less than
683    /// `modulus`.
684    ///
685    /// # Errors
686    /// - Returns `R::Error` in the event the RNG experienced an internal failure.
687    #[deprecated(since = "0.7.0", note = "please use `try_random_mod_vartime` instead")]
688    fn try_random_mod<R: TryRng + ?Sized>(
689        rng: &mut R,
690        modulus: &NonZero<Self>,
691    ) -> Result<Self, R::Error> {
692        Self::try_random_mod_vartime(rng, modulus)
693    }
694}
695
696/// Compute `self + rhs mod p`.
697pub trait AddMod<Rhs = Self, Mod = NonZero<Self>> {
698    /// Output type.
699    type Output;
700
701    /// Compute `self + rhs mod p`.
702    ///
703    /// Assumes `self` and `rhs` are `< p`.
704    #[must_use]
705    fn add_mod(&self, rhs: &Rhs, p: &Mod) -> Self::Output;
706}
707
708/// Compute `self - rhs mod p`.
709pub trait SubMod<Rhs = Self, Mod = NonZero<Self>> {
710    /// Output type.
711    type Output;
712
713    /// Compute `self - rhs mod p`.
714    ///
715    /// Assumes `self` and `rhs` are `< p`.
716    #[must_use]
717    fn sub_mod(&self, rhs: &Rhs, p: &Mod) -> Self::Output;
718}
719
720/// Compute `-self mod p`.
721pub trait NegMod<Mod = NonZero<Self>> {
722    /// Output type.
723    type Output;
724
725    /// Compute `-self mod p`.
726    #[must_use]
727    fn neg_mod(&self, p: &Mod) -> Self::Output;
728}
729
730/// Compute `self * rhs mod p`.
731pub trait MulMod<Rhs = Self, Mod = NonZero<Self>> {
732    /// Output type.
733    type Output;
734
735    /// Compute `self * rhs mod p`.
736    #[must_use]
737    fn mul_mod(&self, rhs: &Rhs, p: &Mod) -> Self::Output;
738}
739
740/// Compute `self * self mod p`.
741pub trait SquareMod<Mod = NonZero<Self>> {
742    /// Output type.
743    type Output;
744
745    /// Compute `self * self mod p`.
746    #[must_use]
747    fn square_mod(&self, p: &Mod) -> Self::Output;
748}
749
750/// Compute `1 / self mod p`.
751#[deprecated(since = "0.7.0", note = "please use `InvertMod` instead")]
752pub trait InvMod<Rhs = Self>: Sized {
753    /// Output type.
754    type Output;
755
756    /// Compute `1 / self mod p`.
757    #[must_use]
758    fn inv_mod(&self, p: &Rhs) -> CtOption<Self::Output>;
759}
760
761#[allow(deprecated)]
762impl<T, Rhs> InvMod<Rhs> for T
763where
764    T: InvertMod<Rhs>,
765{
766    type Output = <T as InvertMod<Rhs>>::Output;
767
768    fn inv_mod(&self, p: &Rhs) -> CtOption<Self::Output> {
769        self.invert_mod(p)
770    }
771}
772
773/// Compute `1 / self mod p`.
774pub trait InvertMod<Mod = NonZero<Self>>: Sized {
775    /// Output type.
776    type Output;
777
778    /// Compute `1 / self mod p`.
779    #[must_use]
780    fn invert_mod(&self, p: &Mod) -> CtOption<Self::Output>;
781}
782
783/// Checked addition.
784pub trait CheckedAdd<Rhs = Self>: Sized {
785    /// Perform checked addition, returning a [`CtOption`] which `is_some` only if the operation
786    /// did not overflow.
787    #[must_use]
788    fn checked_add(&self, rhs: &Rhs) -> CtOption<Self>;
789}
790
791/// Checked division.
792pub trait CheckedDiv<Rhs = Self>: Sized {
793    /// Perform checked division, returning a [`CtOption`] which `is_some` only if the divisor is
794    /// non-zero.
795    #[must_use]
796    fn checked_div(&self, rhs: &Rhs) -> CtOption<Self>;
797}
798
799/// Checked multiplication.
800pub trait CheckedMul<Rhs = Self>: Sized {
801    /// Perform checked multiplication, returning a [`CtOption`] which `is_some`
802    /// only if the operation did not overflow.
803    #[must_use]
804    fn checked_mul(&self, rhs: &Rhs) -> CtOption<Self>;
805}
806
807/// Checked subtraction.
808pub trait CheckedSub<Rhs = Self>: Sized {
809    /// Perform checked subtraction, returning a [`CtOption`] which `is_some`
810    /// only if the operation did not underflow.
811    #[must_use]
812    fn checked_sub(&self, rhs: &Rhs) -> CtOption<Self>;
813}
814
815/// Define the result of concatenating two numbers into a "wide" value.
816pub trait Concat<const HI: usize> {
817    /// Concatenated output: having the width of `Self` plus `HI`.
818    type Output: Integer;
819}
820
821/// Define the result of splitting a number into two parts, with the
822/// first part having the width `LO`.
823pub trait Split<const LO: usize> {
824    /// High limbs of output: having the width of `Self` minus `LO`.
825    type Output: Integer;
826}
827
828/// Define the result of splitting a number into two parts, with
829/// each part having an equal width.
830pub trait SplitEven {
831    /// Split output: each component having half the width of `Self`.
832    type Output: Integer;
833}
834
835/// Support for optimized squaring
836pub trait Square {
837    /// Computes the same as `self * self`, but may be more efficient.
838    #[must_use]
839    fn square(&self) -> Self;
840}
841
842/// Support for optimized squaring in-place
843pub trait SquareAssign {
844    /// Computes the same as `self * self`, but may be more efficient.
845    /// Writes the result in `self`.
846    fn square_assign(&mut self);
847}
848
849/// Support for calculating checked square roots.
850pub trait CheckedSquareRoot: Sized {
851    /// Output of the square root operation.
852    type Output;
853
854    /// Computes `sqrt(self)`, returning `none` if no root exists.
855    #[must_use]
856    fn checked_sqrt(&self) -> CtOption<Self::Output>;
857
858    /// Computes `sqrt(self)`, returning `none` if no root exists.
859    ///
860    /// Variable time with respect to `self`.
861    #[must_use]
862    fn checked_sqrt_vartime(&self) -> Option<Self::Output>;
863}
864
865/// Support for calculating floored square roots.
866pub trait FloorSquareRoot: CheckedSquareRoot {
867    /// Computes `floor(sqrt(self))`.
868    #[must_use]
869    fn floor_sqrt(&self) -> Self::Output;
870
871    /// Computes `floor(sqrt(self))`.
872    ///
873    /// Variable time with respect to `self`.
874    #[must_use]
875    fn floor_sqrt_vartime(&self) -> Self::Output;
876}
877
878/// Support for optimized division by a single limb.
879pub trait DivRemLimb: Sized {
880    /// Computes `self / rhs` using a pre-made reciprocal,
881    /// returns the quotient (q) and remainder (r).
882    #[must_use]
883    fn div_rem_limb(&self, rhs: NonZero<Limb>) -> (Self, Limb) {
884        self.div_rem_limb_with_reciprocal(&Reciprocal::new(rhs))
885    }
886
887    /// Computes `self / rhs`, returns the quotient (q) and remainder (r).
888    #[must_use]
889    fn div_rem_limb_with_reciprocal(&self, reciprocal: &Reciprocal) -> (Self, Limb);
890}
891
892/// Support for calculating the remainder of two differently sized integers.
893pub trait RemMixed<Reductor>: Sized {
894    /// Calculate the remainder of `self` by the `reductor`.
895    #[must_use]
896    fn rem_mixed(&self, reductor: &NonZero<Reductor>) -> Reductor;
897}
898
899/// Modular reduction from a larger value `T`.
900///
901/// This can be seen as fixed modular reduction, where the modulus is fixed at compile time
902/// by `Self`.
903///
904/// For modular reduction with a variable modulus, use [`Rem`].
905pub trait Reduce<T>: Sized {
906    /// Reduces `self` modulo `Modulus`.
907    #[must_use]
908    fn reduce(value: &T) -> Self;
909}
910
911/// Division in variable time.
912pub trait DivVartime: Sized {
913    /// Computes `self / rhs` in variable time.
914    #[must_use]
915    fn div_vartime(&self, rhs: &NonZero<Self>) -> Self;
916}
917
918/// Support for optimized division by a single limb.
919pub trait RemLimb: Sized {
920    /// Computes `self % rhs` using a pre-made reciprocal.
921    #[must_use]
922    fn rem_limb(&self, rhs: NonZero<Limb>) -> Limb {
923        self.rem_limb_with_reciprocal(&Reciprocal::new(rhs))
924    }
925
926    /// Computes `self % rhs`.
927    #[must_use]
928    fn rem_limb_with_reciprocal(&self, reciprocal: &Reciprocal) -> Limb;
929}
930
931/// Constant-time exponentiation.
932pub trait Pow<Exponent> {
933    /// Raises to the `exponent` power.
934    #[must_use]
935    fn pow(&self, exponent: &Exponent) -> Self;
936}
937
938impl<T: PowBoundedExp<Exponent>, Exponent: Unsigned> Pow<Exponent> for T {
939    fn pow(&self, exponent: &Exponent) -> Self {
940        self.pow_bounded_exp(exponent, exponent.bits_precision())
941    }
942}
943
944/// Constant-time exponentiation with exponent of a bounded bit size.
945pub trait PowBoundedExp<Exponent> {
946    /// Raises to the `exponent` power,
947    /// with `exponent_bits` representing the number of (least significant) bits
948    /// to take into account for the exponent.
949    ///
950    /// NOTE: `exponent_bits` may be leaked in the time pattern.
951    #[must_use]
952    fn pow_bounded_exp(&self, exponent: &Exponent, exponent_bits: u32) -> Self;
953}
954
955/// Performs modular multi-exponentiation using Montgomery's ladder.
956///
957/// See: Straus, E. G. Problems and solutions: Addition chains of vectors. American Mathematical Monthly 71 (1964), 806–808.
958pub trait MultiExponentiate<Exponent, BasesAndExponents>: Pow<Exponent> + Sized
959where
960    BasesAndExponents: AsRef<[(Self, Exponent)]> + ?Sized,
961{
962    /// Calculates `x1 ^ k1 * ... * xn ^ kn`.
963    #[must_use]
964    fn multi_exponentiate(bases_and_exponents: &BasesAndExponents) -> Self;
965}
966
967impl<T, Exponent, BasesAndExponents> MultiExponentiate<Exponent, BasesAndExponents> for T
968where
969    T: MultiExponentiateBoundedExp<Exponent, BasesAndExponents>,
970    Exponent: Bounded,
971    BasesAndExponents: AsRef<[(Self, Exponent)]> + ?Sized,
972{
973    fn multi_exponentiate(bases_and_exponents: &BasesAndExponents) -> Self {
974        Self::multi_exponentiate_bounded_exp(bases_and_exponents, Exponent::BITS)
975    }
976}
977
978/// Performs modular multi-exponentiation using Montgomery's ladder.
979/// `exponent_bits` represents the number of bits to take into account for the exponent.
980///
981/// See: Straus, E. G. Problems and solutions: Addition chains of vectors. American Mathematical Monthly 71 (1964), 806–808.
982///
983/// NOTE: this value is leaked in the time pattern.
984pub trait MultiExponentiateBoundedExp<Exponent, BasesAndExponents>: Pow<Exponent> + Sized
985where
986    BasesAndExponents: AsRef<[(Self, Exponent)]> + ?Sized,
987{
988    /// Calculates `x1 ^ k1 * ... * xn ^ kn`.
989    #[must_use]
990    fn multi_exponentiate_bounded_exp(
991        bases_and_exponents: &BasesAndExponents,
992        exponent_bits: u32,
993    ) -> Self;
994}
995
996/// Constant-time inversion.
997pub trait Invert {
998    /// Output of the inversion.
999    type Output;
1000
1001    /// Computes the inverse.
1002    fn invert(&self) -> Self::Output;
1003
1004    /// Computes the inverse in variable-time.
1005    fn invert_vartime(&self) -> Self::Output {
1006        self.invert()
1007    }
1008}
1009
1010/// Widening multiply: returns a value with a number of limbs equal to the sum of the inputs.
1011pub trait ConcatenatingMul<Rhs = Self>: Sized {
1012    /// Output of the widening multiplication.
1013    type Output: Integer;
1014
1015    /// Perform widening multiplication.
1016    #[must_use]
1017    fn concatenating_mul(&self, rhs: Rhs) -> Self::Output;
1018}
1019
1020/// Widening square: returns a value with a number of limbs equal to double the sum of the input.
1021pub trait ConcatenatingSquare: Sized {
1022    /// Output of the widening multiplication.
1023    type Output: Integer;
1024
1025    /// Perform widening squaring.
1026    #[must_use]
1027    fn concatenating_square(&self) -> Self::Output;
1028}
1029
1030/// Widening multiply: returns a value with a number of limbs equal to the sum of the inputs.
1031#[deprecated(since = "0.7.0", note = "please use `ConcatenatingMul` instead")]
1032pub trait WideningMul<Rhs = Self>: Sized {
1033    /// Output of the widening multiplication.
1034    type Output: Integer;
1035
1036    /// Perform widening multiplication.
1037    #[must_use]
1038    fn widening_mul(&self, rhs: Rhs) -> Self::Output;
1039}
1040
1041#[allow(deprecated)]
1042impl<T, Rhs> WideningMul<Rhs> for T
1043where
1044    T: ConcatenatingMul<Rhs>,
1045{
1046    type Output = <T as ConcatenatingMul<Rhs>>::Output;
1047
1048    fn widening_mul(&self, rhs: Rhs) -> Self::Output {
1049        self.concatenating_mul(rhs)
1050    }
1051}
1052
1053/// Left shifts, variable time in `shift`.
1054pub trait ShlVartime: Sized {
1055    /// Computes `self << shift`.
1056    ///
1057    /// Returns `None` if `shift >= self.bits_precision()`.
1058    fn overflowing_shl_vartime(&self, shift: u32) -> Option<Self>;
1059
1060    /// Computes `self << shift`.
1061    ///
1062    /// Returns zero if `shift >= self.bits_precision()`.
1063    #[must_use]
1064    fn unbounded_shl_vartime(&self, shift: u32) -> Self;
1065
1066    /// Computes `self << shift` in a panic-free manner, masking off bits of `shift`
1067    /// which would cause the shift to exceed the type's width.
1068    #[must_use]
1069    fn wrapping_shl_vartime(&self, shift: u32) -> Self;
1070}
1071
1072/// Right shifts, variable time in `shift`.
1073pub trait ShrVartime: Sized {
1074    /// Computes `self >> shift`.
1075    ///
1076    /// Returns `None` if `shift >= self.bits_precision()`.
1077    fn overflowing_shr_vartime(&self, shift: u32) -> Option<Self>;
1078
1079    /// Computes `self >> shift`.
1080    ///
1081    /// Returns zero if `shift >= self.bits_precision()`.
1082    #[must_use]
1083    fn unbounded_shr_vartime(&self, shift: u32) -> Self;
1084
1085    /// Computes `self >> shift` in a panic-free manner, masking off bits of `shift`
1086    /// which would cause the shift to exceed the type's width.
1087    #[must_use]
1088    fn wrapping_shr_vartime(&self, shift: u32) -> Self;
1089}
1090
1091/// Methods for resizing the allocated storage.
1092pub trait Resize: Sized {
1093    /// The result of the resizing.
1094    type Output;
1095
1096    /// Resizes to the minimum storage that fits `at_least_bits_precision`
1097    /// without checking if the bit size of `self` is larger than `at_least_bits_precision`.
1098    ///
1099    /// Variable-time w.r.t. `at_least_bits_precision`.
1100    #[must_use]
1101    fn resize_unchecked(self, at_least_bits_precision: u32) -> Self::Output;
1102
1103    /// Resizes to the minimum storage that fits `at_least_bits_precision`
1104    /// returning `None` if the bit size of `self` is larger than `at_least_bits_precision`.
1105    ///
1106    /// Variable-time w.r.t. `at_least_bits_precision`.
1107    fn try_resize(self, at_least_bits_precision: u32) -> Option<Self::Output>;
1108
1109    /// Resizes to the minimum storage that fits `at_least_bits_precision`
1110    /// panicking if the bit size of `self` is larger than `at_least_bits_precision`.
1111    ///
1112    /// Variable-time w.r.t. `at_least_bits_precision`.
1113    #[must_use]
1114    #[track_caller]
1115    fn resize(self, at_least_bits_precision: u32) -> Self::Output {
1116        self.try_resize(at_least_bits_precision).unwrap_or_else(|| {
1117            panic!("The bit size of `self` is larger than `at_least_bits_precision`")
1118        })
1119    }
1120}
1121
1122/// A representation of an integer optimized for the performance of modular operations.
1123pub trait MontyForm:
1124    'static
1125    + sealed::Sealed
1126    + Clone
1127    + CtEq
1128    + CtSelect
1129    + Debug
1130    + Eq
1131    + Invert<Output = CtOption<Self>>
1132    + Sized
1133    + Send
1134    + Sync
1135    + Add<Output = Self>
1136    + for<'a> Add<&'a Self, Output = Self>
1137    + AddAssign
1138    + for<'a> AddAssign<&'a Self>
1139    + Sub<Output = Self>
1140    + for<'a> Sub<&'a Self, Output = Self>
1141    + SubAssign
1142    + for<'a> SubAssign<&'a Self>
1143    + Mul<Output = Self>
1144    + for<'a> Mul<&'a Self, Output = Self>
1145    + MulAssign
1146    + for<'a> MulAssign<&'a Self>
1147    + Neg<Output = Self>
1148    + PowBoundedExp<Self::Integer>
1149    + Retrieve<Output = Self::Integer>
1150    + Square
1151    + SquareAssign
1152{
1153    /// The original integer type.
1154    type Integer: UnsignedWithMontyForm<MontyForm = Self>;
1155
1156    /// Prepared Montgomery multiplier for tight loops.
1157    type Multiplier<'a>: Debug + Clone + MontyMultiplier<'a, Monty = Self>;
1158
1159    /// The precomputed data needed for this representation.
1160    type Params: 'static
1161        + AsRef<MontyParams<Self::Integer>>
1162        + From<MontyParams<Self::Integer>>
1163        + Clone
1164        + Debug
1165        + Eq
1166        + Sized
1167        + Send
1168        + Sync;
1169
1170    /// Create the precomputed data for Montgomery representation of integers modulo `modulus`,
1171    /// variable time in `modulus`.
1172    #[must_use]
1173    fn new_params_vartime(modulus: Odd<Self::Integer>) -> Self::Params;
1174
1175    /// Convert the value into the representation using precomputed data.
1176    #[must_use]
1177    fn new(value: Self::Integer, params: &Self::Params) -> Self;
1178
1179    /// Returns zero in this representation.
1180    #[must_use]
1181    fn zero(params: &Self::Params) -> Self;
1182
1183    /// Determine if this value is equal to zero.
1184    ///
1185    /// # Returns
1186    ///
1187    /// If zero, returns `Choice(1)`. Otherwise, returns `Choice(0)`.
1188    #[must_use]
1189    fn is_zero(&self) -> Choice {
1190        self.as_montgomery().is_zero()
1191    }
1192
1193    /// Returns one in this representation.
1194    #[must_use]
1195    fn one(params: &Self::Params) -> Self;
1196
1197    /// Determine if this value is equal to one.
1198    ///
1199    /// # Returns
1200    ///
1201    /// If one, returns `Choice(1)`. Otherwise, returns `Choice(0)`.
1202    #[must_use]
1203    fn is_one(&self) -> Choice {
1204        self.as_montgomery().ct_eq(self.params().as_ref().one())
1205    }
1206
1207    /// Returns the parameter struct used to initialize this object.
1208    #[must_use]
1209    fn params(&self) -> &Self::Params;
1210
1211    /// Access the value in Montgomery form.
1212    #[must_use]
1213    fn as_montgomery(&self) -> &Self::Integer;
1214
1215    /// Copy the Montgomery representation from `other` into `self`.
1216    /// NOTE: the parameters remain unchanged.
1217    fn copy_montgomery_from(&mut self, other: &Self);
1218
1219    /// Create a new Montgomery representation from an integer in Montgomery form.
1220    #[must_use]
1221    fn from_montgomery(integer: Self::Integer, params: &Self::Params) -> Self;
1222
1223    /// Move the Montgomery form result out of `self` and return it.
1224    #[must_use]
1225    fn into_montgomery(self) -> Self::Integer;
1226
1227    /// Performs doubling, returning `self + self`.
1228    #[must_use]
1229    fn double(&self) -> Self;
1230
1231    /// Performs division by 2, that is returns `x` such that `x + x = self`.
1232    #[must_use]
1233    fn div_by_2(&self) -> Self;
1234
1235    /// Performs division by 2 inplace, that is finds `x` such that `x + x = self`
1236    /// and writes it into `self`.
1237    fn div_by_2_assign(&mut self) {
1238        *self = self.div_by_2();
1239    }
1240
1241    /// Calculate the sum of products of pairs `(a, b)` in `products`.
1242    ///
1243    /// This method is variable time only with the value of the modulus.
1244    /// For a modulus with leading zeros, this method is more efficient than a naive sum of products.
1245    ///
1246    /// This method will panic if `products` is empty. All terms must be associated with equivalent
1247    /// Montgomery parameters.
1248    #[must_use]
1249    fn lincomb_vartime(products: &[(&Self, &Self)]) -> Self;
1250}
1251
1252/// Prepared Montgomery multiplier for tight loops.
1253///
1254/// Allows one to perform inplace multiplication without allocations
1255/// (important for the `BoxedUint` case).
1256///
1257/// NOTE: You will be operating with Montgomery representations directly,
1258/// make sure they all correspond to the same set of parameters.
1259pub trait MontyMultiplier<'a>: From<&'a <Self::Monty as MontyForm>::Params> {
1260    /// The associated Montgomery-representation integer.
1261    type Monty: MontyForm;
1262
1263    /// Performs a Montgomery multiplication, assigning a fully reduced result to `lhs`.
1264    fn mul_assign(&mut self, lhs: &mut Self::Monty, rhs: &Self::Monty);
1265
1266    /// Performs a Montgomery squaring, assigning a fully reduced result to `lhs`.
1267    fn square_assign(&mut self, lhs: &mut Self::Monty);
1268}
1269
1270/// Prepared Montgomery multiplier for tight loops, performing "Almost Montgomery Multiplication".
1271///
1272/// NOTE: the resulting output of any of these functions will be reduced to the *bit length* of the
1273/// modulus, but not fully reduced and may exceed the modulus. A final reduction is required to
1274/// ensure AMM results are fully reduced, and should not be exposed outside the internals of this
1275/// crate.
1276pub(crate) trait AmmMultiplier<'a>: MontyMultiplier<'a> {
1277    /// Perform an "Almost Montgomery Multiplication", assigning the product to `a`.
1278    fn mul_amm_assign(
1279        &mut self,
1280        a: &mut <Self::Monty as MontyForm>::Integer,
1281        b: &<Self::Monty as MontyForm>::Integer,
1282    );
1283
1284    /// Perform a squaring using "Almost Montgomery Multiplication", assigning the result to `a`.
1285    fn square_amm_assign(&mut self, a: &mut <Self::Monty as MontyForm>::Integer);
1286}
1287
1288/// Support for sealing traits defined in this module.
1289pub(crate) mod sealed {
1290    /// Sealed trait.
1291    pub trait Sealed {}
1292}
1293
1294#[cfg(test)]
1295pub(crate) mod tests {
1296    use super::{
1297        Integer, Invert, MontyForm, Retrieve, Signed, Square, SquareAssign, ToUnsigned, Unsigned,
1298        UnsignedWithMontyForm,
1299    };
1300    use crate::{Choice, CtEq, CtSelect, Limb, NonZero, Odd, One, Reciprocal, Zero};
1301
1302    /// Apply a suite of tests against a type implementing Integer.
1303    pub fn test_integer<T: Integer>(min: T, max: T) {
1304        let zero = T::zero_like(&min);
1305        let one = T::one_like(&min);
1306        let two = one.clone() + &one;
1307        let inputs = &[zero.clone(), one.clone(), max.clone()];
1308        let nz_one = NonZero::new(one.clone()).expect("must be non-zero");
1309        let nz_two = NonZero::new(two.clone()).expect("must be non-zero");
1310
1311        // FIXME Could use itertools combinations or an equivalent iterator
1312        let pairs = &[
1313            (zero.clone(), zero.clone()),
1314            (zero.clone(), one.clone()),
1315            (zero.clone(), max.clone()),
1316            (one.clone(), zero.clone()),
1317            (one.clone(), one.clone()),
1318            (one.clone(), max.clone()),
1319            (max.clone(), zero.clone()),
1320            (max.clone(), one.clone()),
1321            (max.clone(), max.clone()),
1322        ];
1323
1324        // Test formatting
1325        #[cfg(feature = "alloc")]
1326        for a in inputs {
1327            let _ = format!("{a:?}");
1328            let _ = format!("{a:#?}");
1329            let _ = format!("{a:b}");
1330            let _ = format!("{a:x}");
1331            let _ = format!("{a:X}");
1332        }
1333
1334        // Default must be zero
1335        assert_eq!(T::default(), zero);
1336
1337        // Sanity checks
1338        assert_eq!(zero, T::zero());
1339        assert_eq!(one, T::one());
1340        assert_ne!(zero, one);
1341        assert_ne!(zero, max);
1342        assert_ne!(min, max);
1343
1344        // Even/odd trait methods
1345        assert!(zero.is_even().to_bool());
1346        assert!(!zero.is_odd().to_bool());
1347        assert!(!one.is_even().to_bool());
1348        assert!(one.is_odd().to_bool());
1349        assert!(two.is_even().to_bool());
1350        assert!(!two.is_odd().to_bool());
1351
1352        // AsRef<[Limb]>, Eq, Ord, CtEq, CtGt, CtLt, CtNe
1353        for (a, b) in pairs {
1354            assert_eq!(a.nlimbs(), a.as_limbs().len());
1355            assert_eq!(a.as_limbs(), a.as_ref());
1356            assert_eq!(a.clone().as_mut_limbs(), a.clone().as_mut());
1357            assert_eq!(&*a.clone().as_mut_limbs(), a.as_limbs());
1358            assert_eq!(
1359                a.ct_eq(b).to_bool(),
1360                a.as_limbs().ct_eq(b.as_limbs()).to_bool()
1361            );
1362            assert_ne!(a.ct_eq(b).to_bool(), a.ct_ne(b).to_bool());
1363            if a == b {
1364                assert!(!a.ct_lt(b).to_bool());
1365                assert!(!a.ct_gt(b).to_bool());
1366            } else {
1367                assert_ne!(a.ct_lt(b).to_bool(), a.ct_gt(b).to_bool());
1368            }
1369            assert_eq!(a.ct_lt(b).to_bool(), a < b);
1370            assert_eq!(a.ct_gt(b).to_bool(), a > b);
1371        }
1372
1373        // CtAssign, CtSelect
1374        for (a, b) in pairs {
1375            let mut c = a.clone();
1376            c.ct_assign(b, Choice::FALSE);
1377            assert_eq!(&c, a);
1378            c.ct_assign(b, Choice::TRUE);
1379            assert_eq!(&c, b);
1380
1381            assert_eq!(&CtSelect::ct_select(a, b, Choice::FALSE), a);
1382            assert_eq!(&CtSelect::ct_select(a, b, Choice::TRUE), b);
1383            let (mut c, mut d) = (a.clone(), b.clone());
1384            CtSelect::ct_swap(&mut c, &mut d, Choice::FALSE);
1385            assert_eq!((&c, &d), (a, b));
1386            CtSelect::ct_swap(&mut c, &mut d, Choice::TRUE);
1387            assert_eq!((&c, &d), (b, a));
1388        }
1389
1390        // BitAnd
1391        for a in inputs {
1392            assert_eq!(a.clone().bitand(zero.clone()), zero);
1393            assert_eq!(a.clone().bitand(&zero), zero);
1394            assert_eq!(&a.clone().bitand(a), a);
1395            assert_eq!(zero.clone().bitand(a), zero);
1396            assert_eq!(a.clone().not().bitand(a), zero);
1397            // BitAndAssign ref
1398            let mut b = a.clone();
1399            b &= a.clone();
1400            assert_eq!(a, &b);
1401            // BitAndAssign owned
1402            let mut b = a.clone();
1403            b &= a;
1404            assert_eq!(a, &b);
1405        }
1406
1407        // BitOr
1408        for a in inputs {
1409            assert_eq!(&a.clone().bitor(zero.clone()), a);
1410            assert_eq!(&a.clone().bitor(&zero), a);
1411            assert_eq!(&a.clone().bitor(a), a);
1412            assert_eq!(&zero.clone().bitor(a), a);
1413            // BitOrAssign ref
1414            let mut b = a.clone();
1415            b |= a;
1416            assert_eq!(a, &b);
1417            // BitOrAssign owned
1418            let mut b = a.clone();
1419            b |= a.clone();
1420            assert_eq!(a, &b);
1421        }
1422
1423        // BitXor
1424        for a in inputs {
1425            assert_eq!(&a.clone().bitxor(zero.clone()), a);
1426            assert_eq!(&a.clone().bitor(&zero), a);
1427            assert_eq!(a.clone().bitxor(a), zero);
1428            assert_eq!(&zero.clone().bitxor(a), a);
1429            // BitXorAssign ref
1430            let mut b = a.clone();
1431            b ^= a;
1432            assert_eq!(T::zero(), b);
1433            // BitXorAssign owned
1434            let mut b = a.clone();
1435            b ^= a.clone();
1436            assert_eq!(T::zero(), b);
1437        }
1438
1439        // Shr/Shl
1440        assert_eq!(zero.clone().shr(1u32), zero);
1441        assert_eq!(one.clone().shr(1u32), zero);
1442        assert_eq!(zero.clone().shl(1u32), zero);
1443        assert_eq!(one.clone().shl(1u32), two);
1444        assert_eq!(two.clone().shr(1u32), one);
1445        assert_ne!(max.clone().shr(1u32), max);
1446        let mut expect = one.clone();
1447        expect.shl_assign(1);
1448        assert_eq!(expect, two);
1449        expect.shr_assign(1);
1450        assert_eq!(expect, one);
1451
1452        // Non-carrying Add
1453        for a in inputs {
1454            assert_eq!(&a.clone().add(zero.clone()), a);
1455            assert_eq!(&a.clone().add(&zero), a);
1456            assert_eq!(&zero.clone().add(a), a);
1457            // AddAssign ref
1458            let mut b = a.clone();
1459            b += &zero;
1460            assert_eq!(a, &b);
1461            // AddAssign owned
1462            let mut b = a.clone();
1463            b += zero.clone();
1464            assert_eq!(a, &b);
1465        }
1466
1467        // Non-borrowing Sub
1468        for a in inputs {
1469            assert_eq!(&a.clone().sub(zero.clone()), a);
1470            assert_eq!(&a.clone().sub(&zero), a);
1471            assert_eq!(a.clone().sub(a), zero);
1472            // SubAssign ref
1473            let mut b = a.clone();
1474            b -= a;
1475            assert_eq!(zero, b);
1476            // SubAssign owned
1477            let mut b = a.clone();
1478            b -= a.clone();
1479            assert_eq!(zero, b);
1480        }
1481
1482        // Non-carrying Mul
1483        for a in inputs {
1484            assert_eq!(a.clone().mul(zero.clone()), zero);
1485            assert_eq!(a.clone().mul(&zero), zero);
1486            assert_eq!(&a.clone().mul(&one), a);
1487            assert_eq!(zero.clone().mul(a), zero);
1488            assert_eq!(&one.clone().mul(a), a);
1489            // MulAssign ref
1490            let mut b = a.clone();
1491            b *= &one;
1492            assert_eq!(a, &b);
1493            // MulAssign owned
1494            let mut b = a.clone();
1495            b *= one.clone();
1496            assert_eq!(a, &b);
1497        }
1498
1499        // DivAssign ref
1500        let mut a = one.clone();
1501        a /= &nz_one;
1502        assert_eq!(a, one);
1503        // DivAssign owned
1504        let mut a = one.clone();
1505        a /= nz_one.clone();
1506        assert_eq!(a, one);
1507
1508        // Rem
1509        assert_eq!(zero.clone().rem(&nz_one), zero);
1510        assert_eq!(zero.clone().rem(nz_one.clone()), zero);
1511        assert_eq!(one.clone().rem(&nz_one), zero);
1512        assert_eq!(one.clone().rem(&nz_two), one);
1513        // RemAssign ref
1514        let mut a = one.clone();
1515        a %= &nz_one;
1516        assert_eq!(a, zero);
1517        // RemAssign owned
1518        let mut a = one.clone();
1519        a %= nz_one.clone();
1520        assert_eq!(a, zero);
1521
1522        // CheckedAdd
1523        assert_eq!(
1524            zero.clone().checked_add(&zero).into_option(),
1525            Some(zero.clone())
1526        );
1527        assert_eq!(
1528            zero.clone().checked_add(&one).into_option(),
1529            Some(one.clone())
1530        );
1531        assert_eq!(
1532            zero.clone().checked_add(&max).into_option(),
1533            Some(max.clone())
1534        );
1535        assert_eq!(max.checked_add(&one).into_option(), None);
1536        assert_eq!(max.checked_add(&max).into_option(), None);
1537
1538        // CheckedSub
1539        assert_eq!(
1540            zero.clone().checked_sub(&zero).into_option(),
1541            Some(zero.clone())
1542        );
1543        assert_eq!(min.checked_sub(&zero).into_option(), Some(min.clone()));
1544        assert_eq!(min.checked_sub(&one).into_option(), None);
1545        assert_eq!(min.checked_sub(&max).into_option(), None);
1546        assert_eq!(max.checked_sub(&zero).into_option(), Some(max.clone()));
1547        assert_eq!(max.checked_sub(&max).into_option(), Some(zero.clone()));
1548
1549        // CheckedMul
1550        assert_eq!(
1551            zero.clone().checked_mul(&zero).into_option(),
1552            Some(zero.clone())
1553        );
1554        assert_eq!(
1555            zero.clone().checked_mul(&one).into_option(),
1556            Some(zero.clone())
1557        );
1558        assert_eq!(
1559            one.clone().checked_mul(&max).into_option(),
1560            Some(max.clone())
1561        );
1562        assert_eq!(max.checked_mul(&max).into_option(), None);
1563
1564        // CheckedDiv
1565        assert_eq!(zero.clone().checked_div(&zero).into_option(), None);
1566        assert_eq!(one.clone().checked_div(&zero).into_option(), None);
1567        assert_eq!(
1568            one.clone().checked_div(&one).into_option(),
1569            Some(one.clone())
1570        );
1571        assert_eq!(max.checked_div(&max).into_option(), Some(one.clone()));
1572
1573        // CheckedSquareRoot
1574        assert_eq!(zero.checked_sqrt().into_option(), Some(zero.clone()));
1575        assert_eq!(zero.checked_sqrt_vartime(), Some(zero.clone()));
1576        assert_eq!(one.checked_sqrt().into_option(), Some(one.clone()));
1577        assert_eq!(one.checked_sqrt_vartime(), Some(one.clone()));
1578        assert_eq!(two.checked_sqrt().into_option(), None);
1579        assert_eq!(two.checked_sqrt_vartime(), None);
1580
1581        // WrappingAdd
1582        assert_eq!(zero.clone().wrapping_add(&zero), zero);
1583        assert_eq!(zero.clone().wrapping_add(&one), one);
1584        assert_eq!(one.clone().wrapping_add(&zero), one);
1585        assert_eq!(one.clone().wrapping_add(&one), two);
1586        assert_eq!(one.clone().wrapping_add(&max), min);
1587        assert_eq!(max.wrapping_add(&one), min);
1588
1589        // WrappingSub
1590        assert_eq!(zero.clone().wrapping_sub(&zero), zero);
1591        assert_eq!(one.clone().wrapping_sub(&zero), one);
1592        assert_eq!(two.wrapping_sub(&one), one);
1593        assert_eq!(min.wrapping_sub(&one), max);
1594        assert_eq!(min.wrapping_sub(&min), zero);
1595
1596        // WrappingMul
1597        assert_eq!(zero.clone().wrapping_mul(&zero), zero);
1598        assert_eq!(zero.clone().wrapping_mul(&one), zero);
1599        assert_eq!(one.clone().wrapping_mul(&zero), zero);
1600        assert_eq!(one.clone().wrapping_mul(&one), one);
1601        assert_eq!(one.clone().wrapping_mul(&max), max);
1602        assert_eq!(max.wrapping_mul(&zero), zero);
1603        assert_eq!(max.wrapping_mul(&one), max);
1604        assert_eq!(max.wrapping_mul(&two), max.clone().shl(1u32));
1605
1606        // WrappingNeg
1607        assert_eq!(zero.clone().wrapping_neg(), zero);
1608        for a in inputs {
1609            assert_eq!(a.wrapping_add(&a.wrapping_neg()), zero);
1610            assert_eq!(zero.wrapping_sub(a), a.wrapping_neg());
1611        }
1612
1613        // WrappingShr/WrappingShl
1614        assert_eq!(zero.clone().wrapping_shr(1u32), zero);
1615        assert_eq!(one.clone().wrapping_shr(1u32), zero);
1616        assert_eq!(zero.clone().wrapping_shl(1u32), zero);
1617        assert_eq!(one.clone().wrapping_shl(1u32), two);
1618        assert_eq!(two.clone().wrapping_shr(1u32), one);
1619        assert_ne!(max.clone().wrapping_shr(1u32), max);
1620    }
1621
1622    /// Apply a suite of tests against a type implementing Unsigned.
1623    pub fn test_unsigned<T: Unsigned>(min: T, max: T) {
1624        let zero = T::zero_like(&min);
1625        let one = T::one_like(&min);
1626        let two = one.clone() + &one;
1627        let nz_one = NonZero::new(one.clone()).expect("must be non-zero");
1628        let nz_two = NonZero::new(two.clone()).expect("must be non-zero");
1629        let nz_limb_one = NonZero::new(Limb::ONE).expect("must be non-zero");
1630        let nz_limb_two = NonZero::new(Limb::from(2u8)).expect("must be non-zero");
1631        let inputs = &[zero.clone(), one.clone(), max.clone()];
1632
1633        // Test Integer trait
1634        test_integer(min.clone(), max.clone());
1635
1636        // Trait methods
1637        for a in inputs {
1638            assert_eq!(a.as_uint_ref(), a.as_ref());
1639            assert_eq!(a.clone().as_mut_uint_ref(), a.clone().as_mut());
1640            assert_eq!(T::from_limb_like(Limb::ZERO, &one), zero);
1641            assert_eq!(T::from_limb_like(Limb::ONE, &one), one);
1642        }
1643
1644        // Zero trait
1645        assert!(zero.is_zero().to_bool());
1646        assert!(!one.is_zero().to_bool());
1647        let mut a = one.clone();
1648        a.set_zero();
1649        assert_eq!(a, zero);
1650
1651        // One trait
1652        assert!(!zero.is_one().to_bool());
1653        assert!(one.is_one().to_bool());
1654        let mut a = zero.clone();
1655        a.set_one();
1656        assert_eq!(a, one);
1657
1658        // From implementations
1659        assert_eq!(T::from(0u8), T::zero());
1660        assert_eq!(T::from(1u8), T::one());
1661        assert_eq!(T::from(1u16), T::one());
1662        assert_eq!(T::from(1u32), T::one());
1663        assert_eq!(T::from(1u64), T::one());
1664        assert_eq!(T::from(Limb::ONE), T::one());
1665
1666        // ToUnsigned
1667        assert_eq!(one.to_unsigned(), one);
1668        assert_eq!(one.to_unsigned_zero(), zero);
1669
1670        // FloorSquareRoot
1671        assert_eq!(zero.floor_sqrt(), zero);
1672        assert_eq!(zero.floor_sqrt_vartime(), zero);
1673        assert_eq!(one.floor_sqrt(), one);
1674        assert_eq!(one.floor_sqrt_vartime(), one);
1675        assert_eq!(two.floor_sqrt(), one);
1676        assert_eq!(two.floor_sqrt_vartime(), one);
1677
1678        // Gcd
1679        assert_eq!(zero.gcd(&zero), zero);
1680        assert_eq!(zero.gcd_vartime(&zero), zero);
1681        assert_eq!(one.gcd(&one), one);
1682        assert_eq!(one.gcd_vartime(&one), one);
1683        assert_eq!(two.gcd(&one), one);
1684        assert_eq!(two.gcd_vartime(&one), one);
1685
1686        // Div by ref
1687        assert_eq!(zero.clone().div(&nz_one), zero);
1688        assert_eq!(zero.clone().div(&nz_two), zero);
1689        assert_eq!(one.clone().div(&nz_one), one);
1690        assert_eq!(one.clone().div(&nz_two), zero);
1691        // Div by owned
1692        assert_eq!(zero.clone().div(nz_one.clone()), zero);
1693        assert_eq!(zero.clone().div(nz_two.clone()), zero);
1694        assert_eq!(one.clone().div(nz_one.clone()), one);
1695        assert_eq!(one.clone().div(nz_two.clone()), zero);
1696
1697        // DivRemLimb
1698        assert_eq!(zero.div_rem_limb(nz_limb_one), (zero.clone(), Limb::ZERO));
1699        assert_eq!(zero.div_rem_limb(nz_limb_two), (zero.clone(), Limb::ZERO));
1700        assert_eq!(one.div_rem_limb(nz_limb_one), (one.clone(), Limb::ZERO));
1701        assert_eq!(one.div_rem_limb(nz_limb_two), (zero.clone(), Limb::ONE));
1702        assert_eq!(
1703            zero.div_rem_limb_with_reciprocal(&Reciprocal::new(nz_limb_one)),
1704            (zero.clone(), Limb::ZERO)
1705        );
1706        assert_eq!(
1707            one.div_rem_limb_with_reciprocal(&Reciprocal::new(nz_limb_one)),
1708            (one.clone(), Limb::ZERO)
1709        );
1710        assert_eq!(
1711            one.div_rem_limb_with_reciprocal(&Reciprocal::new(nz_limb_two)),
1712            (zero.clone(), Limb::ONE)
1713        );
1714
1715        // RemLimb
1716        assert_eq!(zero.rem_limb(nz_limb_one), Limb::ZERO);
1717        assert_eq!(zero.rem_limb(nz_limb_two), Limb::ZERO);
1718        assert_eq!(one.rem_limb(nz_limb_one), Limb::ZERO);
1719        assert_eq!(one.rem_limb(nz_limb_two), Limb::ONE);
1720        assert_eq!(
1721            zero.rem_limb_with_reciprocal(&Reciprocal::new(nz_limb_one)),
1722            Limb::ZERO
1723        );
1724        assert_eq!(
1725            one.rem_limb_with_reciprocal(&Reciprocal::new(nz_limb_one)),
1726            Limb::ZERO
1727        );
1728        assert_eq!(
1729            one.rem_limb_with_reciprocal(&Reciprocal::new(nz_limb_two)),
1730            Limb::ONE
1731        );
1732
1733        // BitOps
1734        assert_eq!(zero.bit_width(), 0);
1735        assert_eq!(one.bit_width(), 1);
1736        assert_eq!(one.bit_width_vartime(), 1);
1737        assert_eq!(one.bits_precision() as usize, one.bytes_precision() * 8);
1738        assert_eq!(one.bits_precision(), 1 << one.log2_bits());
1739        // Leading/trailing zeros and ones
1740        assert_eq!(zero.leading_zeros(), zero.bits_precision());
1741        assert_eq!(zero.leading_zeros_vartime(), zero.bits_precision());
1742        assert_eq!(zero.trailing_zeros(), zero.bits_precision());
1743        assert_eq!(zero.trailing_zeros_vartime(), zero.bits_precision());
1744        assert_eq!(zero.trailing_ones(), 0);
1745        assert_eq!(zero.trailing_ones_vartime(), 0);
1746        assert_eq!(one.leading_zeros(), one.bits_precision() - 1);
1747        assert_eq!(one.leading_zeros_vartime(), one.bits_precision() - 1);
1748        assert_eq!(one.trailing_zeros(), 0);
1749        assert_eq!(one.trailing_zeros_vartime(), 0);
1750        assert_eq!(one.trailing_ones(), 1);
1751        assert_eq!(one.trailing_ones_vartime(), 1);
1752        // Bit access
1753        assert!(!zero.bit(0).to_bool());
1754        assert!(!zero.bit_vartime(0));
1755        assert!(one.bit(0).to_bool());
1756        assert!(one.bit_vartime(0));
1757        assert!(!one.bit(1).to_bool());
1758        assert!(!one.bit_vartime(1));
1759        // Bit assignment
1760        let mut a = zero.clone();
1761        a.set_bit(0, Choice::TRUE);
1762        assert_eq!(a, one);
1763        let mut a = zero.clone();
1764        a.set_bit_vartime(0, true);
1765        assert_eq!(a, one);
1766        let mut a = one.clone();
1767        a.set_bit(0, Choice::FALSE);
1768        assert_eq!(a, zero);
1769        let mut a = one.clone();
1770        a.set_bit_vartime(0, false);
1771        assert_eq!(a, zero);
1772
1773        // AddMod
1774        assert_eq!(zero.add_mod(&zero, &nz_two), zero);
1775        assert_eq!(zero.add_mod(&one, &nz_two), one);
1776        assert_eq!(one.add_mod(&zero, &nz_two), one);
1777        assert_eq!(one.add_mod(&one, &nz_two), zero);
1778
1779        // SubMod
1780        assert_eq!(zero.sub_mod(&zero, &nz_two), zero);
1781        assert_eq!(zero.sub_mod(&one, &nz_two), one);
1782        assert_eq!(one.sub_mod(&zero, &nz_two), one);
1783        assert_eq!(one.sub_mod(&one, &nz_two), zero);
1784
1785        // MulMod
1786        assert_eq!(zero.mul_mod(&zero, &nz_two), zero);
1787        assert_eq!(zero.mul_mod(&one, &nz_two), zero);
1788        assert_eq!(one.mul_mod(&zero, &nz_two), zero);
1789        assert_eq!(one.mul_mod(&one, &nz_two), one);
1790
1791        // SquareMod
1792        assert_eq!(zero.square_mod(&nz_two), zero);
1793        assert_eq!(one.square_mod(&nz_two), one);
1794
1795        // NegMod
1796        assert_eq!(zero.neg_mod(&nz_two), zero);
1797        assert_eq!(one.neg_mod(&nz_two), one);
1798    }
1799
1800    pub fn test_signed<T: Signed>(min: T, max: T) {
1801        let zero = T::zero_like(&min);
1802        let one = T::one_like(&min);
1803        let two = one.clone() + &one;
1804        let zero_unsigned = T::Unsigned::zero();
1805        let one_unsigned = T::Unsigned::one();
1806        let minus_one = T::from(-1i8);
1807        let nz_one = NonZero::new(one.clone()).expect("must be non-zero");
1808        let nz_minus_one = NonZero::new(minus_one.clone()).expect("must be non-zero");
1809        let nz_two = NonZero::new(two.clone()).expect("must be non-zero");
1810
1811        // Test Integer trait
1812        test_integer(min.clone(), max.clone());
1813
1814        // Trait sign methods
1815        assert!(!zero.is_positive().to_bool());
1816        assert!(!zero.is_negative().to_bool());
1817        assert!(one.is_positive().to_bool());
1818        assert!(!one.is_negative().to_bool());
1819        assert!(!minus_one.is_positive().to_bool());
1820        assert!(minus_one.is_negative().to_bool());
1821        // Trait abs methods
1822        assert_eq!(zero.abs(), zero_unsigned);
1823        assert_eq!(one.abs(), one_unsigned);
1824        assert_eq!(minus_one.abs(), one_unsigned);
1825        let (check, check_sign) = zero.abs_sign();
1826        assert_eq!(
1827            (check, check_sign.to_bool()),
1828            (zero_unsigned.clone(), false)
1829        );
1830        let (check, check_sign) = one.abs_sign();
1831        assert_eq!((check, check_sign.to_bool()), (one_unsigned.clone(), false));
1832        let (check, check_sign) = minus_one.abs_sign();
1833        assert_eq!((check, check_sign.to_bool()), (one_unsigned.clone(), true));
1834
1835        // From implementations
1836        assert_eq!(T::from(0i8), T::zero());
1837        assert_eq!(T::from(1i8), T::one());
1838        assert_eq!(T::from(1i16), T::one());
1839        assert_eq!(T::from(1i32), T::one());
1840        assert_eq!(T::from(1i64), T::one());
1841        assert_eq!(T::from(-1i64), T::zero() - T::one());
1842
1843        // Gcd
1844        assert_eq!(zero.gcd(&zero), T::Unsigned::zero());
1845        assert_eq!(zero.gcd_vartime(&zero), T::Unsigned::zero());
1846        assert_eq!(one.gcd(&one), T::Unsigned::one());
1847        assert_eq!(one.gcd_vartime(&one), T::Unsigned::one());
1848        assert_eq!(two.gcd(&one), T::Unsigned::one());
1849        assert_eq!(two.gcd_vartime(&one), T::Unsigned::one());
1850        assert_eq!(minus_one.gcd(&one), T::Unsigned::one());
1851        assert_eq!(minus_one.gcd_vartime(&one), T::Unsigned::one());
1852
1853        // Div by ref
1854        assert_eq!(zero.clone().div(&nz_one).into_option(), Some(zero.clone()));
1855        assert_eq!(
1856            zero.clone().div(&nz_minus_one).into_option(),
1857            Some(zero.clone())
1858        );
1859        assert_eq!(zero.clone().div(&nz_two).into_option(), Some(zero.clone()));
1860        assert_eq!(one.clone().div(&nz_one).into_option(), Some(one.clone()));
1861        assert_eq!(
1862            one.clone().div(&nz_minus_one).into_option(),
1863            Some(minus_one.clone())
1864        );
1865        assert_eq!(one.clone().div(&nz_two).into_option(), Some(zero.clone()));
1866        // Div by owned
1867        assert_eq!(
1868            zero.clone().div(nz_one.clone()).into_option(),
1869            Some(zero.clone())
1870        );
1871        assert_eq!(
1872            zero.clone().div(nz_minus_one.clone()).into_option(),
1873            Some(zero.clone())
1874        );
1875        assert_eq!(
1876            zero.clone().div(nz_two.clone()).into_option(),
1877            Some(zero.clone())
1878        );
1879        assert_eq!(
1880            one.clone().div(nz_one.clone()).into_option(),
1881            Some(one.clone())
1882        );
1883        assert_eq!(
1884            one.clone().div(nz_minus_one.clone()).into_option(),
1885            Some(minus_one.clone())
1886        );
1887        assert_eq!(
1888            one.clone().div(nz_two.clone()).into_option(),
1889            Some(zero.clone())
1890        );
1891    }
1892
1893    pub fn test_unsigned_monty_form<T: UnsignedWithMontyForm>() {
1894        let modulus = Odd::new(T::from(17863u32)).unwrap();
1895        let params = T::MontyForm::new_params_vartime(modulus);
1896
1897        // test AsRef, From for Params
1898        assert_eq!(
1899            <T::MontyForm as MontyForm>::Params::from(params.as_ref().clone()),
1900            params,
1901        );
1902        // test Clone for Params
1903        assert_eq!(params, params.clone());
1904
1905        // test zero
1906        let zero = T::MontyForm::zero(&params);
1907        assert!(zero.is_zero().to_bool());
1908        assert!(!zero.is_one().to_bool());
1909
1910        // test one
1911        let one = T::MontyForm::one(&params);
1912        assert!(!one.is_zero().to_bool());
1913        assert!(one.is_one().to_bool());
1914
1915        // test as_montgomery()
1916        assert_eq!(zero.as_montgomery(), &T::zero());
1917        assert_eq!(one.as_montgomery(), params.as_ref().one());
1918
1919        // test copy_montgomery_from()
1920        let mut z2 = one.clone();
1921        z2.copy_montgomery_from(&zero);
1922        assert_eq!(z2, zero);
1923
1924        // test from_montgomery()
1925        let one2 =
1926            <T::MontyForm as MontyForm>::from_montgomery(params.as_ref().one().clone(), &params);
1927        assert_eq!(one2, one);
1928
1929        // test into_montgomery()
1930        assert_eq!(&one2.into_montgomery(), params.as_ref().one());
1931
1932        // test double(), div_by_2()
1933        assert_eq!(zero.double(), zero);
1934        assert_ne!(one.double(), one);
1935        assert_eq!(one.double().div_by_2(), one);
1936        let mut half = one.clone();
1937        half.div_by_2_assign();
1938        assert_ne!(half, one);
1939        assert_eq!(half.double(), one);
1940
1941        // test lincomb_vartime()
1942        assert_eq!(
1943            <T::MontyForm as MontyForm>::lincomb_vartime(&[(&zero, &zero)]),
1944            zero
1945        );
1946        assert_eq!(
1947            <T::MontyForm as MontyForm>::lincomb_vartime(&[(&one, &one)]),
1948            one
1949        );
1950        assert_eq!(
1951            <T::MontyForm as MontyForm>::lincomb_vartime(&[(&one, &one), (&one, &one)]),
1952            one.double()
1953        );
1954
1955        // test CtSelect
1956        assert_eq!(zero.ct_select(&one, Choice::FALSE), zero);
1957        assert_eq!(zero.ct_select(&one, Choice::TRUE), one);
1958
1959        // test Invert
1960        assert!(zero.invert().is_none().to_bool());
1961        assert!(zero.invert_vartime().is_none().to_bool());
1962        assert!(one.invert().expect("inversion error").is_one().to_bool());
1963        assert!(
1964            one.invert_vartime()
1965                .expect("inversion error")
1966                .is_one()
1967                .to_bool()
1968        );
1969
1970        // test Add, AddAssign
1971        assert_eq!(one.clone() + one.clone(), one.double());
1972        assert_eq!(one.clone() + &one, one.double());
1973        let mut two = one.clone();
1974        two += one.clone();
1975        assert_eq!(two, one.double());
1976        let mut two = one.clone();
1977        two += &one;
1978        assert_eq!(two, one.double());
1979
1980        // test Sub, SubAssign
1981        assert_eq!(one.clone() - one.clone(), zero);
1982        assert_eq!(one.clone() - &one, zero);
1983        let mut check = one.double();
1984        check -= one.clone();
1985        assert_eq!(check, one);
1986        let mut check = one.double();
1987        check -= &one;
1988        assert_eq!(check, one);
1989
1990        // test Mul, MulAssign
1991        assert_eq!(zero.clone() * &zero, zero);
1992        assert_eq!(zero.clone() * &one, zero);
1993        assert_eq!(one.clone() * one.clone(), one);
1994        let mut check = one.clone();
1995        check *= one.clone();
1996        assert_eq!(check, one);
1997        let mut check = one.clone();
1998        check *= &zero;
1999        assert_eq!(check, zero);
2000
2001        // test Neg
2002        assert_eq!(-zero.clone(), zero);
2003        assert_ne!(-one.clone(), one);
2004        assert_eq!(-(-one.clone()), one);
2005
2006        // test Retrieve
2007        assert_eq!(zero.retrieve(), T::zero());
2008        assert_eq!(one.retrieve(), T::one());
2009
2010        // test Square, SquareAssign
2011        assert_eq!(zero.square(), zero);
2012        assert_eq!(one.square(), one);
2013        let mut check = one.double();
2014        check.square_assign();
2015        assert_eq!(check, one.double().double());
2016    }
2017}