8000 py: If str/bytes hash is 0 then explicitly compute it. · danni/micropython@5f3bda4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5f3bda4

Browse files
committed
py: If str/bytes hash is 0 then explicitly compute it.
1 parent f127bef commit 5f3bda4

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

py/objstr.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,9 @@ mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_
158158
if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
159159
GET_STR_DATA_LEN(args[0], str_data, str_len);
160160
GET_STR_HASH(args[0], str_hash);
161+
if (str_hash == 0) {
162+
str_hash = qstr_compute_hash(str_data, str_len);
163+
}
161164
mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_of_type(type, NULL, str_len));
162165
o->data = str_data;
163166
o->hash = str_hash;
@@ -191,6 +194,9 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size
191194
}
192195
GET_STR_DATA_LEN(args[0], str_data, str_len);
193196
GET_STR_HASH(args[0], str_hash);
197+
if (str_hash == 0) {
198+
str_hash = qstr_compute_hash(str_data, str_len);
199+
}
194200
mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len));
195201
o->data = str_data;
196202
o->hash = str_hash;

py/objstr.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ typedef struct _mp_obj_str_t {
3939
#define MP_DEFINE_STR_OBJ(obj_name, str) mp_obj_str_t obj_name = {{&mp_type_str}, 0, sizeof(str) - 1, (const byte*)str}
4040

4141
// use this macro to extract the string hash
42+
// warning: the hash can be 0, meaning invalid, and must then be explicitly computed from the data
4243
#define GET_STR_HASH(str_obj_in, str_hash) \
4344
mp_uint_t str_hash; if (MP_OBJ_IS_QSTR(str_obj_in)) \
4445
{ str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->hash; }

py/runtime.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,10 @@ mp_obj_t mp_unary_op(mp_uint_t op, mp_obj_t arg) {
217217
} else if (op == MP_UNARY_OP_HASH && MP_OBJ_IS_STR_OR_BYTES(arg)) {
218218
// fast path for hashing str/bytes
219219
GET_STR_HASH(arg, h);
220+
if (h == 0) {
221+
GET_STR_DATA_LEN(arg, data, len);
222+
h = qstr_compute_hash(data, len);
223+
}
220224
return MP_OBJ_NEW_SMALL_INT(h);
221225
} else {
222226
mp_obj_type_t *type = mp_obj_get_type(arg);

0 commit comments

Comments
 (0)
0