From 0d255130984de6ba082f6c6e28356ef3e35984f6 Mon Sep 17 00:00:00 2001 From: Jon Foster Date: Mon, 1 Apr 2024 19:19:29 +0100 Subject: [PATCH] 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 --- py/obj.h | 1 + py/objstr.c | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/py/obj.h b/py/obj.h index 9f2bb46e41..0e56517ddb 100644 --- a/py/obj.h +++ b/py/obj.h @@ -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 diff --git a/py/objstr.c b/py/objstr.c index c7e4ebf53b..ff6d481ec4 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -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);