AuroraRuntime/Source/RNG/WELL.cpp
Reece cf70f0d45c [*/+/-] MEGA COMMIT. ~2 weeks compressed.
The intention is to quickly improve and add util apis, enhance functionality given current demands, go back to the build pipeline, finish that, publish runtime tests, and then use what we have to go back to to linux support with a more stable api.

[+] AuMakeSharedArray
[+] Technet ArgvQuote
[+] Grug subsystem (UNIX signal thread async safe ipc + telemetry flusher + log flusher.)
[+] auEndianness -> Endian swap utils
[+] AuGet<N>(...)
[*] AUE_DEFINE conversion for
        ECompresionType, EAnsiColor, EHashType, EStreamError, EHexDump
[+] ConsoleMessage ByteBuffer serialization
[+] CmdLine subsystem for parsing command line arguments and simple switch/flag checks
[*] Split logger from console subsystem
[+] StartupParameters -> A part of a clean up effort under Process
[*] Refactor SysErrors header + get caller hack
[+] Atomic APIs
[+] popcnt
[+] Ring Buffer sink
[+] Added more standard errors
        Catch,
        Submission,
        LockError,
        NoAccess,
        ResourceMissing,
        ResourceLocked,
        MalformedData,
        InSandboxContext,
        ParseError

[+] Added ErrorCategorySet, ErrorCategoryClear, GetStackTrace
[+] IExitSubscriber, ETriggerLevel
[*] Write bias the high performance RWLockImpl read-lock operation operation
[+] ExitHandlerAdd/ExitHandlerRemove (exit subsystem)
[*] Updated API style
        Digests
[+] CpuId::CpuBitCount
[+] GetUserProgramsFolder
[+] GetPackagePath
[*] Split IStreamReader with an inl file
[*] BlobWriter/BlobReader/BlobArbitraryReader can now take shared pointers to bytebuffers. default constructor allocates a new scalable bytebuffer
[+] ICharacterProvider
[+] ICharacterProviderEx
[+] IBufferedCharacterConsumer
[+] ProviderFromSharedString
[+] ProviderFromString
[+] BufferConsumerFromProvider
[*] Parse Subsystem uses character io bufferer
[*] Rewritten NT's high perf semaphore to use userland SRW/ConVars [like mutex, based on generic semaphore]
[+] ByteBuffer::ResetReadPointer
[*] Bug fix bytebuffer base not reset on free and some scaling issues
[+] ProcessMap -> Added kSectionNameStack, kSectionNameFile, kSectionNameHeap for Section
[*] ProcessMap -> Refactor Segment to Section. I was stupid for keeping a type conflict hack API facing
[+] Added 64 *byte* fast RNG seeds
[+] File Advisorys/File Lock Awareness
[+] Added extended IAuroraThread from OS identifier caches for debug purposes
[*] Tweaked how memory is reported on Windows. Better consistency of what values mean across functions.
[*] Broke AuroraUtils/Typedefs out into a separate library
[*] Update build script
[+] Put some more effort into adding detail to the readme before rewriting it, plus, added some media
[*] Improved public API documentation
[*] Bug fix `SetConsoleCtrlHandler`
[+] Locale TimeDateToFileNameISO8601
[+] Console config stdOutShortTime
[*] Begin using internal UTF8/16 decoders when platform support isnt available (instead of stl)
[*] Bug fixes in decoders
[*] Major bug fix, AuMax
[+] RateLimiter
[+] Binary file sink
[+] Log directory sink
[*] Data header usability (more operators)
[+] AuRemoveRange
[+] AuRemove
[+] AuTryRemove
[+] AuTryRemoveRange
[+] auCastUtils
[+] Finish NewLSWin32Source
[+] AuTryFindByTupleN, AuTryRemoveByTupleN
[+] Separated AuRead/Write types, now in auTypeUtils
[+] Added GetPosition/SetPosition to FileWriter
[*] Fix stupid AuMin in place of AuMax in SpawnThread.Unix.Cpp
[*] Refactored Arbitrary readers to SeekingReaders (as in, they could be atomic and/or parallelized, and accept an arbitrary position as a work parameter -> not Seekable, as in, you can simply set the position)
[*] Hack back in the sched deinit
[+] File AIO loop source interop
[+] Begin to prototype a LoopQueue object I had in mind for NT, untested btw
[+] Stub code for networking
[+] Compression BaseStream/IngestableStreamBase
[*] Major: read/write locks now support write-entrant read routines.
[*] Compression subsystem now uses the MemoryView concept
[*] Rewrite the base stream compressions, made them less broken
[*] Update hashing api
[*] WriterTryGoForward and ReaderTryGoForward now revert to the previous relative index instead of panicing
[+] Added new AuByteBuffer apis
    Trim, Pad, WriteFrom, WriteString, [TODO: ReadString]
[+] Added ByteBufferPushReadState
[+] Added ByteBufferPushWriteState
[*] Move from USC-16 to full UTF-16. Win32 can handle full UTF-16.
[*] ELogLevel is now an Aurora enum
[+] Raised arbitrary limit in header to 255, the max filter buffer
[+] Explicit GZip support
[+] Explicit Zip support
[+] Added [some] compressors

