From 8d68e460bf80bf401e7d189b87918804d4168fee Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Fri, 8 Dec 2023 07:24:55 -0700 Subject: [PATCH] Add `BoxedResidue::new_with_arc` When the `std` feature is available, allows passing `BoxedResidueParams` as an `Arc` which avoids unnecessary cloning. --- src/modular/boxed_residue.rs | 39 ++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/src/modular/boxed_residue.rs b/src/modular/boxed_residue.rs index 10f7f5d1b..58fc2db0c 100644 --- a/src/modular/boxed_residue.rs +++ b/src/modular/boxed_residue.rs @@ -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) -> 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() @@ -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};