//! The pdfTeX random primitives share a job-owned fixed-point sequence. //! Both draws and explicit reseeding become part of a saved continuation. use serde::{Deserialize, Serialize}; const FRACTION: i64 = 1 << 28; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub(super) struct Random { seed: i32, values: Vec, position: usize, } impl Random { pub(super) fn new(seed: i32) -> Self { let seed = seed.saturating_abs(); let mut previous = i64::from(seed); while previous >= FRACTION { previous /= 2; } let mut delta = 1; let mut state = Self { seed, values: vec![0; 55], position: 0, }; for index in 0..55 { (previous, delta) = (delta, (previous - delta).rem_euclid(FRACTION)); state.values[(index * 21) % 55] = previous; } for _ in 0..3 { state.advance(); } state } pub(super) fn seed(&self) -> i32 { self.seed } fn advance(&mut self) { for i in 0..55 { let offset = if i < 24 { i + 31 } else { i - 24 }; self.values[i] = (self.values[i] - self.values[offset]).rem_euclid(FRACTION); } self.position = 54; } fn next(&mut self) -> i64 { if self.position == 0 { self.advance(); } else { self.position -= 1; } self.values[self.position] } pub(super) fn uniform(&mut self, bound: i32) -> i32 { let value = rounded_quotient(i64::from(bound) * self.next(), FRACTION) as i32; if value == bound { 0 } else { value } } /// One trial of the ratio method. The executor can cancel or charge work /// between trials, including trials rejected before the logarithm. pub(super) fn normal_trial(&mut self) -> Option { let offset = self.next() - FRACTION / 2; let x = rounded_quotient(112_429 * offset, FRACTION); let uniform = self.next(); if x.abs() >= uniform { return None; } let sample = rounded_quotient(x * FRACTION, uniform); let log = 139_548_960 - fixed_log(uniform); (sample * sample <= 1024 * log).then_some(sample as i32) } } fn rounded_quotient(numerator: i64, denominator: i64) -> i64 { numerator.signum() * ((numerator.abs() + denominator / 2) / denominator) } /// Fixed-point logarithm used by the ratio acceptance test. Computing a /// floating-point log here can select a different trial and change later draws. fn fixed_log(mut sample: i64) -> i64 { const LOGARITHMS: [i64; 13] = [ 93_032_640, 38_612_034, 17_922_280, 8_662_214, 4_261_238, 2_113_709, 1_052_693, 525_315, 262_400, 131_136, 65_552, 32_772, 16_385, ]; const FLOOR: i64 = 4 * FRACTION; let mut result = 1_302_456_860 - 100; let mut remainder = 27_595 + 6_553_600; while sample < FLOOR { sample *= 2; result -= 93_032_639; remainder -= 48_782; } result += remainder / 65_536; let mut bit = 2; while sample > FLOOR + 4 { let mut amount = ((sample - 1) >> bit) + 1; while sample < FLOOR + amount { amount = (amount + 1) / 2; bit += 1; } result += match bit { 1..=13 => LOGARITHMS[bit - 1], 14..=27 => 1 << (27 - bit), _ => 1, }; sample -= amount; } result / 8 }