2018-05-21 13:48:17 +00:00
|
|
|
// Copyright 2018 Dolphin Emulator Project
|
|
|
|
// Licensed under GPLv2+
|
|
|
|
// Refer to the license.txt file included.
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <cstddef>
|
2021-01-13 13:54:19 +00:00
|
|
|
#include <memory>
|
2018-06-14 14:26:11 +00:00
|
|
|
#include <type_traits>
|
2018-05-21 13:48:17 +00:00
|
|
|
|
|
|
|
#include "Common/CommonTypes.h"
|
|
|
|
|
|
|
|
namespace Common::Random
|
|
|
|
{
|
2021-01-13 13:54:19 +00:00
|
|
|
/// Cryptographically secure pseudo-random number generator, with explicit seed.
|
|
|
|
class PRNG final
|
|
|
|
{
|
|
|
|
public:
|
|
|
|
explicit PRNG(u64 seed) : PRNG(&seed, sizeof(u64)) {}
|
|
|
|
PRNG(void* seed, std::size_t size);
|
|
|
|
~PRNG();
|
|
|
|
|
|
|
|
void Generate(void* buffer, std::size_t size);
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
T GenerateValue()
|
|
|
|
{
|
|
|
|
static_assert(std::is_arithmetic<T>(), "T must be an arithmetic type in GenerateValue.");
|
|
|
|
T value;
|
|
|
|
Generate(&value, sizeof(value));
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
struct Impl;
|
|
|
|
std::unique_ptr<Impl> m_impl;
|
|
|
|
};
|
|
|
|
|
2018-05-21 13:48:17 +00:00
|
|
|
/// Fill `buffer` with random bytes using a cryptographically secure pseudo-random number generator.
|
|
|
|
void Generate(void* buffer, std::size_t size);
|
2018-06-14 14:26:11 +00:00
|
|
|
|
|
|
|
/// Generates a random value of arithmetic type `T`
|
|
|
|
template <typename T>
|
|
|
|
T GenerateValue()
|
|
|
|
{
|
|
|
|
static_assert(std::is_arithmetic<T>(), "T must be an arithmetic type in GenerateValue.");
|
|
|
|
T value;
|
|
|
|
Generate(&value, sizeof(value));
|
|
|
|
return value;
|
|
|
|
}
|
2018-05-21 13:48:17 +00:00
|
|
|
} // namespace Common::Random
|