Skip to content

Commit

Permalink
Add Random support; fix benchmarks
Browse files Browse the repository at this point in the history
  • Loading branch information
tarcieri committed Dec 20, 2023
1 parent 017f991 commit c9bad93
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
14 changes: 7 additions & 7 deletions benches/monty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use criterion::{
};
use crypto_bigint::{
modular::{MontyForm, MontyParams},
Invert, Inverter, PrecomputeInverter, Random, U256,
Invert, Inverter, Odd, PrecomputeInverter, Random, U256,
};
use rand_core::OsRng;

Expand All @@ -14,22 +14,22 @@ use crypto_bigint::MultiExponentiate;
fn bench_montgomery_conversion<M: Measurement>(group: &mut BenchmarkGroup<'_, M>) {
group.bench_function("MontyParams creation", |b| {
b.iter_batched(
|| U256::random(&mut OsRng) | U256::ONE,
|modulus| black_box(MontyParams::new(&modulus)),
|| Odd::<U256>::random(&mut OsRng),
|modulus| black_box(MontyParams::new(modulus)),
BatchSize::SmallInput,
)
});

let params = MontyParams::new(&(U256::random(&mut OsRng) | U256::ONE)).unwrap();
let params = MontyParams::new(Odd::<U256>::random(&mut OsRng));
group.bench_function("MontyForm creation", |b| {
b.iter_batched(
|| U256::random(&mut OsRng),
|| Odd::<U256>::random(&mut OsRng),
|x| black_box(MontyForm::new(&x, params)),
BatchSize::SmallInput,
)
});

let params = MontyParams::new(&(U256::random(&mut OsRng) | U256::ONE)).unwrap();
let params = MontyParams::new(Odd::<U256>::random(&mut OsRng));
group.bench_function("MontyForm retrieve", |b| {
b.iter_batched(
|| MontyForm::new(&U256::random(&mut OsRng), params),
Expand All @@ -40,7 +40,7 @@ fn bench_montgomery_conversion<M: Measurement>(group: &mut BenchmarkGroup<'_, M>
}

fn bench_montgomery_ops<M: Measurement>(group: &mut BenchmarkGroup<'_, M>) {
let params = MontyParams::new(&(U256::random(&mut OsRng) | U256::ONE)).unwrap();
let params = MontyParams::new(Odd::<U256>::random(&mut OsRng));

group.bench_function("invert, U256", |b| {
b.iter_batched(
Expand Down
11 changes: 11 additions & 0 deletions src/odd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ use crate::{Integer, NonZero, Uint};
use core::ops::Deref;
use subtle::{Choice, ConditionallySelectable, CtOption};

#[cfg(feature = "rand_core")]
use {crate::Random, rand_core::CryptoRngCore};

/// Wrapper type for odd integers.
///
/// These are frequently used in cryptography, e.g. as a modulus.
Expand Down Expand Up @@ -88,3 +91,11 @@ impl<T> Deref for Odd<T> {
&self.0
}
}

#[cfg(feature = "rand_core")]
impl<const LIMBS: usize> Random for Odd<Uint<LIMBS>> {
/// Generate a random `NonZero<Uint<T>>`.
fn random(rng: &mut impl CryptoRngCore) -> Self {
Odd(Uint::random(rng) | Uint::ONE)
}
}

0 comments on commit c9bad93

Please sign in to comment.