Skip to main content

Module block

Module block 

Source
Expand description

The Generator trait and BlockRng

Trait Generator may be implemented by block-generators; that is PRNGs whose output is a block of words, such as [u32; 16].

The struct BlockRng wraps such a Generator together with an output buffer and implements several methods (e.g. BlockRng::next_word) to assist in the implementation of TryRng. Note that (unlike in earlier versions of rand_core) BlockRng itself does not implement TryRng since in practice we found it was always beneficial to use a wrapper type over BlockRng.

§Example

use core::convert::Infallible;
use rand_core::{Rng, SeedableRng, TryRng};
use rand_core::block::{Generator, BlockRng};

struct MyRngCore {
    // Generator state ...
}

impl Generator for MyRngCore {
    type Output = [u32; 8];

    fn generate(&mut self, output: &mut Self::Output) {
        // Write a new block to output...
    }
}

// Our RNG is a wrapper over BlockRng
pub struct MyRng(BlockRng<MyRngCore>);

impl SeedableRng for MyRng {
    type Seed = [u8; 32];
    fn from_seed(seed: Self::Seed) -> Self {
        let core = MyRngCore {
            // ...
        };
        MyRng(BlockRng::new(core))
    }
}

impl TryRng for MyRng {
    type Error = Infallible;

    #[inline]
    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
        Ok(self.0.next_word())
    }

    #[inline]
    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
        Ok(self.0.next_u64_from_u32())
    }

    #[inline]
    fn try_fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Infallible> {
        Ok(self.0.fill_bytes(bytes))
    }
}

// And if applicable: impl TryCryptoRng for MyRng {}

let mut rng = MyRng::seed_from_u64(0);
println!("First value: {}", rng.next_u32());

Structs§

BlockRng
RNG functionality for a block Generator

Traits§

Generator
A random (block) generator