mirror of https://github.com/aria2/aria2
SimpleRandmizer: Fix certain bits generated by getRandomBytes are always 0
This is because in Linux RAND_MAX is 2**31-1 and we used int32_t to hold random number from random() and got each bytes. This means that highest bit is always unset. In little endian system, every 4n-th (n >=0) byte has highest bit is unset. To fix this, we just use lower 2 bytes of random().pull/135/merge
parent
ac996737e5
commit
7f18494a8c
|
@ -123,11 +123,12 @@ void SimpleRandomizer::getRandomBytes(unsigned char *buf, size_t len)
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
while (len) {
|
while (len) {
|
||||||
|
// If RAND_MAX is less than 2**16-1, we are in trouble.
|
||||||
union {
|
union {
|
||||||
int32_t r;
|
uint16_t r;
|
||||||
uint8_t b[4];
|
uint8_t b[2];
|
||||||
} r = { (int32_t)random() };
|
} r = { (uint16_t)(random() & 0xffffu) };
|
||||||
for (auto i = 0; i < 4 && len; ++i, --len) {
|
for (auto i = 0; i < 2 && len; ++i, --len) {
|
||||||
*buf++ = r.b[i];
|
*buf++ = r.b[i];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue