fix rand_bytes: init at least the local domain's Rand state

This commit is contained in:
Simon Cruanes 2025-12-04 10:17:20 -05:00
parent 689b932c63
commit 5aec2c99b8
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4

View file

@ -1,4 +1,12 @@
let initialized_ = Atomic.make false
let[@inline never] actually_init () = Random.self_init ()
let[@inline] maybe_init () =
if not (Atomic.exchange initialized_ true) then actually_init ()
let default_rand_bytes_8 () : bytes = let default_rand_bytes_8 () : bytes =
maybe_init ();
let b = Bytes.create 8 in let b = Bytes.create 8 in
for i = 0 to 1 do for i = 0 to 1 do
(* rely on the stdlib's [Random] being thread-or-domain safe *) (* rely on the stdlib's [Random] being thread-or-domain safe *)
@ -14,6 +22,7 @@ let default_rand_bytes_8 () : bytes =
b b
let default_rand_bytes_16 () : bytes = let default_rand_bytes_16 () : bytes =
maybe_init ();
let b = Bytes.create 16 in let b = Bytes.create 16 in
for i = 0 to 4 do for i = 0 to 4 do
(* rely on the stdlib's [Random] being thread-or-domain safe *) (* rely on the stdlib's [Random] being thread-or-domain safe *)