et al
2022-02-17 00:11:40 +00:00

150 lines
4.1 KiB
C++

/*
* Copyright (C) 2008, Chris Lomont
* 2021-2020, Rocks
* Public Domain
*
* http://lomont.org/papers/2008/Lomont_PRNG_2008.pdf
*/
#include <Source/RuntimeInternal.hpp>
#include "WELL.hpp"
#include "mtwister.hpp"
// WELL should provide us reasonably 'secure' and, more importantly, fast RNG for
// general purpose use. It isn't fundamentally broken unlike MT, I dont think 512
// or 16 samples is going to break anything unlike MT with 624 or so. WELL has
// demonstrable better statistical properties and 32-bit performance. I think it
// makes for a better defacto backend than MT. Generic xorshiftrots might be alright
// for improved speed at the cost of what little reliability PRNGs have.
// Redunced seed entropy should not matter to the extent that MT can make up for it
// WELL is used in the fast rng backend, and i feel as though it would be unreasonable
// to go above UInt64 seeds. For toy purposes, U32/64 seeds are probably fine. Treat
// WELL like MT without 624 prediction and performance issues.
static auline void WELL_SeedRand64(WELLRand *rand, AuUInt64 seed)
{
MTRand mtrand = MT_SeedRand(seed & 0xffffffff);
MTRand mtrand2 = MT_SeedRand(seed >> 32);
AuMemset(rand->state, 0, sizeof(rand->state));
// Let's mess with the entropy in case there is an attempt to reverse the base seed from
// iterations of the WELL_NextLong_Unlocked function. Variance between mtrand and mtrand2
// increases with each iteration up to a hopefully unknown value
AuUInt8 confuser = (MT_NextLong(&mtrand2) & 0xFF) / 5 + 5;
for (int z = 0; z < confuser; z++)
{
for (int i = 0; i < z; i++)
{
MT_NextLong(&mtrand);
}
for (unsigned int i = 0; i < AuArraySize(rand->state); i++)
{
rand->state[i] = MT_NextLong(&mtrand) ^ MT_NextLong(&mtrand2);
}
}
}
static auline void WELL_SeedRand(WELLRand *rand, AuUInt32 seed)
{
MTRand mtrand = MT_SeedRand(seed);
AuMemset(rand->state, 0, sizeof(rand->state));
AuUInt8 confuser = (MT_NextLong(&mtrand) & 0xFF) / 5 + 5;
for (int z = 0; z < confuser; z++)
{
for (int i = 0; i < z; i++)
{
MT_NextLong(&mtrand);
}
for (unsigned int i = 0; i < AuArraySize(rand->state); i++)
{
rand->state[i] = MT_NextLong(&mtrand);
}
}
}
/**
* Creates a new random number generator from a given seed.
*/
WELLRand WELL_SeedRand(AuUInt32 seed)
{
WELLRand rand {};
WELL_SeedRand(&rand, seed);
return rand;
}
WELLRand WELL_SeedRand64(AuUInt64 seed)
{
WELLRand rand {};
WELL_SeedRand64(&rand, seed);
return rand;
}
WELLRand WELL_SeedRandBig64(const AuArray<AuUInt8, 64> &seed)
{
WELLRand rand {};
static_assert(64 == sizeof(rand.state));
AuMemcpy(rand.state, seed.data(), sizeof(rand.state));
return rand;
}
/**
* Generates a pseudo-randomly generated long.
*/
auline AuUInt32 WELL_NextLong_Unlocked(WELLRand *rand)
{
AuUInt32 a, b, c, d, ret;
a = rand->state[rand->index];
c = rand->state[(rand->index + 13) & 15];
b = a ^ c ^ (a << 16) ^ (c << 15);
c = rand->state[(rand->index + 9) & 15];
c ^= (c >> 11);
a = rand->state[rand->index] = b ^ c;
d = a ^ ((a << 5) & 0xDA442D24UL);
rand->index = (rand->index + 15) & 15;
a = rand->state[rand->index];
rand->state[rand->index] = a ^ b ^ d ^ (a << 2) ^ (b << 18) ^ (c << 28);
ret = rand->state[rand->index];
return ret;
}
/**
* Generates a pseudo-randomly generated long.
*/
AuUInt32 WELL_NextLong(WELLRand *rand)
{
AU_LOCK_GUARD(rand->lock);
AuUInt32 ret = WELL_NextLong_Unlocked(rand);
return ret;
}
void WELL_NextBytes(WELLRand *rand, void *in, AuUInt32 length)
{
AuUInt i;
AuUInt8 *base;
i = 0;
base = reinterpret_cast<AuUInt8 *>(in);
AU_LOCK_GUARD(rand->lock);
for (; i < length; i += 4)
{
AuUInt32 rng = WELL_NextLong_Unlocked(rand);
AuMemcpy(base + i, &rng, 4);
}
if (i > length)
{
i -= 4;
AuUInt32 padRng = WELL_NextLong_Unlocked(rand);
AuMemcpy(base + i, &padRng, length - i);
}
}