Skip to content

Commit

Permalink
Add BoxedResidue::new_with_arc (#407)
Browse files Browse the repository at this point in the history
When the `std` feature is available, allows passing `BoxedResidueParams`
as an `Arc` which avoids unnecessary cloning.
  • Loading branch information
tarcieri authored Dec 8, 2023
1 parent 68e958c commit 1a0399d
Showing 1 changed file with 28 additions and 11 deletions.
39 changes: 28 additions & 11 deletions src/modular/boxed_residue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,24 +153,26 @@ impl BoxedResidue {
/// Instantiates a new [`BoxedResidue`] that represents an integer modulo the provided params.
pub fn new(mut integer: BoxedUint, residue_params: BoxedResidueParams) -> Self {
debug_assert_eq!(integer.bits_precision(), residue_params.bits_precision());
convert_to_montgomery(&mut integer, &residue_params);

let mut product = integer.mul(&residue_params.r2);
montgomery_reduction_boxed_mut(
&mut product,
&residue_params.modulus,
residue_params.mod_neg_inv,
&mut integer,
);

#[cfg(feature = "zeroize")]
product.zeroize();

#[allow(clippy::useless_conversion)]
Self {
montgomery_form: integer,
residue_params: residue_params.into(),
}
}

/// Instantiates a new [`BoxedResidue`] that represents an integer modulo the provided params.
#[cfg(feature = "std")]
pub fn new_with_arc(mut integer: BoxedUint, residue_params: Arc<BoxedResidueParams>) -> Self {
debug_assert_eq!(integer.bits_precision(), residue_params.bits_precision());
convert_to_montgomery(&mut integer, &residue_params);
Self {
montgomery_form: integer,
residue_params,
}
}

/// Bits of precision in the modulus.
pub fn bits_precision(&self) -> u32 {
self.residue_params.bits_precision()
Expand Down Expand Up @@ -240,6 +242,21 @@ impl Retrieve for BoxedResidue {
}
}

/// Convert the given integer into the Montgomery domain.
#[inline]
fn convert_to_montgomery(integer: &mut BoxedUint, residue_params: &BoxedResidueParams) {
let mut product = integer.mul(&residue_params.r2);
montgomery_reduction_boxed_mut(
&mut product,
&residue_params.modulus,
residue_params.mod_neg_inv,
integer,
);

#[cfg(feature = "zeroize")]
product.zeroize();
}

#[cfg(test)]
mod tests {
use super::{BoxedResidueParams, BoxedUint};
Expand Down

0 comments on commit 1a0399d

Please sign in to comment.