mirror of
https://github.com/systemd/systemd-stable.git
synced 2025-01-25 06:03:40 +03:00
random-util: add random_u64_range() that acquires a random number from a certain range, unbiased
So far we have been quite sloppy with this and ignored modulus and range bias. Let's do something about, and add the option to do better.
This commit is contained in:
parent
26c59e4e95
commit
5464c96186
@ -494,3 +494,22 @@ int random_write_entropy(int fd, const void *seed, size_t size, bool credit) {
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
int random_u64_range(uint64_t m) {
|
||||
uint64_t x, remainder;
|
||||
|
||||
/* Generates a random number in the range 0…m-1, unbiased. (Java's algorithm) */
|
||||
|
||||
if (m == 0) /* Let's take m == 0 as special case to return an integer from the full range */
|
||||
return random_u64();
|
||||
if (m == 1)
|
||||
return 0;
|
||||
|
||||
remainder = UINT64_MAX % m;
|
||||
|
||||
do {
|
||||
x = random_u64();
|
||||
} while (x >= UINT64_MAX - remainder);
|
||||
|
||||
return x % m;
|
||||
}
|
||||
|
@ -40,3 +40,5 @@ int rdrand(unsigned long *ret);
|
||||
size_t random_pool_size(void);
|
||||
|
||||
int random_write_entropy(int fd, const void *seed, size_t size, bool credit);
|
||||
|
||||
int random_u64_range(uint64_t max);
|
||||
|
Loading…
x
Reference in New Issue
Block a user