use crate::mathx;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum DrawKind {
Uniform = 0,
Normal = 1,
}
impl DrawKind {
pub fn name(self) -> &'static str {
match self {
DrawKind::Uniform => "uniform",
DrawKind::Normal => "normal",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum Site {
Unset = 0,
MarketFactorZ = 1,
SectorZ = 2,
FactorIdioZ = 3,
StashU = 4,
SettleU = 5,
JumpMarketU = 6,
JumpMarketZ = 7,
JumpCompanyU = 8,
JumpCompanyZ = 9,
VolumeZ = 10,
VolumeIdioZ = 11,
NewsU = 12,
NewsZ = 13,
EconomyDaily = 14,
EconomyCycle = 15,
CentralBank = 16,
External = 17,
OvernightMarketZ = 18,
OvernightSectorZ = 19,
OvernightIdioZ = 20,
MarketVolLevelZ = 21,
CrisisEpicentreU = 22,
CycleNowcastU = 23,
OvernightIdioChi2 = 24,
MarketDayTailChi2 = 25,
FuturesBasisZ = 26,
NightBridgeZ = 27,
}
impl Site {
pub fn name(self) -> &'static str {
match self {
Site::Unset => "unset",
Site::MarketFactorZ => "market_factor_z",
Site::SectorZ => "sector_z",
Site::FactorIdioZ => "factor_idio_z",
Site::StashU => "stash_u",
Site::SettleU => "settle_u",
Site::JumpMarketU => "jump_market_u",
Site::JumpMarketZ => "jump_market_z",
Site::JumpCompanyU => "jump_company_u",
Site::JumpCompanyZ => "jump_company_z",
Site::VolumeZ => "volume_z",
Site::VolumeIdioZ => "volume_idio_z",
Site::NewsU => "news_u",
Site::NewsZ => "news_z",
Site::EconomyDaily => "economy_daily",
Site::EconomyCycle => "economy_cycle",
Site::CentralBank => "central_bank",
Site::External => "external",
Site::OvernightMarketZ => "overnight_market_z",
Site::OvernightSectorZ => "overnight_sector_z",
Site::OvernightIdioZ => "overnight_idio_z",
Site::MarketVolLevelZ => "market_vol_level_z",
Site::CrisisEpicentreU => "crisis_epicentre_u",
Site::CycleNowcastU => "cycle_nowcast_u",
Site::OvernightIdioChi2 => "overnight_idio_chi2",
Site::MarketDayTailChi2 => "market_day_tail_chi2",
Site::FuturesBasisZ => "futures_basis_z",
Site::NightBridgeZ => "night_bridge_z",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct DrawRecord {
pub kind: DrawKind,
pub index: u64,
pub value: f64,
pub day: i64,
pub site: Site,
pub tag: u32,
}
const _: () = assert!(std::mem::size_of::<DrawRecord>() == 32);
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct DrawOverlay {
pub table: std::collections::BTreeMap<(DrawKind, u64), f64>,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DrawLog {
pub from_day: i64,
pub to_day: i64,
pub records: Vec<DrawRecord>,
}
pub mod stream {
pub const MARKET: u32 = 0;
pub const ECONOMY: u32 = 1;
pub const EXTERNAL: u32 = 2;
pub const JUMPS: u32 = 3;
pub const VOLUME: u32 = 4;
pub const NEWS: u32 = 5;
pub const VOLUME_IDIO: u32 = 6;
pub const OVERNIGHT: u32 = 7;
pub const MARKET_VOL_LEVEL: u32 = 8;
pub const CRISIS_EPICENTRE: u32 = 9;
pub const OPENING: u32 = 10;
pub const CYCLE_NOWCAST: u32 = 11;
pub const ARRIVAL: u32 = 12;
pub const EARNINGS: u32 = 13;
pub const DERIVATIVES: u32 = 14;
pub const COUNT: usize = 10;
pub const STREAM_SEQUENCE_BASE: u32 = 256;
pub const SURGERY_SEQUENCE_BASE: u32 = 512;
pub const SURGERY_TAG: u32 = 0x5355_5247;
pub const SEED64_SEQUENCE_BASE: u32 = 768;
pub const SEED64_SURGERY_SEQUENCE_BASE: u32 = 1024;
pub const SEED64_TAG: u32 = 0x5344_3634;
pub const KEYED_SEQUENCE: u32 = 1280;
}
fn splitmix64_mix(input: u64) -> u64 {
let mut z = input.wrapping_add(0x9E37_79B9_7F4A_7C15);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
pub const PUBLICATION_TAG: u32 = 0x5055_424C;
pub const PREHISTORY_TAG: u64 = 0x5052_4548;
pub fn prehistory_key(key: u64) -> u64 {
splitmix64_mix(key ^ (PREHISTORY_TAG << 32 | PREHISTORY_TAG))
}
pub const AGE_LAW_TAG: u64 = 0x4147_454C;
pub fn age_law_key(key: u64) -> u64 {
splitmix64_mix(key ^ (AGE_LAW_TAG << 32 | AGE_LAW_TAG))
}
pub const OIL_DRIFT_TAG: u32 = 0x4F49_4C44;
pub fn oil_drift_key(root_seed: u64) -> u64 {
splitmix64_mix(root_seed ^ (((OIL_DRIFT_TAG as u64) << 32) | 0xFFFF_FFFF))
}
pub const CORE_TREND_TAG: u32 = 0x4354_5244;
pub fn core_trend_key(root_seed: u64) -> u64 {
splitmix64_mix(root_seed ^ (((CORE_TREND_TAG as u64) << 32) | 0xFFFF_FFFF))
}
pub const SPREAD_NOISE_TAG: u32 = 0x4353_504E;
pub fn spread_noise_key(root_seed: u64) -> u64 {
splitmix64_mix(root_seed ^ (((SPREAD_NOISE_TAG as u64) << 32) | 0xFFFF_FFFF))
}
pub const TERM_PREMIUM_TAG: u32 = 0x5454_504D;
pub fn term_premium_key(root_seed: u64) -> u64 {
splitmix64_mix(root_seed ^ (((TERM_PREMIUM_TAG as u64) << 32) | 0xFFFF_FFFF))
}
pub fn publication_key(root_seed: u64) -> u64 {
splitmix64_mix(root_seed ^ (((PUBLICATION_TAG as u64) << 32) | 0xFFFF_FFFF))
}
pub const SKEW_NOISE_TAG: u32 = 0x534B_574E;
pub fn skew_noise_key(root_seed: u64) -> u64 {
splitmix64_mix(root_seed ^ (((SKEW_NOISE_TAG as u64) << 32) | 0xFFFF_FFFF))
}
pub const GUIDANCE_SIGNAL_TAG: u32 = 0x4753_4947;
pub fn guidance_signal_key(root_seed: u64) -> u64 {
splitmix64_mix(root_seed ^ (((GUIDANCE_SIGNAL_TAG as u64) << 32) | 0xFFFF_FFFF))
}
pub fn publication_uniform(key: u64, k: u64) -> f64 {
let z = splitmix64_mix(key ^ splitmix64_mix(((PUBLICATION_TAG as u64) << 32) | (k & 0xFFFF_FFFF)));
(z >> 11) as f64 * (1.0 / (1u64 << 53) as f64)
}
fn stream_mix(root_seed: u64, stream_id: u32) -> u64 {
if root_seed >> 32 == 0 {
(root_seed << 32) | stream_id as u64
} else {
root_seed ^ splitmix64_mix(((stream::SEED64_TAG as u64) << 32) | stream_id as u64)
}
}
fn fnv1a64(bytes: &[u8]) -> u64 {
let mut h: u64 = 0xCBF2_9CE4_8422_2325;
for &b in bytes {
h = (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01B3);
}
h
}
pub fn arrival_priority(seed: u64, day: u64, step_of_day: u64, label: &str) -> u64 {
let base = splitmix64_mix(stream_mix(seed, stream::ARRIVAL));
let key = splitmix64_mix(splitmix64_mix(base ^ day) ^ step_of_day);
splitmix64_mix(key ^ fnv1a64(label.as_bytes()))
}
pub trait Rng {
fn next_f64(&mut self) -> f64;
fn next_normal(&mut self) -> f64;
fn site(&mut self, _site: Site, _tag: u32) {}
}
impl Rng for GameRng {
fn next_f64(&mut self) -> f64 {
GameRng::next_f64(self)
}
fn next_normal(&mut self) -> f64 {
GameRng::next_normal(self)
}
fn site(&mut self, site: Site, tag: u32) {
self.site = site;
self.tag = tag;
}
}
pub fn to_uint32(value: f64) -> u32 {
if !value.is_finite() {
return 0;
}
let truncated = value.trunc();
let modulo = truncated.rem_euclid(4294967296.0);
modulo as u32
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct RngState {
pub state: u64,
pub increment: u64,
pub spare: Option<f64>,
pub uniforms: u64,
pub normals: u64,
}
impl RngState {
pub fn to_words(&self) -> [f64; crate::widths::RNG_STREAM_WIDTH] {
[
f64::from_bits(self.state),
f64::from_bits(self.increment),
self.spare.unwrap_or(f64::NAN),
self.uniforms as f64,
self.normals as f64,
]
}
pub fn from_words(words: &[f64]) -> Result<Self, String> {
const W: usize = crate::widths::RNG_STREAM_WIDTH;
let words: &[f64; W] = words.try_into().map_err(|_| {
format!(
"an RNG stream state is {W} numbers (state, increment, spare, \
uniforms, normals), got {}",
words.len()
)
})?;
let increment = words[1].to_bits();
if increment & 1 == 0 {
return Err(format!(
"the increment word holds the bits {increment:#018x}, which is \
even. Every PCG increment is odd, so the word was changed on \
the way: a NaN whose bits were rewritten is the usual cause."
));
}
let spare = if words[2].is_nan() {
None
} else if words[2].is_finite() {
Some(words[2])
} else {
return Err(format!(
"the spare word is {}; a spare is finite, or NaN for none.",
words[2]
));
};
let count = |name: &str, v: f64| -> Result<u64, String> {
if v.is_finite() && v >= 0.0 && v.fract() == 0.0 && v <= 9_007_199_254_740_992.0 {
Ok(v as u64)
} else {
Err(format!("the {name} word holds {v}; a draw count is a whole number from 0."))
}
};
Ok(RngState {
state: words[0].to_bits(),
increment,
spare,
uniforms: count("uniforms", words[3])?,
normals: count("normals", words[4])?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pcg32 {
state: u64,
inc: u64,
}
const PCG_MULTIPLIER: u64 = 0x5851_F42D_4C95_7F2D;
impl Pcg32 {
pub fn new(seed: u64, sequence: u32) -> Self {
let mut rng = Self {
state: 0,
inc: ((sequence as u64) << 1) | 1,
};
rng.step();
rng.state = rng.state.wrapping_add(seed);
rng.step();
rng
}
fn step(&mut self) -> u32 {
let old = self.state;
self.state = old.wrapping_mul(PCG_MULTIPLIER).wrapping_add(self.inc);
let xorshifted = (((old >> 18) ^ old) >> 27) as u32;
let rot = (old >> 59) as u32;
xorshifted.rotate_right(rot)
}
pub fn next_u32(&mut self) -> u32 {
self.step()
}
pub fn next_f64(&mut self) -> f64 {
self.next_u32() as f64 / 4294967296.0
}
}
#[derive(Debug, Clone)]
pub struct GameRng {
pcg: Pcg32,
spare: Option<f64>,
uniforms: u64,
normals: u64,
overlay: Option<Box<DrawOverlay>>,
log: Option<Box<DrawLog>>,
site: Site,
tag: u32,
day: i64,
}
impl PartialEq for GameRng {
fn eq(&self, other: &Self) -> bool {
self.pcg == other.pcg && self.spare == other.spare
}
}
impl GameRng {
pub fn new(seed: u64, sequence: u32) -> Self {
Self {
pcg: Pcg32::new(seed, sequence),
spare: None,
uniforms: 0,
normals: 0,
overlay: None,
log: None,
site: Site::Unset,
tag: 0,
day: 0,
}
}
pub fn positions(&self) -> (u64, u64) {
(self.uniforms, self.normals)
}
pub fn patch(&mut self, kind: DrawKind, index: u64, value: f64) {
self.overlay
.get_or_insert_with(Default::default)
.table
.insert((kind, index), value);
}
pub fn overlay(&self) -> Option<&DrawOverlay> {
self.overlay.as_deref()
}
pub fn set_overlay(&mut self, overlay: Option<DrawOverlay>) {
self.overlay = overlay.filter(|o| !o.table.is_empty()).map(Box::new);
}
pub fn enable_log(&mut self, from_day: i64, to_day: i64) {
match self.log.as_deref_mut() {
Some(log) => {
if from_day < log.from_day {
log.from_day = from_day;
}
if to_day > log.to_day {
log.to_day = to_day;
}
}
None => {
self.log = Some(Box::new(DrawLog { from_day, to_day, records: Vec::new() }));
}
}
}
pub fn log(&self) -> Option<&DrawLog> {
self.log.as_deref()
}
pub fn clear_log_records(&mut self) {
if let Some(log) = self.log.as_deref_mut() {
log.records.clear();
log.records.shrink_to_fit();
}
}
pub fn set_day(&mut self, day: i64) {
self.day = day;
}
#[inline]
fn deliver(&mut self, kind: DrawKind, index: u64, raw: f64) -> f64 {
let value = match &self.overlay {
Some(o) => o.table.get(&(kind, index)).copied().unwrap_or(raw),
None => raw,
};
if let Some(log) = &mut self.log {
if log.from_day <= self.day && self.day <= log.to_day {
log.records.push(DrawRecord {
kind,
index,
value,
day: self.day,
site: self.site,
tag: self.tag,
});
}
}
value
}
pub fn from_seed(seed: u64) -> Self {
Self::new(seed, 0)
}
pub fn substream(root_seed: u64, stream_id: u32) -> Self {
if root_seed >> 32 == 0 {
let mixed = splitmix64_mix(stream_mix(root_seed, stream_id));
Self::new(mixed >> 32, stream::STREAM_SEQUENCE_BASE + stream_id)
} else {
Self::new(
splitmix64_mix(stream_mix(root_seed, stream_id)),
stream::SEED64_SEQUENCE_BASE + stream_id,
)
}
}
pub fn earnings_key(root_seed: u64) -> u64 {
let mut g = Self::substream(root_seed, stream::EARNINGS);
let hi = g.pcg.next_u32() as u64;
let lo = g.pcg.next_u32() as u64;
(hi << 32) | lo
}
pub fn keyed(key: u64, a: u64, b: u64) -> Self {
let seed = splitmix64_mix(key ^ splitmix64_mix(a ^ splitmix64_mix(b)));
Self::new(seed, stream::KEYED_SEQUENCE)
}
pub fn surgery(root_seed: u64, stream_id: u32, surgery_seed: u64) -> Self {
let inner = splitmix64_mix(stream_mix(root_seed, stream_id));
if (root_seed | surgery_seed) >> 32 == 0 {
let mixed = splitmix64_mix(
inner ^ ((surgery_seed << 32) | stream::SURGERY_TAG as u64),
);
Self::new(mixed >> 32, stream::SURGERY_SEQUENCE_BASE + stream_id)
} else {
let key = ((stream::SURGERY_TAG as u64) << 32) | stream::SEED64_TAG as u64;
let mixed = splitmix64_mix(inner ^ splitmix64_mix(surgery_seed ^ key));
Self::new(mixed, stream::SEED64_SURGERY_SEQUENCE_BASE + stream_id)
}
}
pub fn next_f64(&mut self) -> f64 {
let raw = self.pcg.next_f64();
let index = self.uniforms;
self.uniforms += 1;
self.deliver(DrawKind::Uniform, index, raw)
}
pub fn snapshot(&self) -> RngState {
RngState {
state: self.pcg.state,
increment: self.pcg.inc,
spare: self.spare,
uniforms: self.uniforms,
normals: self.normals,
}
}
pub fn restore(state: RngState) -> Self {
Self {
pcg: Pcg32 {
state: state.state,
inc: state.increment,
},
spare: state.spare,
uniforms: state.uniforms,
normals: state.normals,
overlay: None,
log: None,
site: Site::Unset,
tag: 0,
day: 0,
}
}
pub fn next_normal(&mut self) -> f64 {
let index = self.normals;
self.normals += 1;
let raw = self.next_normal_raw();
self.deliver(DrawKind::Normal, index, raw)
}
fn next_normal_raw(&mut self) -> f64 {
if let Some(spare) = self.spare.take() {
return spare;
}
let raw = self.pcg.next_f64();
let u = if raw == 0.0 { 1e-10 } else { raw };
let v = self.pcg.next_f64();
let r = mathx::sqrt(-2.0 * mathx::log(u));
self.spare = Some(r * mathx::sin(2.0 * std::f64::consts::PI * v));
r * mathx::cos(2.0 * std::f64::consts::PI * v)
}
pub fn next_int(&mut self, min: i64, max: i64) -> i64 {
let range = max - min + 1;
if range <= 0 {
return min;
}
min + (self.pcg.next_u32() as i64 % range)
}
pub fn next_bool(&mut self, p: f64) -> bool {
self.next_f64() < p
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn publication_draws_are_the_documented_stateless_formula() {
let key = publication_key(7);
assert_eq!(key, splitmix64_mix(7 ^ ((0x5055_424Cu64 << 32) | 0xFFFF_FFFF)));
for k in 0..2000u64 {
let u = publication_uniform(key, k);
assert!((0.0..1.0).contains(&u), "{u}");
let z = splitmix64_mix(key ^ splitmix64_mix((0x5055_424Cu64 << 32) | k));
assert_eq!(u, (z >> 11) as f64 / (1u64 << 53) as f64);
assert_eq!(u, publication_uniform(key, k));
}
assert_ne!(publication_uniform(key, 0), publication_uniform(key, 1));
assert_ne!(publication_key(7), publication_key(8));
assert_ne!(publication_key(7), publication_key(7 | (1 << 40)));
let mean: f64 = (0..10_000u64).map(|k| publication_uniform(key, k)).sum::<f64>() / 10_000.0;
assert!((mean - 0.5).abs() < 0.01, "{mean}");
}
#[test]
fn is_deterministic_for_a_given_seed() {
let mut a = GameRng::from_seed(42);
let mut b = GameRng::from_seed(42);
for _ in 0..1000 {
assert_eq!(a.next_f64().to_bits(), b.next_f64().to_bits());
}
}
#[test]
fn different_seeds_diverge() {
let mut a = GameRng::from_seed(42);
let mut b = GameRng::from_seed(43);
let differs = (0..100).any(|_| a.next_f64() != b.next_f64());
assert!(differs, "seeds 42 and 43 produced identical prefixes");
}
#[test]
fn sequence_zero_and_one_are_different_streams() {
let mut a = GameRng::new(42, 0);
let mut b = GameRng::new(42, 1);
let differs = (0..100).any(|_| a.next_f64() != b.next_f64());
assert!(differs, "sequence 0 and 1 produced the same stream");
}
#[test]
fn floats_are_in_unit_interval() {
let mut rng = GameRng::from_seed(7);
for _ in 0..100_000 {
let x = rng.next_f64();
assert!((0.0..1.0).contains(&x), "out of range: {x}");
}
}
#[test]
fn normal_spare_is_returned_next_and_unchanged() {
let mut probe = GameRng::from_seed(11);
let _first = probe.next_normal();
let cached = probe.spare;
assert!(cached.is_some(), "first next_normal did not cache a spare");
let second = probe.next_normal();
assert_eq!(second.to_bits(), cached.unwrap().to_bits());
assert!(probe.spare.is_none(), "spare was not consumed");
}
#[test]
fn next_int_stays_within_bounds() {
let mut rng = GameRng::from_seed(3);
for _ in 0..100_000 {
let v = rng.next_int(-5, 5);
assert!((-5..=5).contains(&v), "out of range: {v}");
}
}
#[test]
fn to_uint32_matches_javascript_coercion() {
assert_eq!(to_uint32(0.0), 0);
assert_eq!(to_uint32(42.0), 42);
assert_eq!(to_uint32(4294967296.0), 0, "2^32 wraps to 0");
assert_eq!(to_uint32(-1.0), 4294967295, "-1 wraps to u32::MAX");
assert_eq!(to_uint32(4294967297.0), 1, "2^32 + 1 wraps to 1");
assert_eq!(to_uint32(2147483648.0), 2147483648, "2^31 is unchanged");
assert_eq!(to_uint32(1.9), 1, "truncates toward zero");
assert_eq!(to_uint32(-1.9), 4294967295, "truncates, then wraps");
assert_eq!(to_uint32(f64::NAN), 0);
assert_eq!(to_uint32(f64::INFINITY), 0);
}
}
#[cfg(test)]
mod address_tests {
use super::*;
#[test]
fn a_patch_substitutes_without_moving_the_stream() {
let mut plain = GameRng::new(42, 7);
let mut patched = GameRng::new(42, 7);
patched.patch(DrawKind::Uniform, 3, 0.25);
patched.patch(DrawKind::Normal, 2, -1.5);
for i in 0..12u64 {
let (a, b) = (plain.next_f64(), patched.next_f64());
if i == 3 {
assert_eq!(b, 0.25);
} else {
assert_eq!(a.to_bits(), b.to_bits());
}
let (c, d) = (plain.next_normal(), patched.next_normal());
if i == 2 {
assert_eq!(d, -1.5);
} else {
assert_eq!(c.to_bits(), d.to_bits());
}
}
assert_eq!(plain, patched, "the positions diverged");
assert_eq!(plain.positions(), patched.positions());
}
#[test]
fn normals_index_by_normal_count_and_uniforms_by_uniform_count() {
let mut rng = GameRng::new(3, 3);
rng.next_normal();
rng.next_normal();
rng.next_f64();
assert_eq!(rng.positions(), (1, 2));
let mut other = GameRng::new(3, 3);
other.patch(DrawKind::Normal, 1, 9.0);
other.next_normal();
assert_eq!(other.next_normal(), 9.0, "the spare's address is normal 1");
let mut plain = GameRng::new(3, 3);
plain.next_normal();
plain.next_normal();
assert_eq!(other.next_f64().to_bits(), plain.next_f64().to_bits());
assert_eq!(other.positions(), (1, 2));
}
#[test]
fn the_log_records_what_the_consumer_received() {
let mut rng = GameRng::new(5, 5);
rng.patch(DrawKind::Uniform, 1, 0.5);
rng.enable_log(0, 0);
rng.set_day(0);
rng.site(Site::External, 7);
let first = rng.next_f64();
let second = rng.next_f64();
let z = rng.next_normal();
let log = rng.log().unwrap();
assert_eq!(log.records.len(), 3);
assert_eq!(log.records[0].value, first);
assert_eq!((log.records[1].kind, log.records[1].index, log.records[1].value), (DrawKind::Uniform, 1, 0.5));
assert_eq!(second, 0.5);
assert_eq!((log.records[2].kind, log.records[2].index, log.records[2].value, log.records[2].site, log.records[2].tag),
(DrawKind::Normal, 0, z, Site::External, 7));
rng.set_day(1);
rng.next_f64();
assert_eq!(rng.log().unwrap().records.len(), 3, "a day outside the range is not logged");
}
#[test]
fn a_restored_generator_keeps_its_addresses() {
let mut rng = GameRng::new(9, 9);
for _ in 0..5 {
rng.next_f64();
rng.next_normal();
}
let restored = GameRng::restore(rng.snapshot());
assert_eq!(restored.positions(), (5, 5));
assert_eq!(restored, rng);
}
}
#[cfg(test)]
mod substream_tests {
use super::*;
#[test]
fn substream_derivation_is_the_documented_formula() {
for (id, seed) in [
(stream::MARKET, 0xEA67_E2F1_u64),
(stream::ECONOMY, 0x6997_3300),
(stream::EXTERNAL, 0x4B07_4493),
] {
let mut derived = GameRng::substream(42, id);
let mut expected = GameRng::new(seed, stream::STREAM_SEQUENCE_BASE + id);
for _ in 0..64 {
assert_eq!(
derived.next_f64().to_bits(),
expected.next_f64().to_bits(),
"stream {id} does not match the documented derivation"
);
}
}
}
#[test]
fn surgery_derivation_is_the_documented_formula() {
for (root, id, surgery, seed) in [
(42_u64, stream::JUMPS, 7_u64, 0x493A_2503_u64),
(42, stream::MARKET, 1, 0xF382_1A83),
(7, stream::VOLUME_IDIO, 0, 0x3D21_372F),
] {
let mut derived = GameRng::surgery(root, id, surgery);
let mut expected = GameRng::new(seed, stream::SURGERY_SEQUENCE_BASE + id);
for _ in 0..64 {
assert_eq!(
derived.next_f64().to_bits(),
expected.next_f64().to_bits(),
"surgery ({root}, {id}, {surgery}) does not match the documented derivation"
);
}
}
}
#[test]
fn a_surgery_differs_from_its_stream_and_from_other_surgeries() {
let mut own = GameRng::substream(42, stream::JUMPS);
let mut a = GameRng::surgery(42, stream::JUMPS, 7);
assert!((0..64).any(|_| own.next_f64() != a.next_f64()));
let mut a = GameRng::surgery(42, stream::JUMPS, 7);
let mut b = GameRng::surgery(42, stream::JUMPS, 8);
assert!((0..64).any(|_| a.next_f64() != b.next_f64()));
let mut a = GameRng::surgery(42, stream::JUMPS, 7);
let mut c = GameRng::surgery(42, stream::MARKET, 7);
assert!((0..64).any(|_| a.next_f64() != c.next_f64()));
let mut a = GameRng::surgery(42, stream::JUMPS, 7);
let mut d = GameRng::surgery(43, stream::JUMPS, 7);
assert!((0..64).any(|_| a.next_f64() != d.next_f64()));
}
#[test]
fn substreams_of_one_root_differ_from_each_other() {
let ids = [stream::MARKET, stream::ECONOMY, stream::EXTERNAL];
for a in ids {
for b in ids {
if a == b {
continue;
}
let mut x = GameRng::substream(7, a);
let mut y = GameRng::substream(7, b);
assert!(
(0..64).any(|_| x.next_f64() != y.next_f64()),
"streams {a} and {b} agree on a 64-draw prefix"
);
}
}
}
#[test]
fn substreams_differ_across_roots() {
let mut x = GameRng::substream(1, stream::MARKET);
let mut y = GameRng::substream(2, stream::MARKET);
assert!((0..64).any(|_| x.next_f64() != y.next_f64()));
}
#[test]
fn no_substream_is_a_shifted_copy_of_another() {
let ids = [stream::MARKET, stream::ECONOMY, stream::EXTERNAL];
for a in ids {
for b in ids {
if a == b {
continue;
}
let reference: Vec<u32> = {
let mut rng = GameRng::substream(2026, a);
(0..64).map(|_| rng.pcg.next_u32()).collect()
};
let window: Vec<u32> = {
let mut rng = GameRng::substream(2026, b);
(0..1024).map(|_| rng.pcg.next_u32()).collect()
};
assert!(
!window
.windows(reference.len())
.any(|w| w == reference.as_slice()),
"stream {b} replays stream {a}'s prefix at an offset"
);
}
}
}
#[test]
fn substreams_do_not_replay_the_legacy_streams() {
for legacy_sequence in [0, 1, 21, 99] {
for id in [stream::MARKET, stream::ECONOMY, stream::EXTERNAL] {
let mut legacy = GameRng::new(42, legacy_sequence);
let mut derived = GameRng::substream(42, id);
assert!(
(0..64).any(|_| derived.next_f64() != legacy.next_f64()),
"substream {id} replays legacy sequence {legacy_sequence}"
);
}
}
}
}
#[cfg(test)]
mod snapshot_tests {
use super::*;
#[test]
fn a_restored_generator_continues_the_same_stream() {
let mut original = GameRng::new(42, 7);
for _ in 0..37 {
original.next_f64();
}
let mark = original.snapshot();
let expected: Vec<f64> = (0..20).map(|_| original.next_f64()).collect();
let mut restored = GameRng::restore(mark);
let actual: Vec<f64> = (0..20).map(|_| restored.next_f64()).collect();
assert_eq!(expected, actual);
}
#[test]
fn the_cached_spare_is_part_of_the_state() {
let mut original = GameRng::new(11, 3);
original.next_normal();
assert!(original.snapshot().spare.is_some(), "expected a cached spare");
let mark = original.snapshot();
let expected = original.next_normal();
assert_eq!(GameRng::restore(mark).next_normal(), expected);
let mut without_spare = GameRng::restore(RngState {
spare: None,
..mark
});
assert_ne!(without_spare.next_normal(), expected);
}
#[test]
fn a_snapshot_survives_a_mixed_stream() {
let mut original = GameRng::new(5, 99);
for i in 0..25 {
if i % 3 == 0 {
original.next_normal();
} else {
original.next_f64();
}
}
let mark = original.snapshot();
let expected: Vec<f64> = (0..30)
.map(|i| {
if i % 2 == 0 {
original.next_normal()
} else {
original.next_f64()
}
})
.collect();
let mut restored = GameRng::restore(mark);
let actual: Vec<f64> = (0..30)
.map(|i| {
if i % 2 == 0 {
restored.next_normal()
} else {
restored.next_f64()
}
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn two_different_positions_do_not_snapshot_alike() {
let mut rng = GameRng::new(1, 1);
let first = rng.snapshot();
rng.next_f64();
assert_ne!(first, rng.snapshot());
}
}
#[cfg(test)]
mod seed64_tests {
use super::*;
const WIDE: u64 = (1 << 63) + 12345;
fn same_prefix(a: &mut GameRng, b: &mut GameRng) -> bool {
(0..64).all(|_| a.next_f64().to_bits() == b.next_f64().to_bits())
}
#[test]
fn wide_substream_derivation_is_the_documented_formula() {
for (root, id, seed) in [
(1_u64 << 32, stream::MARKET, 0x7547_BEE2_B588_1CEC_u64),
(WIDE, stream::ECONOMY, 0xF98D_6EE9_28B9_562B),
(u64::MAX, stream::EXTERNAL, 0x58C7_9E4C_21E1_08AB),
(0xDEAD_BEEF_0000_0001, stream::NEWS, 0x85B0_9E41_94B4_8998),
] {
let mut derived = GameRng::substream(root, id);
let mut expected = GameRng::new(seed, stream::SEED64_SEQUENCE_BASE + id);
assert!(same_prefix(&mut derived, &mut expected),
"wide root {root:#x}, stream {id} does not match the documented formula");
}
}
#[test]
fn wide_surgery_derivation_is_the_documented_formula() {
for (root, id, surgery, seed) in [
(42_u64, stream::JUMPS, 1_u64 << 32, 0x619E_7212_72AA_47E0_u64),
(WIDE, stream::JUMPS, 7, 0xE96A_D364_3F0A_0013),
(u64::MAX, stream::MARKET, u64::MAX, 0xA2CB_0D15_ABB5_23B0),
] {
let mut derived = GameRng::surgery(root, id, surgery);
let mut expected =
GameRng::new(seed, stream::SEED64_SURGERY_SEQUENCE_BASE + id);
assert!(same_prefix(&mut derived, &mut expected),
"surgery ({root:#x}, {id}, {surgery:#x}) does not match the documented formula");
}
}
#[test]
fn the_boundary_is_at_two_to_the_thirty_two() {
let top = (1_u64 << 32) - 1;
let old = splitmix64_mix((top << 32) | stream::MARKET as u64) >> 32;
let mut a = GameRng::substream(top, stream::MARKET);
let mut b = GameRng::new(old, stream::STREAM_SEQUENCE_BASE + stream::MARKET);
assert!(same_prefix(&mut a, &mut b));
assert_eq!(a.snapshot().increment, b.snapshot().increment);
let mut wide = GameRng::substream(1 << 32, stream::MARKET);
let mut zero = GameRng::substream(0, stream::MARKET);
assert!(!same_prefix(&mut wide, &mut zero));
assert_ne!(GameRng::substream(1 << 32, stream::MARKET).snapshot().increment,
GameRng::substream(0, stream::MARKET).snapshot().increment);
}
#[test]
fn roots_differing_only_in_the_high_bits_are_different_markets() {
for low in [0_u64, 5, 0xFFFF_FFFF] {
for high in [1_u64, 2, 0x8000_0000, 0xFFFF_FFFF] {
for id in 0..stream::COUNT as u32 {
let mut a = GameRng::substream(low, id);
let mut b = GameRng::substream(low | (high << 32), id);
assert!(!same_prefix(&mut a, &mut b),
"root {low:#x} and {:#x} share stream {id}", low | (high << 32));
}
let mut a = GameRng::surgery(low, stream::JUMPS, 3);
let mut b = GameRng::surgery(low | (high << 32), stream::JUMPS, 3);
assert!(!same_prefix(&mut a, &mut b));
let mut a = GameRng::surgery(7, stream::JUMPS, low);
let mut b = GameRng::surgery(7, stream::JUMPS, low | (high << 32));
assert!(!same_prefix(&mut a, &mut b));
}
}
}
#[test]
fn no_two_wide_roots_on_a_sample_share_a_starting_state() {
use std::collections::HashSet;
for id in [stream::MARKET, stream::ECONOMY, stream::NEWS] {
let mut states = HashSet::new();
let mut roots = 0;
for high in 1_u64..=128 {
for low in 0_u64..128 {
let root = (high << 32) | low;
assert!(states.insert(GameRng::substream(root, id).snapshot().state),
"root {root:#x} repeats a starting state on stream {id}");
roots += 1;
}
}
for offset in 0_u64..1024 {
assert!(states.insert(GameRng::substream(u64::MAX - offset, id).snapshot().state));
roots += 1;
}
assert_eq!(states.len(), roots);
}
}
#[test]
fn wide_roots_use_sequences_no_narrow_root_does() {
let narrow: std::collections::HashSet<u64> = (0..=stream::OPENING)
.flat_map(|id| {
[GameRng::substream(42, id).snapshot().increment,
GameRng::surgery(42, id, 1).snapshot().increment]
})
.collect();
for id in 0..=stream::OPENING {
assert!(!narrow.contains(&GameRng::substream(WIDE, id).snapshot().increment));
assert!(!narrow.contains(&GameRng::surgery(WIDE, id, 1).snapshot().increment));
assert!(!narrow.contains(&GameRng::surgery(42, id, 1 << 40).snapshot().increment));
}
}
#[test]
fn arrival_priority_is_the_documented_formula() {
assert_eq!(arrival_priority(201, 0, 0, "a"), 0x09f6_9160_e6ea_96dc);
assert_eq!(arrival_priority(201, 3, 1, "b"), 0x3bc1_d0a9_9543_6b68);
assert_eq!(arrival_priority((1 << 40) + 7, 5, 2, "claude"), 0x32c6_8be7_c13f_fe3b);
assert!(arrival_priority(201, 3, 1, "b") < arrival_priority(201, 3, 1, "a"));
assert_eq!(fnv1a64(b""), 0xCBF2_9CE4_8422_2325);
assert_eq!(fnv1a64(b"a"), 0xAF63_DC4C_8601_EC8C);
}
#[test]
fn the_raw_generator_takes_all_sixty_four_bits() {
let mut a = GameRng::new(0xFFFF_FFFF, 21);
let mut b = GameRng::new(u32::MAX as u64, 21);
assert!(same_prefix(&mut a, &mut b));
let mut wide = GameRng::new(1 << 32, 21);
let mut zero = GameRng::new(0, 21);
assert!(!same_prefix(&mut wide, &mut zero));
let mut top = GameRng::new(u64::MAX, 21);
let mut other = GameRng::new(u64::MAX - (1 << 32), 21);
assert!(!same_prefix(&mut top, &mut other));
}
}