| 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 super::Modulus; |
| 16 | use crate::{ |
| 17 | error, |
| 18 | limb::{self, Limb}, |
| 19 | }; |
| 20 | use alloc::{boxed::Box, vec}; |
| 21 | use core::{ |
| 22 | marker::PhantomData, |
| 23 | ops::{Deref, DerefMut}, |
| 24 | }; |
| 25 | |
| 26 | /// All `BoxedLimbs<M>` are stored in the same number of limbs. |
| 27 | pub(super) struct BoxedLimbs<M> { |
| 28 | limbs: Box<[Limb]>, |
| 29 | |
| 30 | /// The modulus *m* that determines the size of `limbx`. |
| 31 | m: PhantomData<M>, |
| 32 | } |
| 33 | |
| 34 | impl<M> Deref for BoxedLimbs<M> { |
| 35 | type Target = [Limb]; |
| 36 | #[inline ] |
| 37 | fn deref(&self) -> &Self::Target { |
| 38 | &self.limbs |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | impl<M> DerefMut for BoxedLimbs<M> { |
| 43 | #[inline ] |
| 44 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 45 | &mut self.limbs |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | // TODO: `derive(Clone)` after https://github.com/rust-lang/rust/issues/26925 |
| 50 | // is resolved or restrict `M: Clone`. |
| 51 | impl<M> Clone for BoxedLimbs<M> { |
| 52 | fn clone(&self) -> Self { |
| 53 | Self { |
| 54 | limbs: self.limbs.clone(), |
| 55 | m: self.m, |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | impl<M> BoxedLimbs<M> { |
| 61 | pub(super) fn from_be_bytes_padded_less_than( |
| 62 | input: untrusted::Input, |
| 63 | m: &Modulus<M>, |
| 64 | ) -> Result<Self, error::Unspecified> { |
| 65 | let mut r: BoxedLimbs = Self::zero(m.limbs().len()); |
| 66 | limb::parse_big_endian_and_pad_consttime(input, &mut r)?; |
| 67 | limb::verify_limbs_less_than_limbs_leak_bit(&r, b:m.limbs())?; |
| 68 | Ok(r) |
| 69 | } |
| 70 | |
| 71 | pub(super) fn zero(len: usize) -> Self { |
| 72 | Self { |
| 73 | limbs: vec![0; len].into_boxed_slice(), |
| 74 | m: PhantomData, |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | pub(super) fn into_limbs(self) -> Box<[Limb]> { |
| 79 | self.limbs |
| 80 | } |
| 81 | } |
| 82 | |