diff --git a/src/hb-map.hh b/src/hb-map.hh index c708b0839..6b73ac29a 100644 --- a/src/hb-map.hh +++ b/src/hb-map.hh @@ -458,6 +458,9 @@ struct hb_hashmap_t void update (const hb_hashmap_t &other) { if (unlikely (!successful)) return; + /* other.iter () walks other's items array, which set () may free + * if it grows the table. Merging into ourselves changes nothing. */ + if (unlikely (&other == this)) return; hb_copy (other, *this); } diff --git a/src/test-map.cc b/src/test-map.cc index 6720e5f5a..e3b14b578 100644 --- a/src/test-map.cc +++ b/src/test-map.cc @@ -331,6 +331,28 @@ main (int argc, char **argv) hb_always_assert (m1[1] == 3); hb_always_assert (m1[2] == 4); } + /* Test update with self, with the table at its growth threshold so + * that set () would reallocate the items being iterated. */ + { + hb_map_t m; + for (unsigned i = 0; i < 5; i++) + m.set (i, i * 2); + + m.update (m); + hb_always_assert (m.get_population () == 5); + for (unsigned i = 0; i < 5; i++) + hb_always_assert (m[i] == i * 2); + + for (unsigned i = 5; i < 42; i++) + m.set (i, i * 2); + for (unsigned i = 0; i < 32; i++) + m.del (i); + + m.update (m); + hb_always_assert (m.get_population () == 10); + for (unsigned i = 32; i < 42; i++) + hb_always_assert (m[i] == i * 2); + } /* Test keys / values */ { hb_map_t m; diff --git a/test/api/test-map.c b/test/api/test-map.c index 1353aefa4..f1949e98a 100644 --- a/test/api/test-map.c +++ b/test/api/test-map.c @@ -102,6 +102,18 @@ test_map_copy_equal_hash_update (void) assert_map_has (copy, 44, 404); assert_map_has (m, 22, 202); + /* Updating a map from itself is a no-op; 5 entries put the table at + * its growth threshold. */ + hb_map_set (copy, 55, 505); + hb_map_set (copy, 66, 606); + hb_map_update (copy, copy); + g_assert_cmpint (hb_map_get_population (copy), ==, 5); + assert_map_has (copy, 11, 101); + assert_map_has (copy, 22, 222); + assert_map_has (copy, 44, 404); + assert_map_has (copy, 55, 505); + assert_map_has (copy, 66, 606); + hb_map_destroy (updated); hb_map_destroy (copy); hb_map_destroy (m);