Skip to content

Commit b475327

Browse files
stephenkyle-ARMpfalcon
authored andcommitted
py/map: Prevent map resize failure from destroying map.
1 parent 6a051a8 commit b475327

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

py/map.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,11 +118,14 @@ void mp_map_clear(mp_map_t *map) {
118118

119119
STATIC void mp_map_rehash(mp_map_t *map) {
120120
mp_uint_t old_alloc = map->alloc;
121+
mp_uint_t new_alloc = get_doubling_prime_greater_or_equal_to(map->alloc + 1);
121122
mp_map_elem_t *old_table = map->table;
122-
map->alloc = get_doubling_prime_greater_or_equal_to(map->alloc + 1);
123+
mp_map_elem_t *new_table = m_new0(mp_map_elem_t, new_alloc);
124+
// If we reach this point, table resizing succeeded, now we can edit the old map.
125+
map->alloc = new_alloc;
123126
map->used = 0;
124127
map->all_keys_are_qstrs = 1;
125-
map->table = m_new0(mp_map_elem_t, map->alloc);
128+
map->table = new_table;
126129
for (mp_uint_t i = 0; i < old_alloc; i++) {
127130
if (old_table[i].key != MP_OBJ_NULL && old_table[i].key != MP_OBJ_SENTINEL) {
128131
mp_map_lookup(map, old_table[i].key, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = old_table[i].value;

0 commit comments

Comments
 (0)