Random.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Random.h>
  7. namespace AK {
  8. u32 get_random_uniform(u32 max_bounds)
  9. {
  10. // If we try to divide all 2**32 numbers into groups of "max_bounds" numbers, we may end up
  11. // with a group around 2**32-1 that is a bit too small. For this reason, the implementation
  12. // `arc4random() % max_bounds` would be insufficient. Here we compute the last number of the
  13. // last "full group". Note that if max_bounds is a divisor of UINT32_MAX,
  14. // then we end up with UINT32_MAX:
  15. const u32 max_usable = UINT32_MAX - (static_cast<u64>(UINT32_MAX) + 1) % max_bounds;
  16. auto random_value = get_random<u32>();
  17. for (int i = 0; i < 20 && random_value > max_usable; ++i) {
  18. // By chance we picked a value from the incomplete group. Note that this group has size at
  19. // most 2**31-1, so picking this group has a chance of less than 50%.
  20. // In practice, this means that for the worst possible input, there is still only a
  21. // once-in-a-million chance to get to iteration 20. In theory we should be able to loop
  22. // forever. Here we prefer marginally imperfect random numbers over weird runtime behavior.
  23. random_value = get_random<u32>();
  24. }
  25. return random_value % max_bounds;
  26. }
  27. }