Skip to content

Commit

Permalink
py/objstr: Add new mp_obj_new_str_from_cstr() helper function.
Browse files Browse the repository at this point in the history
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_from_cstr(s);

This gives clearer, and probably smaller, code.

Signed-off-by: Jon Foster <[email protected]>
  • Loading branch information
jonfoster authored and dpgeorge committed Jul 4, 2024
1 parent f36a565 commit 289b2dd
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 0 deletions.
1 change: 1 addition & 0 deletions py/obj.h
Original file line number Diff line number Diff line change
Expand Up @@ -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_from_cstr(const char *str); // // accepts null-terminated string, 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
Expand Down
4 changes: 4 additions & 0 deletions py/objstr.c
Original file line number Diff line number Diff line change
Expand Up @@ -2308,6 +2308,10 @@ mp_obj_t mp_obj_new_str(const char *data, size_t len) {
}
}

mp_obj_t mp_obj_new_str_from_cstr(const char *str) {
return mp_obj_new_str(str, strlen(str));
}

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);
Expand Down

0 comments on commit 289b2dd

Please sign in to comment.