Skip to content

Commit e6ebb38

Browse files
authored
Random: get rid of random_seed() (#58042)
For seeding `MersenneTwister()` randomly, we were generating a random seed via `RandomDevice()`, but if it failed, we used other means. This was implemented in `random_seed()`, which dates back from a long time ago, maybe when the ancestor of `RandomDevice()` had a reasonable chance to fail. But nowadays, it never fails in practice, and even the new default RNG uses it fearlessly. So RIP `random_seed()`.
1 parent 019aa63 commit e6ebb38

File tree

1 file changed

+6
-17
lines changed

1 file changed

+6
-17
lines changed

stdlib/Random/src/RNGs.jl

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -278,20 +278,7 @@ end
278278

279279
### seeding
280280

281-
#### random_seed() & hash_seed()
282-
283-
# random_seed tries to produce a random seed of type UInt128 from system entropy
284-
function random_seed()
285-
try
286-
# as MersenneTwister prints its seed when `show`ed, 128 bits is a good compromise for
287-
# almost surely always getting distinct seeds, while having them printed reasonably tersely
288-
return rand(RandomDevice(), UInt128)
289-
catch ex
290-
ex isa IOError || rethrow()
291-
@warn "Entropy pool not available to seed RNG; using ad-hoc entropy sources."
292-
return Libc.rand()
293-
end
294-
end
281+
#### hash_seed()
295282

296283
function hash_seed(seed::Integer)
297284
ctx = SHA.SHA2_256_CTX()
@@ -370,11 +357,13 @@ function initstate!(r::MersenneTwister, data::StridedVector, seed)
370357
return r
371358
end
372359

373-
# when a seed is not provided, we generate one via `RandomDevice()` in `random_seed()` rather
360+
# When a seed is not provided, we generate one via `RandomDevice()` rather
374361
# than calling directly `initstate!` with `rand(RandomDevice(), UInt32, whatever)` because the
375362
# seed is printed in `show(::MersenneTwister)`, so we need one; the cost of `hash_seed` is a
376-
# small overhead compared to `initstate!`, so this simple solution is fine
377-
seed!(r::MersenneTwister, ::Nothing) = seed!(r, random_seed())
363+
# small overhead compared to `initstate!`, so this simple solution is fine.
364+
# A random seed with 128 bits is a good compromise for almost surely always getting distinct
365+
# seeds, while having them printed reasonably tersely.
366+
seed!(r::MersenneTwister, ::Nothing) = seed!(r, rand(RandomDevice(), UInt128))
378367
seed!(r::MersenneTwister, seed) = initstate!(r, hash_seed(seed), seed)
379368

380369

0 commit comments

Comments
 (0)