Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 34k
bpo-40286: Makes simpler the relation between randbytes() and getrandbits()#19574
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
Changes from all commits
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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); | ||
Member There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It looks like this will give different results on big-endian and little-endian platforms, no? MemberAuthor There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
| ||
| break; | ||
| } | ||
| memcpy(ptr, &word, 4); | ||
| ptr += 4; | ||
| n -= 4; | ||
| } while (n); | ||
| } | ||
| return bytes; | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just a matter of taste, but personally I would move this epilog out of the loop and change the loop condition to
n >= 4.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Then you would need to repeat the following 5 lines: