diff options
Diffstat (limited to 'py/obj.c')
-rw-r--r-- | py/obj.c | 24 |
1 files changed, 24 insertions, 0 deletions
@@ -2,6 +2,7 @@ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> +#include <string.h> #include <assert.h> #include "nlr.h" @@ -227,3 +228,26 @@ uint mp_get_index(const mp_obj_type_t *type, machine_uint_t len, mp_obj_t index) nlr_jump(mp_obj_new_exception_msg_varg(MP_QSTR_TypeError, "%s indices must be integers, not %s", type->name, mp_obj_get_type_str(index))); } } + +// may return NULL +mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) { + mp_small_int_t len = 0; + if (MP_OBJ_IS_TYPE(o_in, &str_type)) { + len = strlen(qstr_str(mp_obj_str_get(o_in))); + } else if (MP_OBJ_IS_TYPE(o_in, &tuple_type)) { + uint seq_len; + mp_obj_t *seq_items; + mp_obj_tuple_get(o_in, &seq_len, &seq_items); + len = seq_len; + } else if (MP_OBJ_IS_TYPE(o_in, &list_type)) { + uint seq_len; + mp_obj_t *seq_items; + mp_obj_list_get(o_in, &seq_len, &seq_items); + len = seq_len; + } else if (MP_OBJ_IS_TYPE(o_in, &dict_type)) { + len = mp_obj_dict_len(o_in); + } else { + return NULL; + } + return MP_OBJ_NEW_SMALL_INT(len); +} |