int: Add value accessors: mp_obj_int_get() & mp_obj_int_get_checked().
mp_obj_int_get() can be used when just full resolution of C machine_int_t
is required (returns truncated value of long int). mp_obj_int_get_checked()
will throw exception if Python int value not representable in machine_int_t.
diff --git a/py/obj.c b/py/obj.c
index 9ca3d5d..4fe287d 100644
--- a/py/obj.c
+++ b/py/obj.c
@@ -155,6 +155,8 @@
return 1;
} else if (MP_OBJ_IS_SMALL_INT(arg)) {
return MP_OBJ_SMALL_INT_VALUE(arg);
+ } else if (MP_OBJ_IS_TYPE(arg, &int_type)) {
+ return mp_obj_int_get_checked(arg);
#if MICROPY_ENABLE_FLOAT
} else if (MP_OBJ_IS_TYPE(arg, &float_type)) {
// TODO work out if this should be floor, ceil or trunc
diff --git a/py/obj.h b/py/obj.h
index 99d430f..4984548 100644
--- a/py/obj.h
+++ b/py/obj.h
@@ -265,6 +265,10 @@
// int
extern const mp_obj_type_t int_type;
+// For long int, returns value truncated to machine_int_t
+machine_int_t mp_obj_int_get(mp_obj_t self_in);
+// Will rains exception if value doesn't fit into machine_int_t
+machine_int_t mp_obj_int_get_checked(mp_obj_t self_in);
// exception
extern const mp_obj_type_t exception_type;
diff --git a/py/objint.c b/py/objint.c
index 59181ea..905944d 100644
--- a/py/objint.c
+++ b/py/objint.c
@@ -77,4 +77,13 @@
nlr_jump(mp_obj_new_exception_msg(MP_QSTR_OverflowError, "small int overflow"));
return mp_const_none;
}
+
+machine_int_t mp_obj_int_get(mp_obj_t self_in) {
+ return MP_OBJ_SMALL_INT_VALUE(self_in);
+}
+
+machine_int_t mp_obj_int_get_checked(mp_obj_t self_in) {
+ return MP_OBJ_SMALL_INT_VALUE(self_in);
+}
+
#endif
diff --git a/py/objint_longlong.c b/py/objint_longlong.c
index c940ce1..24d6937 100644
--- a/py/objint_longlong.c
+++ b/py/objint_longlong.c
@@ -120,9 +120,17 @@
return o;
}
-machine_int_t mp_obj_int_get_int(mp_obj_t self_in) {
+machine_int_t mp_obj_int_get(mp_obj_t self_in) {
+ if (MP_OBJ_IS_SMALL_INT(self_in)) {
+ return MP_OBJ_SMALL_INT_VALUE(self_in);
+ }
mp_obj_int_t *self = self_in;
return self->val;
}
+machine_int_t mp_obj_int_get_checked(mp_obj_t self_in) {
+ // TODO: Check overflow
+ return mp_obj_int_get(self_in);
+}
+
#endif