Changeset View
Changeset View
Standalone View
Standalone View
src/random.h
Show First 20 Lines • Show All 131 Lines • ▼ Show 20 Lines | public: | ||||
static constexpr uint64_t min() { return 0; } | static constexpr uint64_t min() { return 0; } | ||||
static constexpr uint64_t max() { | static constexpr uint64_t max() { | ||||
return std::numeric_limits<uint64_t>::max(); | return std::numeric_limits<uint64_t>::max(); | ||||
} | } | ||||
inline uint64_t operator()() { return rand64(); } | inline uint64_t operator()() { return rand64(); } | ||||
}; | }; | ||||
/** | /** | ||||
* More efficient than using std::shuffle on a FastRandomContext. | |||||
* | |||||
* This is more efficient as std::shuffle will consume entropy in groups of | |||||
* 64 bits at the time and throw away most. | |||||
* | |||||
* This also works around a bug in libstdc++ std::shuffle that may cause | |||||
* type::operator=(type&&) to be invoked on itself, which the library's | |||||
* debug mode detects and panics on. This is a known issue, see | |||||
* https://stackoverflow.com/questions/22915325/avoiding-self-assignment-in-stdshuffle | |||||
*/ | |||||
template <typename I, typename R> void Shuffle(I first, I last, R &&rng) { | |||||
while (first != last) { | |||||
size_t j = rng.randrange(last - first); | |||||
if (j) { | |||||
using std::swap; | |||||
swap(*first, *(first + j)); | |||||
} | |||||
++first; | |||||
} | |||||
} | |||||
/** | |||||
* Number of random bytes returned by GetOSRand. | * Number of random bytes returned by GetOSRand. | ||||
* When changing this constant make sure to change all call sites, and make sure | * When changing this constant make sure to change all call sites, and make | ||||
* that the underlying OS APIs for all platforms support the number (many cap | * sure that the underlying OS APIs for all platforms support the number. | ||||
* out at 256 bytes). | * (many cap out at 256 bytes). | ||||
*/ | */ | ||||
static const ssize_t NUM_OS_RANDOM_BYTES = 32; | static const ssize_t NUM_OS_RANDOM_BYTES = 32; | ||||
/** | /** | ||||
* Get 32 bytes of system entropy. Do not use this in application code: use | * Get 32 bytes of system entropy. Do not use this in application code: use | ||||
* GetStrongRandBytes instead. | * GetStrongRandBytes instead. | ||||
*/ | */ | ||||
void GetOSRand(uint8_t *ent32); | void GetOSRand(uint8_t *ent32); | ||||
Show All 11 Lines |