Skip to content

Commit 94b2ead

Browse files
sipaFuzzbawls
authored andcommitted
Make FastRandomContext support standard C++11 RNG interface
This makes it possible to plug it into the various standard C++11 random distribution algorithms and other functions like std::shuffle.
1 parent 75ed795 commit 94b2ead

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/random.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include "uint256.h"
1313

1414
#include <stdint.h>
15+
#include <limits>
1516

1617
/* Seed OpenSSL PRNG with additional entropy data */
1718
void RandAddSeed();
@@ -130,6 +131,12 @@ class FastRandomContext {
130131

131132
/** Generate a random boolean. */
132133
bool randbool() { return randbits(1); }
134+
135+
// Compatibility with the C++11 UniformRandomBitGenerator concept
136+
typedef uint64_t result_type;
137+
static constexpr uint64_t min() { return 0; }
138+
static constexpr uint64_t max() { return std::numeric_limits<uint64_t>::max(); }
139+
inline uint64_t operator()() { return rand64(); }
133140
};
134141

135142
/* Number of random bytes returned by GetOSRand.

src/test/random_tests.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88

99
#include <boost/test/unit_test.hpp>
1010

11+
#include <random>
12+
#include <algorithm>
13+
1114
BOOST_FIXTURE_TEST_SUITE(random_tests, BasicTestingSetup)
1215

1316
BOOST_AUTO_TEST_CASE(osrandom_tests)
@@ -64,4 +67,23 @@ BOOST_AUTO_TEST_CASE(fastrandom_randbits)
6467
}
6568
}
6669

70+
/** Does-it-compile test for compatibility with standard C++11 RNG interface. */
71+
BOOST_AUTO_TEST_CASE(stdrandom_test)
72+
{
73+
FastRandomContext ctx;
74+
std::uniform_int_distribution<int> distribution(3, 9);
75+
for (int i = 0; i < 100; ++i) {
76+
int x = distribution(ctx);
77+
BOOST_CHECK(x >= 3);
78+
BOOST_CHECK(x <= 9);
79+
80+
std::vector<int> test{1,2,3,4,5,6,7,8,9,10};
81+
std::shuffle(test.begin(), test.end(), ctx);
82+
for (int j = 1; j <= 10; ++j) {
83+
BOOST_CHECK(std::find(test.begin(), test.end(), j) != test.end());
84+
}
85+
}
86+
87+
}
88+
6789
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)