8000 py/objint: Add mp_obj_int_get_uint_checked() helper. · andrewleech/micropython@176ab99 · GitHub < 8000 link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png">
[go: up one dir, main page]

Skip to content

Commit 176ab99

Browse files
Jongydpgeorge
authored andcommitted
py/objint: Add mp_obj_int_get_uint_checked() helper.
Can be used where mp_obj_int_get_checked() will overflow due to the sign-bit solely. This returns an mp_uint_t, so it also verifies the given integer is not negative. Currently implemented only for mpz configurations.
1 parent 1c849d6 commit 176ab99

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

py/obj.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -748,6 +748,8 @@ void mp_obj_cell_set(mp_obj_t self_in, mp_obj_t obj);
748748
mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in);
749749
// Will raise exception if value doesn't fit into mp_int_t
750750
mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in);
751+
// Will raise exception if value is negative or doesn't fit into mp_uint_t
752+
mp_uint_t mp_obj_int_get_uint_checked(mp_const_obj_t self_in);
751753

752754
// exception
753755
#define mp_obj_is_native_exception_instance(o) (mp_obj_get_type(o)->make_new == mp_obj_exception_make_new)

py/objint_mpz.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,22 @@ mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
411411
}
412412
}
413413

414+
mp_uint_t mp_obj_int_get_uint_checked(mp_const_obj_t self_in) {
415+
if (mp_obj_is_small_int(self_in)) {
416+
if (MP_OBJ_SMALL_INT_VALUE(self_in) >= 0) {
417+
return MP_OBJ_SMALL_INT_VALUE(self_in);
418+
}
419+
} else {
420+
const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
421+
mp_uint_t value;
422+
if (mpz_as_uint_checked(&self->mpz, &value)) {
423+
return value;
424+
}
425+
}
426+
427+
mp_raise_msg(&mp_type_OverflowError, "overflow converting long int to machine word");
428+
}
429+
414430
#if MICROPY_PY_BUILTINS_FLOAT
415431
mp_float_t mp_obj_int_as_float_impl(mp_obj_t self_in) {
416432
assert(mp_obj_is_type(self_in, &mp_type_int));

0 commit comments

Comments
 (0)
0