diff options
| author | Yoctopuce dev <dev@yoctopuce.com> | 2025-06-30 23:28:20 +0200 |
|---|---|---|
| committer | Damien George <damien@micropython.org> | 2025-07-09 11:54:21 +1000 |
| commit | c4a88f2ce7da87d5f635ec25edba481917020fd8 (patch) | |
| tree | 6d8c704092f58c09136d5bd41563a7c73c57e6f4 /py/objint_longlong.c | |
| parent | 49159ef6b7e283681cb1c2dfe44cdf14bd397467 (diff) | |
py/obj: Add functions to retrieve large integers from mp_obj_t.
This commit provides helpers to retrieve integer values from
mp_obj_t when the content does not fit in a 32 bits integer,
without risking an implicit wrap due to an int overflow.
Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
Diffstat (limited to 'py/objint_longlong.c')
| -rw-r--r-- | py/objint_longlong.c | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/py/objint_longlong.c b/py/objint_longlong.c index 1940b8153..5b60eb65a 100644 --- a/py/objint_longlong.c +++ b/py/objint_longlong.c @@ -295,6 +295,22 @@ mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) { return mp_obj_int_get_truncated(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 = self_in; + long long value = self->val; + mp_uint_t truncated = (mp_uint_t)value; + if (value >= 0 && (long long)truncated == value) { + return truncated; + } + } + mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("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_exact_type(self_in, &mp_type_int)); |
