From 1ff63f3479389f977156048ba436a5e8f0990a0d Mon Sep 17 00:00:00 2001 From: Reece Date: Tue, 13 Jul 2021 13:09:10 +0100 Subject: [PATCH] [+] Added stub for fast rng [*] Fixed RNG strings may contain a null byte [+] Added RngByte, RngArray, RngBoolean --- Include/Aurora/RNG/RNG.hpp | 57 ++++++++++++++++++++++++++++++++------ Source/RNG/RNG.cpp | 6 ++++ 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/Include/Aurora/RNG/RNG.hpp b/Include/Aurora/RNG/RNG.hpp index fff1ea31..9f10f4a1 100644 --- a/Include/Aurora/RNG/RNG.hpp +++ b/Include/Aurora/RNG/RNG.hpp @@ -10,17 +10,32 @@ namespace Aurora::RNG { AUKN_SYM void ReadSecureRNG(void *in, AuUInt length); - - template + AUKN_SYM void ReadFastRNG(void *in, AuUInt length); + + template void Read(T(&array)[N]) { - ReadSecureRNG(array, N * sizeof(T)); + if constexpr (fast) + { + ReadFastRNG(array, N * sizeof(T)); + } + else + { + ReadSecureRNG(array, N * sizeof(T)); + } } - template + template void Read(T *array, AuUInt length) { - ReadSecureRNG(array, length * sizeof(T)); + if constexpr (fast) + { + ReadFastRNG(array, length * sizeof(T)); + } + else + { + ReadSecureRNG(array, length * sizeof(T)); + } } enum class RngStringCharacters @@ -28,12 +43,12 @@ namespace Aurora::RNG eAlphaCharacters, eAlphaNumericCharacters, eExtendedEntropy, - MAX + eCount }; static void RngString(char *string, AuUInt length, RngStringCharacters type = RngStringCharacters::eAlphaCharacters) { - static std::pair rngSequence[static_cast(RngStringCharacters::MAX)] = + static std::pair rngSequence[static_cast(RngStringCharacters::eCount)] = { {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 52}, {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 62}, @@ -46,8 +61,34 @@ namespace Aurora::RNG for (auto i = 0; i < length; i++) { - auto idx = static_cast(reinterpret_cast(string)[i]) / 255.f * static_cast(pair.second); + auto idx = std::floor(static_cast(reinterpret_cast(string)[i]) / 255.f * static_cast(pair.second - 1)); string[i] = pair.first[static_cast(idx)]; } } + + static bool RngBoolean() + { + AuUInt8 x[1]; + Read(x); + return x[0] > 127; + } + + static AuUInt8 RngByte() + { + AuUInt8 x[1]; + Read(x); + return x[0]; + } + + template + static T &RngArray(T *items, AuUInt count) + { + return items[static_cast(std::floor(static_cast(RngByte()) / 255.f * static_cast(count - 1))]; + } + + template + static T &RngVector(const AuList &items) + { + return RngArray(items.data(), items.size()); + } } \ No newline at end of file diff --git a/Source/RNG/RNG.cpp b/Source/RNG/RNG.cpp index d6b91669..f0e39d20 100644 --- a/Source/RNG/RNG.cpp +++ b/Source/RNG/RNG.cpp @@ -173,6 +173,12 @@ namespace Aurora::RNG SysAssertExp(bytes == length, "Couldn't consume {} RNG bytes", length); } + AUKN_SYM void ReadFastRNG(void *in, AuUInt length) + { + // TODO: implement me + return ReadSecureRNG(in, length); + } + void Init() { InitRandPlatform();