Daniel Lemire has published a more efficient range reduction algorithm
for finding a random number in a given range without bias:
https://arxiv.org/pdf/1805.10941
This algorithm is already in use by the Go standard library:
https://cs.opensource.google/go/go/+/refs/tags/go1.23.3:src/math/rand/rand.go;l=161
Reimplement arc4random_uniform using this method.
A microbenchmark shows that performance is improved by around 22% on my Haswell box:
os: FreeBSD arch: amd64 cpu: Intel(R) Core(TM) i7-4910MQ CPU @ 2.90GHz │ benchmark.out │ │ sec/op │ Arc4random_uniform 56.53n ± 0% Fast_uniform 44.00n ± 0% geomean 49.87n
A new unit test is added to validate that the range reduction works correctly.
We cannot currently validate that there is no bias however.
The paper is referenced in arc4random(3).