py/modsys: Implement maybe_intern() function.
If interned string with the same content as input argument exists, return
it. Otherwise, return the original string.
@@ -176,6 +176,27 @@ STATIC mp_obj_t mp_sys_intern(mp_obj_t str_in) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_sys_intern_obj, mp_sys_intern);
#endif
+#if MICROPY_PY_SYS_MAYBE_INTERN
+STATIC mp_obj_t mp_sys_maybe_intern(mp_obj_t str_in) {
+ if (MP_OBJ_IS_QSTR(str_in)) {
+ return str_in;
+ }
+ if (!MP_OBJ_IS_TYPE(str_in, &mp_type_str)) {
+ mp_raise_TypeError(NULL);
+ }
+
+ GET_STR_DATA_LEN(str_in, str_data, str_len);
+
+ qstr qst = qstr_find_strn((const char *)str_data, str_len);
+ if (qst != MP_QSTRnull) {
+ return MP_OBJ_NEW_QSTR(qst);
+ }
+
+ return str_in;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_sys_maybe_intern_obj, mp_sys_maybe_intern);
+#endif
+
#if MICROPY_PY_SYS_STDFILES_OVERRIDE
STATIC MP_NS_DICT mp_obj_dict_t mp_module_sys_globals;
@@ -269,6 +290,9 @@ STATIC MP_SYS_STDIO_ATTR mp_rom_map_elem_t mp_module_sys_globals_table[] = {
#if MICROPY_PY_SYS_INTERN
{ MP_ROM_QSTR(MP_QSTR_intern), MP_ROM_PTR(&mp_sys_intern_obj) },
#endif
+ #if MICROPY_PY_SYS_MAYBE_INTERN
+ { MP_ROM_QSTR(MP_QSTR_maybe_intern), MP_ROM_PTR(&mp_sys_maybe_intern_obj) },
+ #endif
/*
* Extensions to CPython
