Skip to content

Commit 081c64b

Browse files
committed
chore(stdlib): fix math.random to use thread-local LCG for reliable virtualized clock resolution
1 parent 1e5f473 commit 081c64b

1 file changed

Lines changed: 18 additions & 5 deletions

File tree

stdlib/src/math.rs

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -159,12 +159,25 @@ impl StdlibRegistry {
159159
name: "random".to_string(),
160160
arity: 0,
161161
callback: |_ctx, _args| {
162+
use std::cell::Cell;
162163
use std::time::SystemTime;
163-
let nano = SystemTime::now()
164-
.duration_since(SystemTime::UNIX_EPOCH)
165-
.unwrap_or_default()
166-
.subsec_nanos();
167-
let rand_float = (nano as f64) / 1_000_000_000.0;
164+
thread_local! {
165+
static SEED: Cell<u64> = Cell::new({
166+
SystemTime::now()
167+
.duration_since(SystemTime::UNIX_EPOCH)
168+
.unwrap_or_default()
169+
.as_nanos() as u64
170+
});
171+
}
172+
let next_seed = SEED.with(|cell| {
173+
let current = cell.get();
174+
let next = current
175+
.wrapping_mul(6364136223846793005)
176+
.wrapping_add(1442695040888963407);
177+
cell.set(next);
178+
next
179+
});
180+
let rand_float = (next_seed as f64) / (u64::MAX as f64);
168181
Ok(RuntimeValue::Float(rand_float))
169182
},
170183
}),

0 commit comments

Comments
 (0)