smol-rs / fastrand

A simple and fast random number generator
Apache License 2.0
386 stars 33 forks source link

Using getrandom on non-wasm targets? #65

Closed mwcampbell closed 1 year ago

mwcampbell commented 1 year ago

I'm curious about why fastrand doesn't use getrandom on non-wasm targets. Is it just for the sake of reducing the dependency count, or is there another reason?

notgull commented 1 year ago

fastrand isn't really meant to be a secure RNG, just to provide a "good enough" PRNG to provide the illusion of randomness. Such as, for something like round-robin scheduling in async-executor, where it's not really of the utmost importance to have completely secure RNG, but it's still nice to have an evenly distributed number generator.

The only real factor that needs consideration is the initial seed of the generator. Using standard library hash maps we can get a decent seed from the hash of the current thread ID and the current time. Unfortunately this isn't available on WASM, hence the dependency on getrandom (so we don't have to reimplement accessing the JS random API).

I would accept a PR adding a getrandom feature for using getrandom on other targets, if that's desired.

mwcampbell commented 1 year ago

I'm sorry, I didn't study the non-wasm variant of random_seed carefully enough. I saw that it was using the standard library's default hasher, then I assumed that this was a roundabout way of using something like getrandom without adding the dependency, since I knew that the standard library hasher is usually instantiated with random state. Then I remembered that DefaultHasher::new doesn't use random state. So this makes sense now, and I have no desire to change it.