stdlib: Simplify arc4random_uniform
commitc622ac1b8662908b595ec1a19e401ad6a629f52c
authorAdhemerval Zanella <adhemerval.zanella@linaro.org>
Thu, 28 Jul 2022 12:18:01 +0000 (28 09:18 -0300)
committerAdhemerval Zanella <adhemerval.zanella@linaro.org>
Mon, 1 Aug 2022 17:37:24 +0000 (1 14:37 -0300)
tree3f45901eabfdbcb7688b68d22f8cf55d07eaf4c1
parent7187efd0aa270c83c428ea6cd0e1cffc34b41a74
stdlib: Simplify arc4random_uniform

It uses the bitmask with rejection [1], which calculates a mask
being the lowest power of two bounding the request upper bound,
successively queries new random values, and rejects values
outside the requested range.

Performance-wise, there is no much gain in trying to conserve
bits since arc4random is wrapper on getrandom syscall.  It should
be cheaper to just query a uint32_t value.  The algorithm also
avoids modulo and divide operations, which might be costly
depending of the architecture.

[1] https://www.pcg-random.org/posts/bounded-rands.html

Reviewed-by: Yann Droneaud <ydroneaud@opteya.com>
stdlib/arc4random_uniform.c