Skip to content

Commit e7f2b4c

Browse files
committed
objstrunicode: Revamp len() handling for unicode, and optimize bool().
1 parent 86d3898 commit e7f2b4c

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

py/obj.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,12 @@ uint mp_get_index(const mp_obj_type_t *type, machine_uint_t len, mp_obj_t index,
354354

355355
// may return MP_OBJ_NULL
356356
mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) {
357-
if (MP_OBJ_IS_STR(o_in) || MP_OBJ_IS_TYPE(o_in, &mp_type_bytes)) {
357+
if (
358+
#if !MICROPY_PY_BUILTINS_STR_UNICODE
359+
// It's simple - unicode is slow, non-unicode is fast
360+
MP_OBJ_IS_STR(o_in) ||
361+
#endif
362+
MP_OBJ_IS_TYPE(o_in, &mp_type_bytes)) {
358363
return MP_OBJ_NEW_SMALL_INT((machine_int_t)mp_obj_str_get_len(o_in));
359364
} else {
360365
mp_obj_type_t *type = mp_obj_get_type(o_in);

py/objstrunicode.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,18 @@ STATIC void uni_print(void (*print)(void *env, const char *fmt, ...), void *env,
100100
}
101101
}
102102

103+
STATIC mp_obj_t uni_unary_op(int op, mp_obj_t self_in) {
104+
GET_STR_DATA_LEN(self_in, str_data, str_len);
105+
switch (op) {
106+
case MP_UNARY_OP_BOOL:
107+
return MP_BOOL(str_len != 0);
108+
case MP_UNARY_OP_LEN:
109+
return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char *)str_data, str_len));
110+
default:
111+
return MP_OBJ_NULL; // op not supported
112+
}
113+
}
114+
103115
STATIC mp_obj_t str_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
104116
#if MICROPY_CPYTHON_COMPAT
105117
if (n_kw != 0) {
@@ -297,6 +309,7 @@ const mp_obj_type_t mp_type_str = {
297309
.name = MP_QSTR_str,
298310
.print = uni_print,
299311
.make_new = str_make_new,
312+
.unary_op = uni_unary_op,
300313
.binary_op = str_binary_op,
301314
.subscr = str_subscr,
302315
.getiter = mp_obj_new_str_iterator,

0 commit comments

Comments
 (0)