Skip to content

py/objint: Add mp_obj_int_get_uint_checked() helper. #4928

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions py/obj.h
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,8 @@ void mp_obj_cell_set(mp_obj_t self_in, mp_obj_t obj);
mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in);
// Will raise exception if value doesn't fit into mp_int_t
mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in);
// Will raise exception if value is negative or doesn't fit into mp_uint_t
mp_uint_t mp_obj_int_get_uint_checked(mp_const_obj_t self_in);

// exception
#define mp_obj_is_native_exception_instance(o) (mp_obj_get_type(o)->make_new == mp_obj_exception_make_new)
Expand Down
16 changes: 16 additions & 0 deletions py/objint_mpz.c
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,22 @@ mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
}
}

mp_uint_t mp_obj_int_get_uint_checked(mp_const_obj_t self_in) {
if (mp_obj_is_small_int(self_in)) {
if (MP_OBJ_SMALL_INT_VALUE(self_in) >= 0) {
return MP_OBJ_SMALL_INT_VALUE(self_in);
}
} else {
const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
mp_uint_t value;
if (mpz_as_uint_checked(&self->mpz, &value)) {
return value;
}
}

mp_raise_msg(&mp_type_OverflowError, "overflow converting long int to machine word");
}

#if MICROPY_PY_BUILTINS_FLOAT
mp_float_t mp_obj_int_as_float_impl(mp_obj_t self_in) {
assert(mp_obj_is_type(self_in, &mp_type_int));
Expand Down