tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

45 lignes · 1453 octetsBrut · Historique
1/// A seeded random generator: SplitMix64 (Steele, Lea and Flood, 2014),
2/// for simulations, property tests, reproducible shuffles and the seeded
3/// `random` handler (`random.with_seed`, ADR 0036).
4///
5/// let g = prng.seeded(42)
6/// let (x, g) = prng.next(g) // a U64, and the next generator
7///
8/// **Not for secrets.** Its output is predictable from a few values: never
9/// use it for tokens, salts, keys or IDs; `std/random`'s system handler
10/// reads the kernel's generator for those.
11///
12/// The sequence for a seed is part of the interface: changing it would
13/// change what seeded tests see, so it is a breaking change.
14
15import std/u64.{type U64}
16
17/// A generator's state.
18pub opaque type Prng { Prng(U64) }
19
20/// A generator seeded with `seed` (taken modulo 2^64).
21pub fn seeded :: seed: Int -> Prng
22{
23 Prng(u64.from_int seed)
24}
25
26/// The next 64 random bits, and the generator to draw the following ones
27/// from.
28pub fn next :: g: Prng -> (U64, Prng)
29{
30 match g
31 { Prng(state) ->
32 {
33 let s = state + word 0x9E3779B9 0x7F4A7C15
34 let z = u64.xor s (u64.shift_right s 30) * word 0xBF58476D 0x1CE4E5B9
35 let z = u64.xor z (u64.shift_right z 27) * word 0x94D049BB 0x133111EB
36 (u64.xor z (u64.shift_right z 31), Prng(s))
37 }
38 }
39}
40
41/// `hi * 2^32 + lo`: U64 has no literals, and Int literals stop at 2^62.
42fn word :: hi: Int lo: Int -> U64
43{
44 u64.or (u64.shift_left (u64.from_int hi) 32) (u64.from_int lo)
45}