index/misc

Misc scripts and tools
git clone https://git.alexwennerberg.com/misc

rand.rs@main

raw
fef0790 Add simple rand library alex wennerberg 2021-07-21 12:16:39+0700
...

1// A fast, low quality and insecure pseudo-random number generator, for when 
2// those things don't matter
3// 
4// Don't use this as a crate, just copy/paste this code
5// and save yourself a dependency
6
7use std::cell::Cell;
8use std::time::{SystemTime, UNIX_EPOCH};
9
10
11fn main() {
12    // Example usage
13    println!("Unseeded rand:");
14    for _ in 0..3 { 
15        println!("{}", rand());
16    }
17    println!("\nSeeded rand:");
18    let start = SystemTime::now();
19    let time = start
20        .duration_since(UNIX_EPOCH).unwrap();
21    seed_rand(time.as_secs());
22    for _ in 0..3 { 
23        println!("{}", rand());
24    }
25
26    println!("\nroll a d20:");
27    println!("{}", rand() % 20);
28
29    println!("\nflip a coin:");
30    println!("{}", match rand() % 2 {
31        0 => "heads",
32        1 => "tails",
33        _ => "sideways",
34    })
35}
36
37thread_local!(static SEED: Cell<u64> = Cell::new(0));
38
39fn seed_rand(n: u64) {
40    SEED.with(|s|  {
41        s.set(n - 1)
42    })
43}
44
45// LCG https://en.wikipedia.org/wiki/Linear_congruential_generator
46// from musl https://git.musl-libc.org/cgit/musl/tree/src/prng/rand.c
47fn rand() -> u64 {
48    SEED.with(|s|  {
49        s.set(6364136223846793005_u64.wrapping_mul(s.get()) + 1);
50        s.get() >> 33
51    })
52}
53