extmod/modurandom: Support an argument of bits=0 to getrandbits.

This was changed in CPython 3.9; see https://bugs.python.org/issue40282.

Signed-off-by: Damien George <damien@micropython.org>
This commit is contained in:
Damien George 2021-05-30 16:52:08 +10:00
parent 34d4dab683
commit c3199f5649
3 changed files with 13 additions and 3 deletions

View File

@ -87,9 +87,12 @@ STATIC uint32_t yasmarang_randbelow(uint32_t n) {
STATIC mp_obj_t mod_urandom_getrandbits(mp_obj_t num_in) { STATIC mp_obj_t mod_urandom_getrandbits(mp_obj_t num_in) {
int n = mp_obj_get_int(num_in); int n = mp_obj_get_int(num_in);
if (n > 32 || n == 0) { if (n > 32 || n < 0) {
mp_raise_ValueError(MP_ERROR_TEXT("bits must be 32 or less")); mp_raise_ValueError(MP_ERROR_TEXT("bits must be 32 or less"));
} }
if (n == 0) {
return MP_OBJ_NEW_SMALL_INT(0);
}
uint32_t mask = ~0; uint32_t mask = ~0;
// Beware of C undefined behavior when shifting by >= than bit size // Beware of C undefined behavior when shifting by >= than bit size
mask >>= (32 - n); mask >>= (32 - n);

View File

@ -22,8 +22,11 @@ r = random.getrandbits(16)
random.seed(1) random.seed(1)
print(random.getrandbits(16) == r) print(random.getrandbits(16) == r)
# check that it throws an error for zero bits # check that zero bits works
print(random.getrandbits(0))
# check that it throws an error for negative bits
try: try:
random.getrandbits(0) random.getrandbits(-1)
except ValueError: except ValueError:
print("ValueError") print("ValueError")

View File

@ -0,0 +1,4 @@
True
True
0
ValueError