diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2020-04-17 20:51:28 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-17 20:51:28 (GMT) |
commit | 223221b290db00ca1042c77103efcbc072f29c90 (patch) | |
tree | 199bb4c0de90ab39ee03500b83b8c312250895cb /Modules | |
parent | 5b1d9184bb0e34391637c06bc7651fb6de8a6240 (diff) | |
download | cpython-223221b290db00ca1042c77103efcbc072f29c90.zip cpython-223221b290db00ca1042c77103efcbc072f29c90.tar.gz cpython-223221b290db00ca1042c77103efcbc072f29c90.tar.bz2 |
bpo-40286: Makes simpler the relation between randbytes() and getrandbits() (GH-19574)
Diffstat (limited to 'Modules')
-rw-r--r-- | Modules/_randommodule.c | 18 |
1 files changed, 6 insertions, 12 deletions
diff --git a/Modules/_randommodule.c b/Modules/_randommodule.c index 64e44e3..0fc2d07 100644 --- a/Modules/_randommodule.c +++ b/Modules/_randommodule.c @@ -534,31 +534,25 @@ _random_Random_randbytes_impl(RandomObject *self, Py_ssize_t n) return NULL; } - if (n == 0) { - /* Don't consume any entropy */ - return PyBytes_FromStringAndSize(NULL, 0); - } - PyObject *bytes = PyBytes_FromStringAndSize(NULL, n); if (bytes == NULL) { return NULL; } uint8_t *ptr = (uint8_t *)PyBytes_AS_STRING(bytes); - do { + for (; n; ptr += 4, n -= 4) { uint32_t word = genrand_uint32(self); -#if PY_LITTLE_ENDIAN - /* Convert to big endian */ +#if PY_BIG_ENDIAN + /* Convert to little endian */ word = _Py_bswap32(word); #endif if (n < 4) { - memcpy(ptr, &word, n); + /* Drop least significant bits */ + memcpy(ptr, (uint8_t *)&word + (4 - n), n); break; } memcpy(ptr, &word, 4); - ptr += 4; - n -= 4; - } while (n); + } return bytes; } |