Skip to content

Commit 1ec1602

Browse files
committed
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 4ba3d4f commit 1ec1602

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
@@ -11,6 +11,7 @@
1111
#include <uint256.h>
1212

1313
#include <stdint.h>
14+
#include <limits>
1415

1516
/* Seed OpenSSL PRNG with additional entropy data */
1617
void RandAddSeed();
@@ -121,6 +122,12 @@ class FastRandomContext {
121122

122123
/** Generate a random boolean. */
123124
bool randbool() { return randbits(1); }
125+
126+
// Compatibility with the C++11 UniformRandomBitGenerator concept
127+
typedef uint64_t result_type;
128+
static constexpr uint64_t min() { return 0; }
129+
static constexpr uint64_t max() { return std::numeric_limits<uint64_t>::max(); }
130+
inline uint64_t operator()() { return rand64(); }
124131
};
125132

126133
/* 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)
@@ -57,4 +60,23 @@ BOOST_AUTO_TEST_CASE(fastrandom_randbits)
5760
}
5861
}
5962

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

0 commit comments

Comments
 (0)