1#include "prng.h"
2
3#include <base/system.h>
4
5// From https://en.wikipedia.org/w/index.php?title=Permuted_congruential_generator&oldid=901497400#Example_code.
6//
7// > The generator recommended for most users is PCG-XSH-RR with 64-bit state
8// > and 32-bit output.
9
10#define NAME "pcg-xsh-rr"
11
12CPrng::CPrng() :
13 m_Seeded(false)
14{
15}
16
17const char *CPrng::Description() const
18{
19 if(!m_Seeded)
20 {
21 return NAME ":unseeded";
22 }
23 return m_aDescription;
24}
25
26static unsigned int RotateRight32(unsigned int x, int Shift)
27{
28 return (x >> Shift) | (x << (-Shift & 31));
29}
30
31void CPrng::Seed(uint64_t aSeed[2])
32{
33 m_Seeded = true;
34 str_format(buffer: m_aDescription, buffer_size: sizeof(m_aDescription), format: "%s:%08x%08x:%08x%08x", NAME,
35 (unsigned)(aSeed[0] >> 32), (unsigned)aSeed[0],
36 (unsigned)(aSeed[1] >> 32), (unsigned)aSeed[1]);
37
38 m_Increment = (aSeed[1] << 1) | 1;
39 m_State = aSeed[0] + m_Increment;
40 RandomBits();
41}
42
43unsigned int CPrng::RandomBits()
44{
45 dbg_assert(m_Seeded, "prng needs to be seeded before it can generate random numbers");
46
47 uint64_t x = m_State;
48 unsigned int Count = x >> 59;
49
50 static const uint64_t s_Multiplier = 6364136223846793005u;
51 m_State = x * s_Multiplier + m_Increment;
52 x ^= x >> 18;
53 return RotateRight32(x: x >> 27, Shift: Count);
54}
55