scoop:scoop.std:0.1.0
src/random/xoshiro.scoop
Selected production source · src/random/xoshiro.scoop
1
package scoop.random3
// xoshiro256** by David Blackman and Sebastiano Vigna (2018),4
// seeded with SplitMix64 by Sebastiano Vigna (2015). See licenses/PRNG.txt.5
private fun splitMix(value: ULong): ULong {6
var mixed = (value xor (value shr 30L)) * 0xbf58476d1ce4e5b9uL7
mixed = (mixed xor (mixed shr 27L)) * 0x94d049bb133111ebuL8
return mixed xor (mixed shr 31L)9
}11
private fun xoshiroSeed(seed: Long): (ULong, ULong, ULong, ULong) {12
val step = 0x9e3779b97f4a7c15uL13
val first = seed.toULong() + step14
return (splitMix(first), splitMix(first + step), splitMix(first + step * 2uL), splitMix(first + step * 3uL))15
}17
private 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 for22
* repeatable randomized algorithms, not cryptographic secrets.23
*/24
public class Xoshiro256StarStar private constructor(state: (ULong, ULong, ULong, ULong)) : Random {25
private var first: ULong = state._126
private var second: ULong = state._227
private var third: ULong = state._328
private var fourth: ULong = state._430
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 count34
* 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 039
val result = rotateLeft(second * 5uL, 7L) * 9uL40
val shifted = second shl 17L41
third = third xor first42
fourth = fourth xor second43
second = second xor third44
first = first xor fourth45
third = third xor shifted46
fourth = rotateLeft(fourth, 45L)47
return (result shr (64L - bitCount.toLong())).toInt()48
}49
}