Random

Introduction

Random is a tiny library that provides a convenient API to generate any number of random outcomes based on a provided seed.

First, it uses the seed bytes directly, so the results are as random as the provided seed. This gives to your disposal up to 8 u32 integers (or equivalent in other types) that are strongly random.

Once all bytes are used the first time - it shuffles them by a simple algorithm that guarantees to produce a unique new pseudo-random sequence of bytes for at least 420 reuse cycles. This should be enough for any practical application inside a Scrypto component.

All methods return results that are uniformly distributed within limits decided either by the data type or by the provided arguments.

API reference

/// Instantiate a new Random. Seed length must be a multiple of 4.
pub fn new(seed: &Vec<u8>) -> Random
/// Returns `true` or `false`.
pub fn next_bool(&mut self) -> bool
/// Returns a random number of size T (u8, u16, u32, u64, usize).
pub fn next_int<T>(&mut self) -> T where T: Num
/// Returns a random number in the range [min, max).
pub fn in_range<T>(&mut self, min: T, max: T) -> T where T: Num
/// Returns a random number in the range [0, max). For example, `roll(3)` will return one of [0, 1, 2].
pub fn roll<T>(&mut self, max: T) -> T where T: Num

Usage

First, you add a dependency to your `Cargo.toml` (see the latest revision in the examples repo):

Then you can instantiate and use it inside your callback:

Examples

Last updated