misc

Misc scripts and tools
git clone git://git.alexwennerberg.com/misc
Log | Files | Refs | README | LICENSE

commit fef0790fa2f8b20b554c7e18e9b74952dd2529ae
parent 38145fafbe0f46e125dcf1b174e8dd9fcafac4e9
Author: alex wennerberg <alex@alexwennerberg.com>
Date:   Tue, 20 Jul 2021 22:16:39 -0700

Add simple rand library

Diffstat:
Arand.rs | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 52 insertions(+), 0 deletions(-)

diff --git a/rand.rs b/rand.rs @@ -0,0 +1,52 @@ +// A fast, low quality and insecure pseudo-random number generator, for when +// those things don't matter +// +// Don't use this as a crate, just copy/paste this code +// and save yourself a dependency + +use std::cell::Cell; +use std::time::{SystemTime, UNIX_EPOCH}; + + +fn main() { + // Example usage + println!("Unseeded rand:"); + for _ in 0..3 { + println!("{}", rand()); + } + println!("\nSeeded rand:"); + let start = SystemTime::now(); + let time = start + .duration_since(UNIX_EPOCH).unwrap(); + seed_rand(time.as_secs()); + for _ in 0..3 { + println!("{}", rand()); + } + + println!("\nroll a d20:"); + println!("{}", rand() % 20); + + println!("\nflip a coin:"); + println!("{}", match rand() % 2 { + 0 => "heads", + 1 => "tails", + _ => "sideways", + }) +} + +thread_local!(static SEED: Cell<u64> = Cell::new(0)); + +fn seed_rand(n: u64) { + SEED.with(|s| { + s.set(n - 1) + }) +} + +// LCG https://en.wikipedia.org/wiki/Linear_congruential_generator +// from musl https://git.musl-libc.org/cgit/musl/tree/src/prng/rand.c +fn rand() -> u64 { + SEED.with(|s| { + s.set(6364136223846793005_u64.wrapping_mul(s.get()) + 1); + s.get() >> 33 + }) +}