Skip to content

Instantly share code, notes, and snippets.

@angelfor3v3r
Last active November 6, 2019 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angelfor3v3r/ecbecec5f4fd511f1ca6c775c2f7066a to your computer and use it in GitHub Desktop.
Save angelfor3v3r/ecbecec5f4fd511f1ca6c775c2f7066a to your computer and use it in GitHub Desktop.
MSVC C++17 run-time pseudo-random number generation using MT19937 (requires a somewhat modern CPU)
/*
MIT License
Copyright (c) 2019 angelfor3v3r
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
// usage examples //
// any uint32_t
const auto foo = Rand::get< uint32_t >();
// uint32_t in bounds [0..100]
const auto bar = Rand::get< uint32_t >( 0, 100 );
// int32_t in bounds [-1000..1000]
const auto baz = Rand::get< int32_t >( -1000, 1000 );
*/
#pragma once
/* include defs */
#ifndef NOMINMAX
#define NOMINMAX
#endif
/* includes */
#include <intrin.h>
#include <cstdint>
#include <type_traits>
#include <array>
#include <vector>
#include <optional>
#include <random>
#include <atomic>
#include <mutex>
#undef NOMINMAX
/* Rand implementation */
namespace Rand
{
/* PRNG implementation details */
namespace Impl
{
/* implementation utils */
// true if T is in Ts
template< class T, class... Ts > inline constexpr bool is_any_of =
std::disjunction_v< std::is_same< T, Ts >... >;
// true if T is allowed in std::uniform_int_distribution
template< class T > inline constexpr bool is_uniform_int_type =
is_any_of< T, short,
int,
long,
long long,
unsigned short,
unsigned int,
unsigned long,
unsigned long long >;
// always false for Ts...
template< class... Ts > inline constexpr bool always_false = false;
// returns the mutex used for our PRNG engine
static __declspec( noinline ) std::mutex &get_lock() noexcept
{
static std::mutex ret;
return ret;
}
}
/* utils */
// check if the CPU supports RDSEED
static __declspec( noinline ) bool is_rdseed_supported() noexcept
{
static std::atomic_bool once = false;
static std::atomic_bool ret = false;
if( !once )
{
std::array< int, 4 > regs;
// get info about the CPU
__cpuidex( regs.data(), 7, 0 );
// according to intel manual (Vol. 1, 7.3.17.2):
// "CPUID.(EAX=07H, ECX=0H):EBX.RDSEED[bit 18] = 1"
if( ( regs[ 1 ] & ( 1 << 18 ) ) )
ret = true;
once = true;
}
return ret;
}
// generates a 32-bit random seed
static __declspec( noinline ) std::optional< uint32_t > get_seed_32( uint8_t retries = 32 ) noexcept
{
if( !is_rdseed_supported() )
return {};
// must run the loop at least once
retries = std::max< uint8_t >( 1, retries );
// try to generate a seed
// this must be done since RDSEED isn't always guaranteed to generate a seed
for( auto i = retries; i--; )
{
if( uint32_t seed; _rdseed32_step( &seed ) )
return seed;
}
return {};
}
// returns the current mt19937 engine
static __declspec( noinline ) std::mt19937 &get_rng_engine() noexcept
{
static std::atomic_bool once = false;
static std::mt19937 mt;
if( !once )
{
// CPU doesn't support RDSEED, fallback to default seed
if( !is_rdseed_supported() )
mt.seed( mt.default_seed );
// CPU supports RDSEED, seed normally
else
{
std::vector< std::mt19937::result_type > seeds;
// pre-allocate enough froom for seeds
seeds.reserve( mt.state_size );
// generate the amount of seeds we need
while( seeds.size() < mt.state_size )
{
// try to add a new seed to our vector
if( const auto seed = get_seed_32() )
seeds.push_back( *seed );
}
// generate seed sequence
std::seed_seq seq( seeds.begin(), seeds.end() );
// seed PRNG
mt.seed( seq );
}
once = true;
}
return mt;
}
/* run-time PRNG using Mersenne Twister */
// bad type for get, should never call this
template< class T, std::enable_if_t< !Impl::is_uniform_int_type< T >, int > = 0 >
[[ noreturn ]] inline constexpr T get( [[ maybe_unused ]] T min = { 0 }, [[ maybe_unused ]] T max = { 0 } ) noexcept
{
// tell user
static_assert( Impl::always_false< T >,
"invalid template argument for Rand::get: requires one of "
"short, int, long, long long, unsigned short, unsigned int, unsigned long, unsigned long long"
);
}
// generate random uniform int in range
template< class T, std::enable_if_t< Impl::is_uniform_int_type< T >, int > = 0 >
static __declspec( noinline ) T get( T min = 0, T max = std::numeric_limits< T >::max() ) noexcept
{
std::lock_guard< std::mutex > guard( Impl::get_lock() );
std::uniform_int_distribution< T > dist( min, max );
return dist( get_rng_engine() );
}
} // namespaced Rand
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment