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 AUTHOR DISCLAIMS ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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.
1415use super::Modulus;
16use crate::{
17 error,
18 limb::{self, Limb},
19};
20use alloc::{boxed::Box, vec};
21use core::{
22 marker::PhantomData,
23 ops::{Deref, DerefMut},
24};
2526/// All `BoxedLimbs<M>` are stored in the same number of limbs.
27pub(super) struct BoxedLimbs<M> {
28 limbs: Box<[Limb]>,
2930/// The modulus *m* that determines the size of `limbx`.
31m: PhantomData<M>,
32}
3334impl<M> Deref for BoxedLimbs<M> {
35type Target = [Limb];
36#[inline]
37fn deref(&self) -> &Self::Target {
38&self.limbs
39 }
40}
4142impl<M> DerefMut for BoxedLimbs<M> {
43#[inline]
44fn deref_mut(&mut self) -> &mut Self::Target {
45&mut self.limbs
46 }
47}
4849// TODO: `derive(Clone)` after https://github.com/rust-lang/rust/issues/26925
50// is resolved or restrict `M: Clone`.
51impl<M> Clone for BoxedLimbs<M> {
52fn clone(&self) -> Self {
53Self {
54 limbs: self.limbs.clone(),
55 m: self.m,
56 }
57 }
58}
5960impl<M> BoxedLimbs<M> {
61pub(super) fn from_be_bytes_padded_less_than(
62 input: untrusted::Input,
63 m: &Modulus<M>,
64 ) -> Result<Self, error::Unspecified> {
65let mut r = 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, m.limbs())?;
68Ok(r)
69 }
7071pub(super) fn zero(len: usize) -> Self {
72Self {
73 limbs: vec![0; len].into_boxed_slice(),
74 m: PhantomData,
75 }
76 }
7778pub(super) fn into_limbs(self) -> Box<[Limb]> {
79self.limbs
80 }
81}