2022-01-04 10:21:08 +01:00
|
|
|
// Copyright (c) 2019-2022 Alexander Medvednikov. All rights reserved.
|
2020-06-01 21:13:56 +02:00
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
2020-06-09 15:06:07 +02:00
|
|
|
module wyrand
|
2020-06-01 21:13:56 +02:00
|
|
|
|
2021-01-26 14:55:09 +01:00
|
|
|
import rand.seed
|
2021-01-29 10:57:30 +01:00
|
|
|
import rand.constants
|
2021-01-26 14:55:09 +01:00
|
|
|
import hash
|
2020-06-01 21:13:56 +02:00
|
|
|
|
2020-12-27 19:06:17 +01:00
|
|
|
// Redefinition of some constants that we will need for pseudorandom number generation.
|
2020-06-01 21:13:56 +02:00
|
|
|
const (
|
|
|
|
wyp0 = u64(0xa0761d6478bd642f)
|
|
|
|
wyp1 = u64(0xe7037ed1a0b428db)
|
|
|
|
)
|
|
|
|
|
2020-12-27 19:06:17 +01:00
|
|
|
// WyRandRNG is a RNG based on the WyHash hashing algorithm.
|
2020-06-01 21:13:56 +02:00
|
|
|
pub struct WyRandRNG {
|
|
|
|
mut:
|
2021-01-26 14:55:09 +01:00
|
|
|
state u64 = seed.time_seed_64()
|
2020-09-09 15:34:41 +02:00
|
|
|
has_extra bool
|
2020-06-01 21:13:56 +02:00
|
|
|
extra u32
|
|
|
|
}
|
|
|
|
|
2020-12-27 19:06:17 +01:00
|
|
|
// seed sets the seed, needs only two `u32`s in little-endian format as [lower, higher].
|
2020-06-01 21:13:56 +02:00
|
|
|
pub fn (mut rng WyRandRNG) seed(seed_data []u32) {
|
|
|
|
if seed_data.len != 2 {
|
|
|
|
eprintln('WyRandRNG 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
|
|
|
|
}
|
|
|
|
|
2020-12-27 19:06:17 +01:00
|
|
|
// u32 updates the PRNG state and returns the next pseudorandom `u32`.
|
2020-06-01 21:13:56 +02:00
|
|
|
[inline]
|
|
|
|
pub fn (mut rng WyRandRNG) u32() u32 {
|
|
|
|
if rng.has_extra {
|
|
|
|
rng.has_extra = false
|
|
|
|
return rng.extra
|
|
|
|
}
|
|
|
|
full_value := rng.u64()
|
2021-01-29 10:57:30 +01:00
|
|
|
lower := u32(full_value & constants.lower_mask)
|
2020-06-01 21:13:56 +02:00
|
|
|
upper := u32(full_value >> 32)
|
|
|
|
rng.extra = upper
|
|
|
|
rng.has_extra = true
|
|
|
|
return lower
|
|
|
|
}
|
|
|
|
|
2020-12-27 19:06:17 +01:00
|
|
|
// u64 updates the PRNG state and returns the next pseudorandom `u64`.
|
2020-06-01 21:13:56 +02:00
|
|
|
[inline]
|
|
|
|
pub fn (mut rng WyRandRNG) u64() u64 {
|
|
|
|
unsafe {
|
|
|
|
mut seed1 := rng.state
|
2021-01-26 14:55:09 +01:00
|
|
|
seed1 += wyrand.wyp0
|
2020-06-01 21:13:56 +02:00
|
|
|
rng.state = seed1
|
2021-01-26 14:55:09 +01:00
|
|
|
return hash.wymum(seed1 ^ wyrand.wyp1, seed1)
|
2020-06-01 21:13:56 +02:00
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|