Skip to content

Commit c3199f5

Browse files
committed
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>
1 parent 34d4dab commit c3199f5

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

extmod/modurandom.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,12 @@ STATIC uint32_t yasmarang_randbelow(uint32_t n) {
8787

8888
STATIC mp_obj_t mod_urandom_getrandbits(mp_obj_t num_in) {
8989
int n = mp_obj_get_int(num_in);
90-
if (n > 32 || n == 0) {
90+
if (n > 32 || n < 0) {
9191
mp_raise_ValueError(MP_ERROR_TEXT("bits must be 32 or less"));
9292
}
93+
if (n == 0) {
94+
return MP_OBJ_NEW_SMALL_INT(0);
95+
}
9396
uint32_t mask = ~0;
9497
// Beware of C undefined behavior when shifting by >= than bit size
9598
mask >>= (32 - n);

tests/extmod/urandom_basic.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,11 @@
2222
random.seed(1)
2323
print(random.getrandbits(16) == r)
2424

25-
# check that it throws an error for zero bits
25+
# check that zero bits works
26+
print(random.getrandbits(0))
27+
28+
# check that it throws an error for negative bits
2629
try:
27-
random.getrandbits(0)
30+
random.getrandbits(-1)
2831
except ValueError:
2932
print("ValueError")

tests/extmod/urandom_basic.py.exp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
True
2+
True
3+
0
4+
ValueError

0 commit comments

Comments
 (0)