1 // Copyright 2015-2023 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15 use crate::{
16 bits, error,
17 limb::{self, Limb, LimbMask, LIMB_BYTES},
18 };
19 use alloc::{boxed::Box, vec, vec::Vec};
20
21 /// Nonnegative integers.
22 pub(crate) struct Nonnegative {
23 limbs: Vec<Limb>,
24 }
25
26 impl Nonnegative {
from_be_bytes_with_bit_length( input: untrusted::Input, ) -> Result<(Self, bits::BitLength), error::Unspecified>27 pub fn from_be_bytes_with_bit_length(
28 input: untrusted::Input,
29 ) -> Result<(Self, bits::BitLength), error::Unspecified> {
30 let mut limbs = vec![0; (input.len() + LIMB_BYTES - 1) / LIMB_BYTES];
31 // Rejects empty inputs.
32 limb::parse_big_endian_and_pad_consttime(input, &mut limbs)?;
33 while limbs.last() == Some(&0) {
34 let _ = limbs.pop();
35 }
36 let r_bits = limb::limbs_minimal_bits(&limbs);
37 Ok((Self { limbs }, r_bits))
38 }
39
40 #[inline]
is_odd(&self) -> bool41 pub fn is_odd(&self) -> bool {
42 limb::limbs_are_even_constant_time(&self.limbs) != LimbMask::True
43 }
44
verify_less_than(&self, other: &Self) -> Result<(), error::Unspecified>45 pub fn verify_less_than(&self, other: &Self) -> Result<(), error::Unspecified> {
46 if !greater_than(other, self) {
47 return Err(error::Unspecified);
48 }
49 Ok(())
50 }
51
52 #[inline]
limbs(&self) -> &[Limb]53 pub fn limbs(&self) -> &[Limb] {
54 &self.limbs
55 }
56
57 #[inline]
into_limbs(self) -> Box<[Limb]>58 pub fn into_limbs(self) -> Box<[Limb]> {
59 self.limbs.into_boxed_slice()
60 }
61 }
62
63 // Returns a > b.
greater_than(a: &Nonnegative, b: &Nonnegative) -> bool64 fn greater_than(a: &Nonnegative, b: &Nonnegative) -> bool {
65 if a.limbs.len() == b.limbs.len() {
66 limb::limbs_less_than_limbs_vartime(&b.limbs, &a.limbs)
67 } else {
68 a.limbs.len() > b.limbs.len()
69 }
70 }
71