Skip to main content

with_rng

Function with_rng 

Source
pub fn with_rng<F, R>(f: F) -> R
where F: FnOnce(&RngGuard) -> R,
Expand description

Run f with R’s RNG state loaded, handing it the guard to draw from.

Loads the state (GetRNGstate()) when it is called, not before, so a set.seed() that ran in R before this call decides the draws. The state is saved (PutRNGstate()) when f returns or panics. This is a convenience wrapper around RngGuard.

§Example

ⓘ
use miniextendr_api::rng::with_rng;

let values = with_rng(|rng| (0..10).map(|_| rng.unif_rand()).collect::<Vec<_>>());

§Panics

Panics when called off R’s main thread.

§Warning

Like RngGuard, this relies on Rust drop semantics and won’t properly clean up if R longjumps. For R-exposed functions, use #[miniextendr(rng)] instead, and draw from its &RngGuard parameter rather than calling with_rng inside it (see the module docs).