random.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #include "base/random.h"
  8. extern "C" {
  9. #include <openssl/rand.h>
  10. } // extern "C"
  11. namespace base {
  12. namespace {
  13. template <typename Next>
  14. int RandomIndex(int count, Next &&next) {
  15. Expects(count > 0);
  16. if (count == 1) {
  17. return 0;
  18. }
  19. const auto max = (std::numeric_limits<uint32>::max() / count) * count;
  20. while (true) {
  21. const auto random = next();
  22. if (random < max) {
  23. return int(random % count);
  24. }
  25. }
  26. }
  27. } // namespace
  28. void RandomFill(bytes::span bytes) {
  29. const auto result = RAND_bytes(
  30. reinterpret_cast<unsigned char*>(bytes.data()),
  31. bytes.size());
  32. Ensures(result);
  33. }
  34. int RandomIndex(int count) {
  35. return RandomIndex(count, [] { return RandomValue<uint32>(); });
  36. }
  37. int RandomIndex(int count, BufferedRandom<uint32> buffered) {
  38. return RandomIndex(count, [&] { return buffered.next(); });
  39. }
  40. void RandomAddSeed(bytes::const_span bytes) {
  41. RAND_seed(bytes.data(), bytes.size());
  42. }
  43. } // namespace base