Scoop API

scoop:scoop.std:0.1.0

src/random/xoshiro.scoop

Selected production source · src/random/xoshiro.scoop

1package scoop.random
3// xoshiro256** by David Blackman and Sebastiano Vigna (2018),
4// seeded with SplitMix64 by Sebastiano Vigna (2015). See licenses/PRNG.txt.
5private fun splitMix(value: ULong): ULong {
6 var mixed = (value xor (value shr 30L)) * 0xbf58476d1ce4e5b9uL
7 mixed = (mixed xor (mixed shr 27L)) * 0x94d049bb133111ebuL
8 return mixed xor (mixed shr 31L)
9}
11private fun xoshiroSeed(seed: Long): (ULong, ULong, ULong, ULong) {
12 val step = 0x9e3779b97f4a7c15uL
13 val first = seed.toULong() + step
14 return (splitMix(first), splitMix(first + step), splitMix(first + step * 2uL), splitMix(first + step * 3uL))
17private fun rotateLeft(value: ULong, bits: Long): ULong =
18 (value shl bits) or (value shr (64L - bits))
20/**
21 * A deterministic xoshiro256** generator initialized from a Long seed. It is intended for
22 * repeatable randomized algorithms, not cryptographic secrets.
23 */
24public class Xoshiro256StarStar private constructor(state: (ULong, ULong, ULong, ULong)) : Random {
25 private var first: ULong = state._1
26 private var second: ULong = state._2
27 private var third: ULong = state._3
28 private var fourth: ULong = state._4
30 public constructor(seed: Long) : this(xoshiroSeed(seed)) {}
32 /**
33 * Returns 0..32 high bits of the next generator output in the result's low bits. A zero count
34 * returns zero without advancing the generator; counts outside this range throw.
35 */
36 public override fun nextBits(bitCount: Int): Int {
37 if (bitCount < 0 || bitCount > 32) throw IllegalArgumentException(Some("bitCount must be in 0..32"))
38 if (bitCount == 0) return 0
39 val result = rotateLeft(second * 5uL, 7L) * 9uL
40 val shifted = second shl 17L
41 third = third xor first
42 fourth = fourth xor second
43 second = second xor third
44 first = first xor fourth
45 third = third xor shifted
46 fourth = rotateLeft(fourth, 45L)
47 return (result shr (64L - bitCount.toLong())).toInt()
48 }