crypto_bigint/limb/
rand.rs
1use super::Limb;
4use crate::{Encoding, NonZero, Random, RandomMod};
5use rand_core::{CryptoRng, RngCore};
6use subtle::ConstantTimeLess;
7
8#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
9impl Random for Limb {
10 #[cfg(target_pointer_width = "32")]
11 fn random(mut rng: impl CryptoRng + RngCore) -> Self {
12 Self(rng.next_u32())
13 }
14
15 #[cfg(target_pointer_width = "64")]
16 fn random(mut rng: impl CryptoRng + RngCore) -> Self {
17 Self(rng.next_u64())
18 }
19}
20
21#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
22impl RandomMod for Limb {
23 fn random_mod(mut rng: impl CryptoRng + RngCore, modulus: &NonZero<Self>) -> Self {
24 let mut bytes = <Self as Encoding>::Repr::default();
25
26 let mut n_bytes = modulus.bits() / 8;
29
30 if n_bytes < Self::BYTE_SIZE {
33 n_bytes += 1;
34 }
35
36 loop {
37 rng.fill_bytes(&mut bytes[..n_bytes]);
38 let n = Limb::from_le_bytes(bytes);
39
40 if n.ct_lt(modulus).into() {
41 return n;
42 }
43 }
44 }
45}