Skip to main content

RngGuard

Struct RngGuard 

Source
pub struct RngGuard {
    _private: (),
}
Expand description

RAII guard for R’s RNG state.

Calls GetRNGstate() on creation and PutRNGstate() on drop. This ensures RNG state is properly saved even if the function panics or returns early.

§Example

use miniextendr_api::rng::RngGuard;
use miniextendr_api::ffi::unif_rand;

fn generate_uniform() -> f64 {
    let _guard = RngGuard::new();
    unsafe { unif_rand() }
}

§Warning: R Longjumps

This guard relies on Rust’s drop semantics. If R triggers a longjmp (via Rf_error etc.), the destructor will NOT run unless the code is wrapped in with_r_unwind_protect. For functions exposed to R, prefer using #[miniextendr(rng)] which handles this correctly.

§Safety

Must be used on R’s main thread. The guard assumes it has exclusive access to R’s RNG state while alive.

Fields§

§_private: ()

Implementations§

Source§

impl RngGuard

Source

pub fn new() -> Self

Create a new RNG guard, loading the current RNG state.

Calls GetRNGstate() to load R’s .Random.seed into the RNG.

§Safety

Must be called from R’s main thread.

Trait Implementations§

Source§

impl Default for RngGuard

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for RngGuard

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> RDefault for T
where T: Default,

Source§

fn default() -> T

Create a new instance with default values.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.