From f39e3397265cf64c7c32fc50e6ff278cb13129a2 Mon Sep 17 00:00:00 2001 From: Walther Chen Date: Mon, 18 Nov 2024 08:20:32 -0500 Subject: [PATCH] Fix error when HashMap.remove on uninitialized HashMap (#1629) * HashMap: test removal on uninitialized * HashMap.remove_entry_for_key: return false on unintialized * test: switch to temp_init * release note --- lib/std/collections/hashmap.c3 | 1 + releasenotes.md | 1 + test/unit/stdlib/collections/map.c3 | 12 +++++++++++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/std/collections/hashmap.c3 b/lib/std/collections/hashmap.c3 index c58bd18d5..e609f4753 100644 --- a/lib/std/collections/hashmap.c3 +++ b/lib/std/collections/hashmap.c3 @@ -482,6 +482,7 @@ fn void HashMap.free_internal(&map, void* ptr) @inline @private fn bool HashMap.remove_entry_for_key(&map, Key key) @private { + if (!map.count) return false; uint hash = rehash(key.hash()); uint i = index_for(hash, map.table.len); Entry* prev = map.table[i]; diff --git a/releasenotes.md b/releasenotes.md index 4a32eaf86..6f7eb3a48 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -12,6 +12,7 @@ - Fix issue writing a single byte in the WriteBuffer - A distinct inline pointer type can now participate in pointer arithmetics. - Support &a[0] returning the distinct type when applying it to a distinct of a pointer. +- Fix error when calling `HashMap.remove` on uninitialized `HashMap`. ### Stdlib changes - Add `io::MultiReader`, `io::MultiWriter`, and `io::TeeReader` structs. diff --git a/test/unit/stdlib/collections/map.c3 b/test/unit/stdlib/collections/map.c3 index c03c84f93..2cbdab9b9 100644 --- a/test/unit/stdlib/collections/map.c3 +++ b/test/unit/stdlib/collections/map.c3 @@ -53,4 +53,14 @@ fn void map() assert(tc.key == list[i].key); assert(tc.value == list[i].value); } -} \ No newline at end of file +} + +fn void map_remove() +{ + Map m; + assert(!@ok(m.remove("A"))); + m.temp_init(); + assert(!@ok(m.remove("A"))); + m.set("A", 0); + assert(@ok(m.remove("A"))); +}