mirror of
https://github.com/bitcoin/bitcoin.git
synced 2025-11-11 06:28:31 +01:00
Add a FastRandomContext::randrange and use it
This commit is contained in:
12
src/random.h
12
src/random.h
@@ -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); }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user