Add a FastRandomContext::randrange and use it

This commit is contained in:
Pieter Wuille
2017-02-25 12:16:58 -08:00
parent 16329224e7
commit 4fd2d2fc97
7 changed files with 75 additions and 2 deletions

View File

@@ -7,6 +7,7 @@
#define BITCOIN_RANDOM_H
#include "crypto/chacha20.h"
#include "crypto/common.h"
#include "uint256.h"
#include <stdint.h>
@@ -91,6 +92,17 @@ public:
}
}
/** Generate a random integer in the range [0..range). */
uint64_t randrange(uint64_t range)
{
--range;
int bits = CountBits(range);
while (true) {
uint64_t ret = randbits(bits);
if (ret <= range) return ret;
}
}
/** Generate a random 32-bit integer. */
uint32_t rand32() { return randbits(32); }