/* $OpenBSD: arc4random_uniform.c,v 1.3 2019/01/20 02:59:07 bcook Exp $ */12/*3* Copyright (c) 2008, Damien Miller <[email protected]>4*5* Permission to use, copy, modify, and distribute this software for any6* purpose with or without fee is hereby granted, provided that the above7* copyright notice and this permission notice appear in all copies.8*9* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES10* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF11* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR12* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES13* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN14* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF15* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.16*/1718#include <sys/types.h>19#include <sys/libkern.h>2021/*22* Calculate a uniformly distributed random number less than upper_bound23* avoiding "modulo bias".24*25* Uniformity is achieved by generating new random numbers until the one26* returned is outside the range [0, 2**32 % upper_bound). This27* guarantees the selected random number will be inside28* [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)29* after reduction modulo upper_bound.30*/31uint32_t32arc4random_uniform(uint32_t upper_bound)33{34uint32_t r, min;3536if (upper_bound < 2)37return 0;3839/* 2**32 % x == (2**32 - x) % x */40min = -upper_bound % upper_bound;4142/*43* This could theoretically loop forever but each retry has44* p > 0.5 (worst case, usually far better) of selecting a45* number inside the range we need, so it should rarely need46* to re-roll.47*/48for (;;) {49r = arc4random();50if (r >= min)51break;52}5354return r % upper_bound;55}565758