k_system_control.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <random>
  5. #include "core/hle/kernel/k_system_control.h"
  6. namespace Kernel {
  7. namespace {
  8. template <typename F>
  9. u64 GenerateUniformRange(u64 min, u64 max, F f) {
  10. // Handle the case where the difference is too large to represent.
  11. if (max == std::numeric_limits<u64>::max() && min == std::numeric_limits<u64>::min()) {
  12. return f();
  13. }
  14. // Iterate until we get a value in range.
  15. const u64 range_size = ((max + 1) - min);
  16. const u64 effective_max = (std::numeric_limits<u64>::max() / range_size) * range_size;
  17. while (true) {
  18. if (const u64 rnd = f(); rnd < effective_max) {
  19. return min + (rnd % range_size);
  20. }
  21. }
  22. }
  23. } // Anonymous namespace
  24. u64 KSystemControl::GenerateRandomU64() {
  25. static std::random_device device;
  26. static std::mt19937 gen(device());
  27. static std::uniform_int_distribution<u64> distribution(1, std::numeric_limits<u64>::max());
  28. return distribution(gen);
  29. }
  30. u64 KSystemControl::GenerateRandomRange(u64 min, u64 max) {
  31. return GenerateUniformRange(min, max, GenerateRandomU64);
  32. }
  33. } // namespace Kernel