Skip to content

Commit 3c8f9f4

Browse files
committed
py/modbuiltins: Share vstr_add_char's implementation of utf8 encoding.
This saves ~84 bytes on trinket m0, and saves 112 bytes on PYBV10. Signed-off-by: Jeff Epler <[email protected]>
1 parent 28c2094 commit 3c8f9f4

File tree

1 file changed

+4
-22
lines changed

1 file changed

+4
-22
lines changed

py/modbuiltins.c

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -137,30 +137,12 @@ MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_callable_obj, mp_builtin_callable);
137137
STATIC mp_obj_t mp_builtin_chr(mp_obj_t o_in) {
138138
#if MICROPY_PY_BUILTINS_STR_UNICODE
139139
mp_uint_t c = mp_obj_get_int(o_in);
140-
uint8_t str[4];
141-
int len = 0;
142-
if (c < 0x80) {
143-
*str = c;
144-
len = 1;
145-
} else if (c < 0x800) {
146-
str[0] = (c >> 6) | 0xC0;
147-
str[1] = (c & 0x3F) | 0x80;
148-
len = 2;
149-
} else if (c < 0x10000) {
150-
str[0] = (c >> 12) | 0xE0;
151-
str[1] = ((c >> 6) & 0x3F) | 0x80;
152-
str[2] = (c & 0x3F) | 0x80;
153-
len = 3;
154-
} else if (c < 0x110000) {
155-
str[0] = (c >> 18) | 0xF0;
156-
str[1] = ((c >> 12) & 0x3F) | 0x80;
157-
str[2] = ((c >> 6) & 0x3F) | 0x80;
158-
str[3] = (c & 0x3F) | 0x80;
159-
len = 4;
160-
} else {
140+
if (c >= 0x110000) {
161141
mp_raise_ValueError(MP_ERROR_TEXT("chr() arg not in range(0x110000)"));
162142
}
163-
return mp_obj_new_str_via_qstr((char *)str, len);
143+
VSTR_FIXED(buf, 4);
144+
vstr_add_char(&buf, c);
145+
return mp_obj_new_str_via_qstr(buf.buf, buf.len);
164146
#else
165147
mp_int_t ord = mp_obj_get_int(o_in);
166148
if (0 <= ord && ord <= 0xff) {

0 commit comments

Comments
 (0)