diff options
| author | Damien George <damien@micropython.org> | 2021-05-30 16:52:08 +1000 |
|---|---|---|
| committer | Damien George <damien@micropython.org> | 2021-05-30 17:05:56 +1000 |
| commit | c3199f56494429ba44f7e722597945dc91f3589c (patch) | |
| tree | 0c63951475cd94dc1eabb02e37e13a9859a47c17 | |
| parent | 34d4dab683c69578b0ddd1725290529dd812b291 (diff) | |
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>
| -rw-r--r-- | extmod/modurandom.c | 5 | ||||
| -rw-r--r-- | tests/extmod/urandom_basic.py | 7 | ||||
| -rw-r--r-- | tests/extmod/urandom_basic.py.exp | 4 |
3 files changed, 13 insertions, 3 deletions
diff --git a/extmod/modurandom.c b/extmod/modurandom.c index f44510be9..21fbac694 100644 --- a/extmod/modurandom.c +++ b/extmod/modurandom.c @@ -87,9 +87,12 @@ STATIC uint32_t yasmarang_randbelow(uint32_t n) { STATIC mp_obj_t mod_urandom_getrandbits(mp_obj_t 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")); } + if (n == 0) { + return MP_OBJ_NEW_SMALL_INT(0); + } uint32_t mask = ~0; // Beware of C undefined behavior when shifting by >= than bit size mask >>= (32 - n); diff --git a/tests/extmod/urandom_basic.py b/tests/extmod/urandom_basic.py index 180197398..f7f5a6d69 100644 --- a/tests/extmod/urandom_basic.py +++ b/tests/extmod/urandom_basic.py @@ -22,8 +22,11 @@ r = random.getrandbits(16) random.seed(1) 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: - random.getrandbits(0) + random.getrandbits(-1) except ValueError: print("ValueError") diff --git a/tests/extmod/urandom_basic.py.exp b/tests/extmod/urandom_basic.py.exp new file mode 100644 index 000000000..d629828d7 --- /dev/null +++ b/tests/extmod/urandom_basic.py.exp @@ -0,0 +1,4 @@ +True +True +0 +ValueError |
