2021-05-14 15:16:06 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2021, the SerenityOS developers.
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <AK/Random.h>
|
2023-12-30 15:23:59 +00:00
|
|
|
#include <AK/UFixedBigInt.h>
|
|
|
|
#include <AK/UFixedBigIntDivision.h>
|
2021-05-14 15:16:06 +00:00
|
|
|
|
|
|
|
namespace AK {
|
|
|
|
|
|
|
|
u32 get_random_uniform(u32 max_bounds)
|
|
|
|
{
|
|
|
|
// If we try to divide all 2**32 numbers into groups of "max_bounds" numbers, we may end up
|
|
|
|
// with a group around 2**32-1 that is a bit too small. For this reason, the implementation
|
|
|
|
// `arc4random() % max_bounds` would be insufficient. Here we compute the last number of the
|
|
|
|
// last "full group". Note that if max_bounds is a divisor of UINT32_MAX,
|
|
|
|
// then we end up with UINT32_MAX:
|
2024-04-18 19:32:56 +00:00
|
|
|
u32 const max_usable = UINT32_MAX - (static_cast<u64>(UINT32_MAX) + 1) % max_bounds;
|
2021-05-14 15:16:06 +00:00
|
|
|
auto random_value = get_random<u32>();
|
|
|
|
for (int i = 0; i < 20 && random_value > max_usable; ++i) {
|
|
|
|
// By chance we picked a value from the incomplete group. Note that this group has size at
|
|
|
|
// most 2**31-1, so picking this group has a chance of less than 50%.
|
|
|
|
// In practice, this means that for the worst possible input, there is still only a
|
|
|
|
// once-in-a-million chance to get to iteration 20. In theory we should be able to loop
|
|
|
|
// forever. Here we prefer marginally imperfect random numbers over weird runtime behavior.
|
|
|
|
random_value = get_random<u32>();
|
|
|
|
}
|
|
|
|
return random_value % max_bounds;
|
|
|
|
}
|
|
|
|
|
2023-12-30 15:23:59 +00:00
|
|
|
u64 get_random_uniform_64(u64 max_bounds)
|
|
|
|
{
|
|
|
|
// Uses the same algorithm as `get_random_uniform`,
|
|
|
|
// by replacing u64 with u128 and u32 with u64.
|
2024-04-18 19:32:56 +00:00
|
|
|
u64 const max_usable = UINT64_MAX - static_cast<u64>((static_cast<u128>(UINT64_MAX) + 1) % max_bounds);
|
2023-12-30 15:23:59 +00:00
|
|
|
auto random_value = get_random<u64>();
|
|
|
|
for (int i = 0; i < 20 && random_value > max_usable; ++i) {
|
|
|
|
random_value = get_random<u64>();
|
|
|
|
}
|
|
|
|
return random_value % max_bounds;
|
|
|
|
}
|
|
|
|
|
2021-05-14 15:16:06 +00:00
|
|
|
}
|