#rng #dirty #cheap #non-deterministic

voxell_rng

Cheap and dirty thread-local RNGs

4 releases (2 breaking)

new 0.3.0 Nov 20, 2024
0.2.0 Nov 19, 2024
0.1.1 Nov 16, 2024
0.1.0 Nov 16, 2024

#455 in Algorithms

Download history 186/week @ 2024-11-11

186 downloads per month

MIT license

84KB
2.5K SLoC

Cheap and dirty RNGs

use voxell_rng::rng::XorShift32;
// seeds using runtime entropy (no overhead / no syscalls)
let mut rng = XorShift32::default();
rng.next_u32();

Welcome to the land of unreproducible builds

Use this crate if you need simple random number generators for your project and you don't want to depend on a big library like rand.

You can seed your RNGs using the system time voxell_rng::time_seeded or runtime entropy voxell_rng::runtime_seeded.

There are 4 RNGs available:

All RNGs implement BranchRng which is a simple trait that provides a branch_rng method for creating a new divergent RNG from the current one. The resulting RNG will have a different state and will produce different random numbers without needing to specify a new seed.

Examples

  1. Create a new RNG using a constant seed and use it:
use voxell_rng::rng::XorShift32;

// create the rng
let mut rng = XorShift32::new(0xcafebabe as u64);

// generate a new number
rng.next_f32();
  1. Seed your RNGs using the system time
use voxell_rng::time_seeded::TimeSeededXorShift32;
let mut rng = TimeSeededXorShift32::generate().unwrap();
rng.next_f32();
  1. Seed your RNGs using runtime entropy
use voxell_rng::runtime_seeded::MagicallySeededXorShift32;
let mut rng = MagicallySeededXorShift32::new_magic();
rng.next_f32();

let mut rng2 = MagicallySeededXorShift32::new_with_reference(&());
rng2.next_f32();
  1. Create new RNGs from a master RNG for divergent thread local RNGs:
use voxell_rng::branch_rng::BranchRng;
use voxell_rng::rng::XoRoShiRo128Plus;

let mut master_rng = XoRoShiRo128Plus::new(0xabad1dea as u64);
let thread_handles = (0..16)
    .map(|_| {
        let rng = master_rng.branch_rng();
        std::thread::spawn(move || {
            let mut thread_local_rng = rng;
            for _ in 0..1000 {
                thread_local_rng.next_u64();
            }
        })
    })
    .collect::<Vec<_>>();

Dependencies

~47KB