Skip to content

Commit e269cab

Browse files
committed
py/objint: In to_bytes(), allow length arg to be any int and check sign.
1 parent 8c5632a commit e269cab

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

py/objint.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,10 @@ STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) {
435435
// TODO: Support signed param (assumes signed=False)
436436
(void)n_args;
437437

438-
mp_uint_t len = MP_OBJ_SMALL_INT_VALUE(args[1]);
438+
mp_int_t len = mp_obj_get_int(args[1]);
439+
if (len < 0) {
440+
mp_raise_ValueError(NULL);
441+
}
439442
bool big_endian = args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little);
440443

441444
vstr_t vstr;

tests/basics/int_bytes.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,9 @@
1414
print((100).to_bytes(10, "big"))
1515
print(int.from_bytes(b"\0\0\0\0\0\0\0\0\0\x01", "big"))
1616
print(int.from_bytes(b"\x01\0", "big"))
17+
18+
# negative number of bytes should raise an error
19+
try:
20+
(1).to_bytes(-1, "little")
21+
except ValueError:
22+
print("ValueError")

0 commit comments

Comments
 (0)