random.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. #pragma once
  8. #include <cstddef>
  9. #include <type_traits>
  10. #include "base/bytes.h"
  11. namespace base {
  12. void RandomFill(bytes::span bytes);
  13. inline void RandomFill(void *data, std::size_t length) {
  14. RandomFill({ static_cast<bytes::type*>(data), length });
  15. }
  16. template <
  17. typename T,
  18. typename = std::enable_if_t<std::is_trivially_copyable_v<T>>>
  19. [[nodiscard]] inline T RandomValue() {
  20. auto result = T();
  21. RandomFill({ reinterpret_cast<std::byte*>(&result), sizeof(T) });
  22. return result;
  23. }
  24. [[nodiscard]] int RandomIndex(int count);
  25. template <typename T>
  26. class BufferedRandom final {
  27. public:
  28. explicit BufferedRandom(int bufferSize) : _buffer(bufferSize) {
  29. Expects(bufferSize > 0);
  30. }
  31. [[nodiscard]] T next() {
  32. if (_index == _buffer.size()) {
  33. _index = 0;
  34. }
  35. if (!_index) {
  36. RandomFill(bytes::make_span(_buffer));
  37. }
  38. return _buffer[_index++];
  39. }
  40. private:
  41. std::vector<T> _buffer;
  42. int _index = 0;
  43. };
  44. [[nodiscard]] int RandomIndex(int count, BufferedRandom<uint32> buffered);
  45. void RandomAddSeed(bytes::const_span bytes);
  46. } // namespace base