py/objstr.c: Add new mp_obj_new_str_0() method.

There were lots of places where this pattern was duplicated, to convert
a standard C string to a MicroPython string:

x = mp_obj_new_str(s, strlen(s));

This commit provides a simpler method that removes this code duplication:

x = mp_obj_new_str_0(s);

The _0 suffix is because it accepts a NUL-terminated string as a
parameter.

This gives clearer, and probably smaller, code.

Signed-off-by: Jon Foster <jon@jon-foster.co.uk>
pull/14227/head
Jon Foster 2024-04-01 19:19:29 +01:00
rodzic 5114f2c1ea
commit 0d25513098
2 zmienionych plików z 5 dodań i 0 usunięć

Wyświetl plik

@ -971,6 +971,7 @@ mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, uns
mp_obj_t mp_obj_new_int_from_ll(long long val); // this must return a multi-precision integer object (or raise an overflow exception)
mp_obj_t mp_obj_new_int_from_ull(unsigned long long val); // this must return a multi-precision integer object (or raise an overflow exception)
mp_obj_t mp_obj_new_str(const char *data, size_t len); // will check utf-8 (raises UnicodeError)
mp_obj_t mp_obj_new_str_0(const char *data); // will check utf-8 (raises UnicodeError)
mp_obj_t mp_obj_new_str_via_qstr(const char *data, size_t len); // input data must be valid utf-8
mp_obj_t mp_obj_new_str_from_vstr(vstr_t *vstr); // will check utf-8 (raises UnicodeError)
#if MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK

Wyświetl plik

@ -2308,6 +2308,10 @@ mp_obj_t mp_obj_new_str(const char *data, size_t len) {
}
}
mp_obj_t mp_obj_new_str_0(const char *data) {
return mp_obj_new_str(data, strlen(data));
}
mp_obj_t mp_obj_str_intern(mp_obj_t str) {
GET_STR_DATA_LEN(str, data, len);
return mp_obj_new_str_via_qstr((const char *)data, len);