Skip to content
This repository was archived by the owner on Jun 7, 2026. It is now read-only.

Commit 94b7e74

Browse files
authored
Merge pull request zkcrypto#59 from baloo/baloo/try_from_rng
Provide a `Group::try_from_rng`
2 parents 430e26a + 4456de8 commit 94b7e74

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ and this library adheres to Rust's notion of
1212
- `group::Group::random(rng: impl RngCore) -> Self` has been changed to
1313
`Group::random<R: RngCore + ?Sized>(rng: &mut R) -> Self`, to enable passing a
1414
trait object as the RNG.
15+
- `group::Group::try_from_rng` is a new trait method that must be implemented by
16+
downstreams. `Group::random` now has a default implementation that calls it.
1517

1618
## [0.13.0] - 2022-12-06
1719
### Changed

src/lib.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,12 @@ extern crate alloc;
99
// Re-export ff to make version-matching easier.
1010
pub use ff;
1111

12+
use core::convert::Infallible;
1213
use core::fmt;
1314
use core::iter::Sum;
1415
use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
1516
use ff::PrimeField;
16-
use rand_core::RngCore;
17+
use rand_core::{RngCore, TryRngCore};
1718
use subtle::{Choice, CtOption};
1819

1920
pub mod cofactor;
@@ -76,7 +77,22 @@ pub trait Group:
7677
/// this group.
7778
///
7879
/// This function is non-deterministic, and samples from the user-provided RNG.
79-
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self;
80+
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
81+
Self::try_from_rng(rng)
82+
.map_err(|e: Infallible| e)
83+
.expect("Infallible failed")
84+
85+
// NOTE: once MSRV gets to 1.82 remove the map_err/expect and use
86+
// let Ok(out) = Self::try_from_rng(rng);
87+
// out
88+
// See: https://blog.rust-lang.org/2024/10/17/Rust-1.82.0.html#omitting-empty-types-in-pattern-matching
89+
}
90+
91+
/// Returns an element chosen uniformly at random from the non-identity elements of
92+
/// this group.
93+
///
94+
/// This function is non-deterministic, and samples from the user-provided RNG.
95+
fn try_from_rng<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error>;
8096

8197
/// Returns the additive identity, also known as the "neutral element".
8298
fn identity() -> Self;

0 commit comments

Comments
 (0)