Skip to content

Commit b5fbd0b

Browse files
committed
py: Add mp_obj_is_integer; make mp_get_index check for long int.
mp_obj_is_integer should be used to check if an object is of integral type. It returns true for bool, small int and long int.
1 parent d99944a commit b5fbd0b

3 files changed

Lines changed: 9 additions & 5 deletions

File tree

py/obj.c

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,11 @@ int mp_obj_is_true(mp_obj_t arg) {
9999
}
100100
}
101101

102+
// returns true if o_in is bool, small int, or long int
103+
bool mp_obj_is_integer(mp_obj_t o_in) {
104+
return MP_OBJ_IS_INT(o_in) || MP_OBJ_IS_TYPE(o_in, &mp_type_bool);
105+
}
106+
102107
bool mp_obj_is_callable(mp_obj_t o_in) {
103108
return mp_obj_get_type(o_in)->call != NULL;
104109
}
@@ -285,8 +290,8 @@ void mp_obj_get_array_fixed_n(mp_obj_t o, uint len, mp_obj_t **items) {
285290
// is_slice determines whether the index is a slice index
286291
uint mp_get_index(const mp_obj_type_t *type, machine_uint_t len, mp_obj_t index, bool is_slice) {
287292
int i;
288-
if (MP_OBJ_IS_SMALL_INT(index)) {
289-
i = MP_OBJ_SMALL_INT_VALUE(index);
293+
if (MP_OBJ_IS_INT(index)) {
294+
i = mp_obj_int_get_checked(index);
290295
} else if (MP_OBJ_IS_TYPE(index, &mp_type_bool)) {
291296
i = (index == mp_const_true ? 1 : 0);
292297
} else {

py/obj.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,7 @@ void mp_obj_print(mp_obj_t o, mp_print_kind_t kind);
369369
void mp_obj_print_exception(mp_obj_t exc);
370370

371371
int mp_obj_is_true(mp_obj_t arg);
372+
bool mp_obj_is_integer(mp_obj_t o_in); // returns true if o_in is bool, small int, or long int
372373
bool mp_obj_is_callable(mp_obj_t o_in);
373374
machine_int_t mp_obj_hash(mp_obj_t o_in);
374375
bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2);

py/objstr.c

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -221,9 +221,7 @@ STATIC mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
221221
GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
222222
switch (op) {
223223
case MP_BINARY_OP_SUBSCR:
224-
// TODO: need predicate to check for int-like type (bools are such for example)
225-
// ["no", "yes"][1 == 2] is common idiom
226-
if (MP_OBJ_IS_SMALL_INT(rhs_in)) {
224+
if (mp_obj_is_integer(rhs_in)) {
227225
uint index = mp_get_index(mp_obj_get_type(lhs_in), lhs_len, rhs_in, false);
228226
if (MP_OBJ_IS_TYPE(lhs_in, &mp_type_bytes)) {
229227
return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)lhs_data[index]);

0 commit comments

Comments
 (0)