11/* -----------------------------------------------------------------------------------------------
22The MIT License (MIT)
33
4- Copyright (c) 2014-2024 Kim Kulling
4+ Copyright (c) 2014-2025 Kim Kulling
55
66Permission is hereby granted, free of charge, to any person obtaining a copy of
77this software and associated documentation files (the "Software"), to deal in
@@ -28,21 +28,29 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2828
2929namespace cppcore {
3030
31- static const unsigned int N = 624 ;
32- static const unsigned int M = 397 ;
31+ static constexpr unsigned int N = 624 ;
32+ static constexpr unsigned int M = 397 ;
3333
34- static void mersenne_twister_vector_init ( unsigned int *seedPoints, size_t len ) {
35- assert ( nullptr != seedPoints );
34+ static bool mersenne_twister_vector_init ( unsigned int *seedPoints, size_t len ) {
35+ if (seedPoints == nullptr ) {
36+ return false ;
37+ }
3638
3739 const unsigned int mult = 1812433253ul ;
3840 unsigned int seed = 5489ul ;
3941 for (size_t i = 0 ; i < len; ++i) {
4042 seedPoints[ i ] = seed;
4143 seed = mult * (seed ^ (seed >> 30 )) + (static_cast <unsigned int >(i) + 1 );
4244 }
45+
46+ return true ;
4347}
4448
45- static void mersenne_twister_vector_update (unsigned int * const p) {
49+ static bool mersenne_twister_vector_update (unsigned int * const p) {
50+ if (p == nullptr ) {
51+ return false ;
52+ }
53+
4654 static const unsigned int A[ 2 ] = { 0 , 0x9908B0DF };
4755 unsigned int i=0 ;
4856 for (; i < N - M; i++) {
@@ -52,6 +60,8 @@ static void mersenne_twister_vector_update(unsigned int* const p) {
5260 p[i] = p[i + (M - N)] ^ (((p[i] & 0x80000000 ) | (p[i + 1 ] & 0x7FFFFFFF )) >> 1 ) ^ A[p[i + 1 ] & 1 ];
5361 }
5462 p[N - 1 ] = p[M - 1 ] ^ (((p[N - 1 ] & 0x80000000 ) | (p[0 ] & 0x7FFFFFFF )) >> 1 ) ^ A[p[0 ] & 1 ];
63+
64+ return true ;
5565}
5666
5767unsigned int mersenne_twister () {
@@ -60,13 +70,15 @@ unsigned int mersenne_twister() {
6070 // readout index
6171 static int idx = N + 1 ;
6272
73+ bool ok = true ;
6374 if (static_cast <unsigned int >(idx) >= N) {
6475 if (static_cast <unsigned int >(idx) > N) {
65- mersenne_twister_vector_init (vector, N);
76+ ok |= mersenne_twister_vector_init (vector, N);
6677 }
67- mersenne_twister_vector_update (vector);
78+ ok |= mersenne_twister_vector_update (vector);
6879 idx = 0 ;
6980 }
81+ assert (ok);
7082 unsigned int e = vector[ idx++ ];
7183
7284 // Tempering
@@ -80,7 +92,7 @@ unsigned int mersenne_twister() {
8092
8193RandomGenerator::RandomGenerator ( GeneratorType type ) noexcept :
8294 m_type ( type ) {
83- ::srand ( static_cast <unsigned int >(time(nullptr )));
95+ ::srand (static_cast <unsigned int >(time(nullptr )));
8496}
8597
8698int RandomGenerator::get ( int lower, int upper ) {
0 commit comments