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>
This commit is contained in:
parent
28c2094b8d
commit
3c8f9f4dab
@ -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) {
|
STATIC mp_obj_t mp_builtin_chr(mp_obj_t o_in) {
|
||||||
#if MICROPY_PY_BUILTINS_STR_UNICODE
|
#if MICROPY_PY_BUILTINS_STR_UNICODE
|
||||||
mp_uint_t c = mp_obj_get_int(o_in);
|
mp_uint_t c = mp_obj_get_int(o_in);
|
||||||
uint8_t str[4];
|
if (c >= 0x110000) {
|
||||||
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 {
|
|
||||||
mp_raise_ValueError(MP_ERROR_TEXT("chr() arg not in range(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
|
#else
|
||||||
mp_int_t ord = mp_obj_get_int(o_in);
|
mp_int_t ord = mp_obj_get_int(o_in);
|
||||||
if (0 <= ord && ord <= 0xff) {
|
if (0 <= ord && ord <= 0xff) {
|
||||||
|
Loading…
Reference in New Issue
Block a user