1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

rand: extend PRNG interface, add buffering support (#13608)

This commit is contained in:
Subhomoy Haldar
2022-02-28 16:47:54 +05:30
committed by GitHub
parent efeb3e04da
commit a0d9e6e1c2
9 changed files with 380 additions and 110 deletions

View File

@ -4,14 +4,15 @@
module splitmix64
import rand.seed
import rand.constants
pub const seed_len = 2
// SplitMix64RNG ported from http://xoshiro.di.unimi.it/splitmix64.c
pub struct SplitMix64RNG {
mut:
state u64 = seed.time_seed_64()
has_extra bool
extra u32
state u64 = seed.time_seed_64()
bytes_left int
buffer u64
}
// seed sets the seed of the accepting SplitMix64RNG to the given data
@ -22,25 +23,57 @@ pub fn (mut rng SplitMix64RNG) seed(seed_data []u32) {
exit(1)
}
rng.state = seed_data[0] | (u64(seed_data[1]) << 32)
rng.has_extra = false
rng.bytes_left = 0
rng.buffer = 0
}
// u32 updates the PRNG state and returns the next pseudorandom `u32`.
// byte returns a uniformly distributed pseudorandom 8-bit unsigned positive `byte`.
[inline]
pub fn (mut rng SplitMix64RNG) byte() byte {
if rng.bytes_left >= 1 {
rng.bytes_left -= 1
value := byte(rng.buffer)
rng.buffer >>= 8
return value
}
rng.buffer = rng.u64()
rng.bytes_left = 7
value := byte(rng.buffer)
rng.buffer >>= 8
return value
}
// u16 returns a pseudorandom 16bit int in range `[0, 2¹⁶)`.
[inline]
pub fn (mut rng SplitMix64RNG) u16() u16 {
if rng.bytes_left >= 2 {
rng.bytes_left -= 2
value := u16(rng.buffer)
rng.buffer >>= 16
return value
}
ans := rng.u64()
rng.buffer = ans >> 16
rng.bytes_left = 6
return u16(ans)
}
// u32 returns a pseudorandom 32bit int in range `[0, 2³²)`.
[inline]
pub fn (mut rng SplitMix64RNG) u32() u32 {
if rng.has_extra {
rng.has_extra = false
return rng.extra
if rng.bytes_left >= 4 {
rng.bytes_left -= 4
value := u32(rng.buffer)
rng.buffer >>= 32
return value
}
full_value := rng.u64()
lower := u32(full_value & constants.lower_mask)
upper := u32(full_value >> 32)
rng.extra = upper
rng.has_extra = true
return lower
ans := rng.u64()
rng.buffer = ans >> 32
rng.bytes_left = 4
return u32(ans)
}
// u64 updates the PRNG state and returns the next pseudorandom `u64`.
// u64 returns a pseudorandom 64bit int in range `[0, 2⁶⁴)`.
[inline]
pub fn (mut rng SplitMix64RNG) u64() u64 {
rng.state += (0x9e3779b97f4a7c15)
@ -50,6 +83,12 @@ pub fn (mut rng SplitMix64RNG) u64() u64 {
return z ^ (z >> (31))
}
// block_size returns the number of bits that the RNG can produce in a single iteration.
[inline]
pub fn (mut rng SplitMix64RNG) block_size() int {
return 64
}
// free should be called when the generator is no longer needed
[unsafe]
pub fn (mut rng SplitMix64RNG) free() {