aboutsummaryrefslogtreecommitdiff
path: root/py/objint_mpz.c
diff options
context:
space:
mode:
authorYonatan Goldschmidt <yon.goldschmidt@gmail.com>2020-01-13 23:35:07 +0200
committerDamien George <damien.p.george@gmail.com>2020-01-14 23:35:22 +1100
commit176ab99180a95eeac8794828f2f751a696571bb5 (patch)
treecb572f1c13d0dbeaeada70eeb24dafdeb46404fe /py/objint_mpz.c
parent1c849d63a86782f006b73a9d570d542cfd18538e (diff)
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.
Diffstat (limited to 'py/objint_mpz.c')
-rw-r--r--py/objint_mpz.c16
1 files changed, 16 insertions, 0 deletions
diff --git a/py/objint_mpz.c b/py/objint_mpz.c
index 121fd0342..2c09d9bd2 100644
--- a/py/objint_mpz.c
+++ b/py/objint_mpz.c
@@ -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));