/// A seeded random generator: SplitMix64 (Steele, Lea and Flood, 2014), /// for simulations, property tests, reproducible shuffles and the seeded /// `random` handler (`random.with_seed`, ADR 0036). /// /// let g = prng.seeded(42) /// let (x, g) = prng.next(g) // a U64, and the next generator /// /// **Not for secrets.** Its output is predictable from a few values: never /// use it for tokens, salts, keys or IDs; `std/random`'s system handler /// reads the kernel's generator for those. /// /// The sequence for a seed is part of the interface: changing it would /// change what seeded tests see, so it is a breaking change. import std/u64.{type U64} /// A generator's state. pub opaque type Prng { Prng(U64) } /// A generator seeded with `seed` (taken modulo 2^64). pub fn seeded :: seed: Int -> Prng { Prng(u64.from_int seed) } /// The next 64 random bits, and the generator to draw the following ones /// from. pub fn next :: g: Prng -> (U64, Prng) { match g { Prng(state) -> { let s = state + word 0x9E3779B9 0x7F4A7C15 let z = u64.xor s (u64.shift_right s 30) * word 0xBF58476D 0x1CE4E5B9 let z = u64.xor z (u64.shift_right z 27) * word 0x94D049BB 0x133111EB (u64.xor z (u64.shift_right z 31), Prng(s)) } } } /// `hi * 2^32 + lo`: U64 has no literals, and Int literals stop at 2^62. fn word :: hi: Int lo: Int -> U64 { u64.or (u64.shift_left (u64.from_int hi) 32) (u64.from_int lo) }