Skip to content

Commit a1c3210

Browse files
committed
py/qstr: Add qstr_from_strn_static() helper function.
Allows an interned string to reference static/ROM data, instead of allocating it on the GC heap. Signed-off-by: Damien George <[email protected]>
1 parent 50637ff commit a1c3210

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

py/qstr.c

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ qstr qstr_from_str(const char *str) {
309309
return qstr_from_strn(str, strlen(str));
310310
}
311311

312-
qstr qstr_from_strn(const char *str, size_t len) {
312+
static qstr qstr_from_strn_helper(const char *str, size_t len, bool data_is_static) {
313313
QSTR_ENTER();
314314
qstr q = qstr_find_strn(str, len);
315315
if (q == 0) {
@@ -321,6 +321,12 @@ qstr qstr_from_strn(const char *str, size_t len) {
321321
mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("name too long"));
322322
}
323323

324+
if (data_is_static) {
325+
// Given string data will be forever available so use it directly.
326+
assert(str[len] == '\0');
327+
goto add;
328+
}
329+
324330
// compute number of bytes needed to intern this string
325331
size_t n_bytes = len + 1;
326332

@@ -364,12 +370,26 @@ qstr qstr_from_strn(const char *str, size_t len) {
364370
// store the interned strings' data
365371
memcpy(q_ptr, str, len);
366372
q_ptr[len] = '\0';
367-
q = qstr_add(len, q_ptr);
373+
str = q_ptr;
374+
375+
add:
376+
q = qstr_add(len, str);
368377
}
369378
QSTR_EXIT();
370379
return q;
371380
}
372381

382+
qstr qstr_from_strn(const char *str, size_t len) {
383+
return qstr_from_strn_helper(str, len, false);
384+
}
385+
386+
#if MICROPY_VFS_ROM
387+
// Create a new qstr that can forever reference the given string data.
388+
qstr qstr_from_strn_static(const char *str, size_t len) {
389+
return qstr_from_strn_helper(str, len, true);
390+
}
391+
#endif
392+
373393
mp_uint_t qstr_hash(qstr q) {
374394
const qstr_pool_t *pool = find_qstr(&q);
375395
#if MICROPY_QSTR_BYTES_IN_HASH

py/qstr.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ qstr qstr_find_strn(const char *str, size_t str_len); // returns MP_QSTRnull if
101101

102102
qstr qstr_from_str(const char *str);
103103
qstr qstr_from_strn(const char *str, size_t len);
104+
#if MICROPY_VFS_ROM
105+
qstr qstr_from_strn_static(const char *str, size_t len);
106+
#endif
104107

105108
mp_uint_t qstr_hash(qstr q);
106109
const char *qstr_str(qstr q);

0 commit comments

Comments
 (0)