Skip to content

Commit 65ddc23

Browse files
committed
py/objstr: Factor code with a helper function to create empty str/bytes.
This reduces code duplication, and may help reduce code size. Signed-off-by: Damien George <damien@micropython.org>
1 parent 716aae8 commit 65ddc23

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

py/objstr.c

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@ static void check_is_str_or_bytes(mp_obj_t self_in) {
6868
mp_check_self(mp_obj_is_str_or_bytes(self_in));
6969
}
7070

71+
static mp_obj_t make_empty_str_of_type(const mp_obj_type_t *type) {
72+
if (type == &mp_type_str) {
73+
return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
74+
} else {
75+
return mp_const_empty_bytes;
76+
}
77+
}
78+
7179
static const byte *get_substring_data(const mp_obj_t obj, size_t n_args, const mp_obj_t *args, size_t *len) {
7280
// Get substring data from obj, using args[0,1] to specify start and end indices.
7381
GET_STR_DATA_LEN(obj, str, str_len);
@@ -383,11 +391,7 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i
383391
return MP_OBJ_NULL; // op not supported
384392
}
385393
if (n <= 0) {
386-
if (lhs_type == &mp_type_str) {
387-
return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
388-
} else {
389-
return mp_const_empty_bytes;
390-
}
394+
return make_empty_str_of_type(lhs_type);
391395
}
392396
vstr_t vstr;
393397
vstr_init_len(&vstr, lhs_len * n);
@@ -906,11 +910,7 @@ static mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
906910

907911
if (!first_good_char_pos_set) {
908912
// string is all whitespace, return ''
909-
if (self_type == &mp_type_str) {
910-
return MP_OBJ_NEW_QSTR(MP_QSTR_);
911-
} else {
912-
return mp_const_empty_bytes;
913-
}
913+
return make_empty_str_of_type(self_type);
914914
}
915915

916916
assert(last_good_char_pos >= first_good_char_pos);
@@ -1836,15 +1836,9 @@ static mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
18361836
}
18371837

18381838
mp_obj_t result[3];
1839-
if (self_type == &mp_type_str) {
1840-
result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1841-
result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1842-
result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1843-
} else {
1844-
result[0] = mp_const_empty_bytes;
1845-
result[1] = mp_const_empty_bytes;
1846-
result[2] = mp_const_empty_bytes;
1847-
}
1839+
result[0] = make_empty_str_of_type(self_type);
1840+
result[1] = make_empty_str_of_type(self_type);
1841+
result[2] = make_empty_str_of_type(self_type);
18481842

18491843
if (direction > 0) {
18501844
result[0] = self_in;

0 commit comments

Comments
 (0)