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,15 +4,18 @@
module pcg32
import rand.seed
import rand.constants
pub const seed_len = 4
// PCG32RNG ported from http://www.pcg-random.org/download.html,
// https://github.com/imneme/pcg-c-basic/blob/master/pcg_basic.c, and
// https://github.com/imneme/pcg-c-basic/blob/master/pcg_basic.h
pub struct PCG32RNG {
mut:
state u64 = u64(0x853c49e6748fea9b) ^ seed.time_seed_64()
inc u64 = u64(0xda3e39cb94b95bdb) ^ seed.time_seed_64()
state u64 = u64(0x853c49e6748fea9b) ^ seed.time_seed_64()
inc u64 = u64(0xda3e39cb94b95bdb) ^ seed.time_seed_64()
bytes_left int
buffer u32
}
// seed seeds the PCG32RNG with 4 `u32` values.
@@ -30,11 +33,44 @@ pub fn (mut rng PCG32RNG) seed(seed_data []u32) {
rng.u32()
rng.state += init_state
rng.u32()
rng.bytes_left = 0
rng.buffer = 0
}
// byte returns a uniformly distributed pseudorandom 8-bit unsigned positive `byte`.
[inline]
fn (mut rng PCG32RNG) byte() byte {
if rng.bytes_left >= 1 {
rng.bytes_left -= 1
value := byte(rng.buffer)
rng.buffer >>= 8
return value
}
rng.buffer = rng.u32()
rng.bytes_left = 3
value := byte(rng.buffer)
rng.buffer >>= 8
return value
}
// u16 returns a pseudorandom 16-bit unsigned integer (`u16`).
[inline]
pub fn (mut rng PCG32RNG) u16() u16 {
if rng.bytes_left >= 2 {
rng.bytes_left -= 2
value := u16(rng.buffer)
rng.buffer >>= 16
return value
}
ans := rng.u32()
rng.buffer = ans >> 16
rng.bytes_left = 2
return u16(ans)
}
// u32 returns a pseudorandom unsigned `u32`.
[inline]
pub fn (mut rng PCG32RNG) u32() u32 {
fn (mut rng PCG32RNG) u32() u32 {
oldstate := rng.state
rng.state = oldstate * (6364136223846793005) + rng.inc
xorshifted := u32(((oldstate >> u64(18)) ^ oldstate) >> u64(27))
@@ -48,6 +84,12 @@ pub fn (mut rng PCG32RNG) u64() u64 {
return u64(rng.u32()) | (u64(rng.u32()) << 32)
}
// block_size returns the number of bits that the RNG can produce in a single iteration.
[inline]
pub fn (mut rng PCG32RNG) block_size() int {
return 32
}
// free should be called when the generator is no longer needed
[unsafe]
pub fn (mut rng PCG32RNG) free() {