Skip to content

Commit d26b379

Browse files
committed
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.
1 parent 166bb40 commit d26b379

4 files changed

Lines changed: 24 additions & 1 deletion

File tree

py/obj.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ machine_int_t mp_obj_get_int(mp_obj_t arg) {
155155
return 1;
156156
} else if (MP_OBJ_IS_SMALL_INT(arg)) {
157157
return MP_OBJ_SMALL_INT_VALUE(arg);
158+
} else if (MP_OBJ_IS_TYPE(arg, &int_type)) {
159+
return mp_obj_int_get_checked(arg);
158160
#if MICROPY_ENABLE_FLOAT
159161
} else if (MP_OBJ_IS_TYPE(arg, &float_type)) {
160162
// TODO work out if this should be floor, ceil or trunc

py/obj.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,10 @@ void mp_obj_cell_set(mp_obj_t self_in, mp_obj_t obj);
265265

266266
// int
267267
extern const mp_obj_type_t int_type;
268+
// For long int, returns value truncated to machine_int_t
269+
machine_int_t mp_obj_int_get(mp_obj_t self_in);
270+
// Will rains exception if value doesn't fit into machine_int_t
271+
machine_int_t mp_obj_int_get_checked(mp_obj_t self_in);
268272

269273
// exception
270274
extern const mp_obj_type_t exception_type;

py/objint.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,13 @@ mp_obj_t mp_obj_new_int(machine_int_t value) {
7777
nlr_jump(mp_obj_new_exception_msg(MP_QSTR_OverflowError, "small int overflow"));
7878
return mp_const_none;
7979
}
80+
81+
machine_int_t mp_obj_int_get(mp_obj_t self_in) {
82+
return MP_OBJ_SMALL_INT_VALUE(self_in);
83+
}
84+
85+
machine_int_t mp_obj_int_get_checked(mp_obj_t self_in) {
86+
return MP_OBJ_SMALL_INT_VALUE(self_in);
87+
}
88+
8089
#endif

py/objint_longlong.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,17 @@ mp_obj_t mp_obj_new_int_from_long_str(const char *s) {
120120
return o;
121121
}
122122

123-
machine_int_t mp_obj_int_get_int(mp_obj_t self_in) {
123+
machine_int_t mp_obj_int_get(mp_obj_t self_in) {
124+
if (MP_OBJ_IS_SMALL_INT(self_in)) {
125+
return MP_OBJ_SMALL_INT_VALUE(self_in);
126+
}
124127
mp_obj_int_t *self = self_in;
125128
return self->val;
126129
}
127130

131+
machine_int_t mp_obj_int_get_checked(mp_obj_t self_in) {
132+
// TODO: Check overflow
133+
return mp_obj_int_get(self_in);
134+
}
135+
128136
#endif

0 commit comments

Comments
 (0)