2022-01-04 12:21:08 +03:00
|
|
|
// Copyright (c) 2019-2022 Alexander Medvednikov. All rights reserved.
|
2020-06-01 22:13:56 +03:00
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
2020-06-09 16:06:07 +03:00
|
|
|
module splitmix64
|
|
|
|
|
2021-01-26 16:55:09 +03:00
|
|
|
import rand.seed
|
2021-01-29 12:57:30 +03:00
|
|
|
import rand.constants
|
2020-06-01 22:13:56 +03:00
|
|
|
|
2020-12-27 21:06:17 +03:00
|
|
|
// SplitMix64RNG ported from http://xoshiro.di.unimi.it/splitmix64.c
|
2020-06-01 22:13:56 +03:00
|
|
|
pub struct SplitMix64RNG {
|
2019-09-23 00:50:22 +03:00
|
|
|
mut:
|
2021-01-26 16:55:09 +03:00
|
|
|
state u64 = seed.time_seed_64()
|
2020-09-09 16:34:41 +03:00
|
|
|
has_extra bool
|
2020-06-01 22:13:56 +03:00
|
|
|
extra u32
|
2019-09-23 00:50:22 +03:00
|
|
|
}
|
2019-12-20 00:29:37 +03:00
|
|
|
|
2020-12-27 21:06:17 +03:00
|
|
|
// seed sets the seed of the accepting SplitMix64RNG to the given data
|
2020-06-01 22:13:56 +03:00
|
|
|
// in little-endian format (i.e. lower 32 bits are in [0] and higher 32 bits in [1]).
|
|
|
|
pub fn (mut rng SplitMix64RNG) seed(seed_data []u32) {
|
|
|
|
if seed_data.len != 2 {
|
|
|
|
eprintln('SplitMix64RNG needs 2 32-bit unsigned integers as the seed.')
|
|
|
|
exit(1)
|
|
|
|
}
|
|
|
|
rng.state = seed_data[0] | (u64(seed_data[1]) << 32)
|
|
|
|
rng.has_extra = false
|
2019-09-23 00:50:22 +03:00
|
|
|
}
|
2019-12-20 00:29:37 +03:00
|
|
|
|
2020-12-27 21:06:17 +03:00
|
|
|
// u32 updates the PRNG state and returns the next pseudorandom `u32`.
|
2020-06-01 22:13:56 +03:00
|
|
|
[inline]
|
|
|
|
pub fn (mut rng SplitMix64RNG) u32() u32 {
|
|
|
|
if rng.has_extra {
|
|
|
|
rng.has_extra = false
|
|
|
|
return rng.extra
|
|
|
|
}
|
|
|
|
full_value := rng.u64()
|
2021-01-29 12:57:30 +03:00
|
|
|
lower := u32(full_value & constants.lower_mask)
|
2020-06-01 22:13:56 +03:00
|
|
|
upper := u32(full_value >> 32)
|
|
|
|
rng.extra = upper
|
|
|
|
rng.has_extra = true
|
|
|
|
return lower
|
|
|
|
}
|
2019-12-20 00:29:37 +03:00
|
|
|
|
2020-12-27 21:06:17 +03:00
|
|
|
// u64 updates the PRNG state and returns the next pseudorandom `u64`.
|
2019-12-20 00:29:37 +03:00
|
|
|
[inline]
|
2020-06-01 22:13:56 +03:00
|
|
|
pub fn (mut rng SplitMix64RNG) u64() u64 {
|
2019-12-07 15:51:00 +03:00
|
|
|
rng.state += (0x9e3779b97f4a7c15)
|
2019-09-23 00:50:22 +03:00
|
|
|
mut z := rng.state
|
2021-11-16 12:44:36 +03:00
|
|
|
z = (z ^ (z >> u64(30))) * 0xbf58476d1ce4e5b9
|
|
|
|
z = (z ^ (z >> u64(27))) * 0x94d049bb133111eb
|
2020-06-01 22:13:56 +03:00
|
|
|
return z ^ (z >> (31))
|
2019-09-23 00:50:22 +03:00
|
|
|
}
|
2019-12-20 00:29:37 +03:00
|
|
|
|
2021-09-23 11:14:20 +03:00
|
|
|
// free should be called when the generator is no longer needed
|
|
|
|
[unsafe]
|
|
|
|
pub fn (mut rng SplitMix64RNG) free() {
|
|
|
|
unsafe { free(rng) }
|
|
|
|
}
|