v/vlib/rand/wyrand/wyrand.v

60 lines
1.5 KiB
V
Raw Normal View History

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
import rand.seed
import rand.constants
import hash
2020-06-01 21:13:56 +02: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)
)
// WyRandRNG is a RNG based on the WyHash hashing algorithm.
2020-06-01 21:13:56 +02:00
pub struct WyRandRNG {
mut:
state u64 = seed.time_seed_64()
has_extra bool
2020-06-01 21:13:56 +02:00
extra u32
}
// 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
}
// 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()
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
}
// 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
seed1 += wyrand.wyp0
2020-06-01 21:13:56 +02:00
rng.state = seed1
return hash.wymum(seed1 ^ wyrand.wyp1, seed1)
2020-06-01 21:13:56 +02:00
}
return 0
}