AuroraRuntime/Include/Aurora/RNG/RNG.hpp

92 lines
2.4 KiB
C++
Raw Normal View History

2021-06-27 21:25:29 +00:00
/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: RNG.hpp
Date: 2021-6-10
Author: Reece
***/
#pragma once
namespace Aurora::RNG
{
AUKN_SYM void ReadSecureRNG(void *in, AuUInt length);
AUKN_SYM void ReadFastRNG(void *in, AuUInt length);
template<bool fast = true, typename T, int N>
static inline void Read(T(&array)[N])
2021-06-27 21:25:29 +00:00
{
if constexpr (fast)
{
ReadFastRNG(array, N * sizeof(T));
}
else
{
ReadSecureRNG(array, N * sizeof(T));
}
2021-06-27 21:25:29 +00:00
}
template<bool fast = true, typename T>
static inline void Read(T *array, AuUInt length)
2021-06-27 21:25:29 +00:00
{
if constexpr (fast)
{
ReadFastRNG(array, length * sizeof(T));
}
else
{
ReadSecureRNG(array, length * sizeof(T));
}
2021-06-27 21:25:29 +00:00
}
enum class RngStringCharacters
{
eAlphaCharacters,
eAlphaNumericCharacters,
eExtendedEntropy,
eCount
2021-06-27 21:25:29 +00:00
};
static void RngString(char *string, AuUInt length, RngStringCharacters type = RngStringCharacters::eAlphaCharacters)
{
static std::pair<const char *, int> rngSequence[static_cast<int>(RngStringCharacters::eCount)] =
2021-06-27 21:25:29 +00:00
{
{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 52},
{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 62},
{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890=-+!$%^*.[];:", 75}
};
ReadSecureRNG(string, length);
const auto &pair = rngSequence[static_cast<int>(type)];
for (auto i = 0; i < length; i++)
{
auto idx = std::floor(static_cast<float>(reinterpret_cast<AuUInt8 *>(string)[i]) / 255.f * static_cast<float>(pair.second - 1));
2021-06-27 21:25:29 +00:00
string[i] = pair.first[static_cast<int>(idx)];
}
}
2021-07-13 12:13:21 +00:00
static inline AuUInt8 RngByte()
{
AuUInt8 x[1];
Read<true>(x);
return x[0];
}
2021-07-13 12:13:21 +00:00
static inline bool RngBoolean()
{
return RngByte() > 127;
}
template<typename T>
2021-07-13 12:13:21 +00:00
static inline T &RngArray(T *items, AuUInt count)
{
2021-07-13 12:16:40 +00:00
return items[static_cast<int>(std::floor(static_cast<float>(RngByte()) / 255.f * static_cast<float>(count - 1)))];
}
template<typename T>
2021-07-13 12:13:21 +00:00
static inline T &RngVector(const AuList<T> &items)
{
return RngArray(items.data(), items.size());
}
2021-06-27 21:25:29 +00:00
}