summaryrefslogtreecommitdiff
path: root/py/modbuiltins.c
diff options
context:
space:
mode:
authorJeff Epler <jepler@gmail.com>2023-11-23 11:49:57 -0600
committerDamien George <damien@micropython.org>2023-11-28 23:34:56 +1100
commit9c7067d9ad91a303389ec0add306bedac55e18f9 (patch)
treefa34865e2bc6284fc4af9213a65286df2e1f87fe /py/modbuiltins.c
parentcfcd0c4022c571a174efd0400496d679fbe369e2 (diff)
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 <jepler@gmail.com>
Diffstat (limited to 'py/modbuiltins.c')
-rw-r--r--py/modbuiltins.c26
1 files changed, 4 insertions, 22 deletions
diff --git a/py/modbuiltins.c b/py/modbuiltins.c
index da29e5b67..4ff7d4450 100644
--- a/py/modbuiltins.c
+++ b/py/modbuiltins.c
@@ -137,30 +137,12 @@ MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_callable_obj, mp_builtin_callable);
STATIC mp_obj_t mp_builtin_chr(mp_obj_t o_in) {
#if MICROPY_PY_BUILTINS_STR_UNICODE
mp_uint_t c = mp_obj_get_int(o_in);
- uint8_t str[4];
- int len = 0;
- if (c < 0x80) {
- *str = c;
- len = 1;
- } else if (c < 0x800) {
- str[0] = (c >> 6) | 0xC0;
- str[1] = (c & 0x3F) | 0x80;
- len = 2;
- } else if (c < 0x10000) {
- str[0] = (c >> 12) | 0xE0;
- str[1] = ((c >> 6) & 0x3F) | 0x80;
- str[2] = (c & 0x3F) | 0x80;
- len = 3;
- } else if (c < 0x110000) {
- str[0] = (c >> 18) | 0xF0;
- str[1] = ((c >> 12) & 0x3F) | 0x80;
- str[2] = ((c >> 6) & 0x3F) | 0x80;
- str[3] = (c & 0x3F) | 0x80;
- len = 4;
- } else {
+ if (c >= 0x110000) {
mp_raise_ValueError(MP_ERROR_TEXT("chr() arg not in range(0x110000)"));
}
- return mp_obj_new_str_via_qstr((char *)str, len);
+ VSTR_FIXED(buf, 4);
+ vstr_add_char(&buf, c);
+ return mp_obj_new_str_via_qstr(buf.buf, buf.len);
#else
mp_int_t ord = mp_obj_get_int(o_in);
if (0 <= ord && ord <= 0xff) {