Skip to content

Commit

Permalink
py/objint: Allow int() to parse anything with the buffer protocol.
Browse files Browse the repository at this point in the history
This generalises and simplifies the code and follows CPython behaviour.

See similar change for floats in a07fc5b.

Signed-off-by: Damien George <damien@micropython.org>
  • Loading branch information
dpgeorge committed Jun 1, 2023
1 parent 66dc139 commit 69dd013
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
9 changes: 4 additions & 5 deletions py/objint.c
Expand Up @@ -49,14 +49,13 @@ STATIC mp_obj_t mp_obj_int_make_new(const mp_obj_type_t *type_in, size_t n_args,
return MP_OBJ_NEW_SMALL_INT(0);

case 1: {
mp_buffer_info_t bufinfo;
mp_obj_t o = mp_unary_op(MP_UNARY_OP_INT_MAYBE, args[0]);
if (o != MP_OBJ_NULL) {
return o;
} else if (mp_obj_is_str_or_bytes(args[0])) {
// a string, parse it
size_t l;
const char *s = mp_obj_str_get_data(args[0], &l);
return mp_parse_num_integer(s, l, 0, NULL);
} else if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
// a textual representation, parse it
return mp_parse_num_integer(bufinfo.buf, bufinfo.len, 0, NULL);
#if MICROPY_PY_BUILTINS_FLOAT
} else if (mp_obj_is_float(args[0])) {
return mp_obj_new_int_from_float(mp_obj_float_get(args[0]));
Expand Down
12 changes: 12 additions & 0 deletions tests/basics/int_parse.py
@@ -0,0 +1,12 @@
# Test parsing ints.

try:
bytearray
memoryview
except NameError:
print("SKIP")
raise SystemExit

print(int(b"123"))
print(int(bytearray(b"123")))
print(int(memoryview(b"123")))

0 comments on commit 69dd013

Please sign in to comment.