| ... | ... | @@ -175,7 +175,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 |
| 175 | 175 | return hm.get(key) != null; |
| 176 | 176 | } |
| 177 | 177 | |
| 178 | | pub fn remove(hm: *Self, key: K) ?*KV { |
| 178 | pub fn remove(hm: *Self, key: K) ?KV { |
| 179 | 179 | if (hm.entries.len == 0) return null; |
| 180 | 180 | hm.incrementModificationCount(); |
| 181 | 181 | const start_index = hm.keyToIndex(key); |
| ... | ... | @@ -189,13 +189,14 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 |
| 189 | 189 | |
| 190 | 190 | if (!eql(entry.kv.key, key)) continue; |
| 191 | 191 | |
| 192 | const removed_kv = entry.kv; |
| 192 | 193 | while (roll_over < hm.entries.len) : (roll_over += 1) { |
| 193 | 194 | const next_index = (start_index + roll_over + 1) % hm.entries.len; |
| 194 | 195 | const next_entry = &hm.entries[next_index]; |
| 195 | 196 | if (!next_entry.used or next_entry.distance_from_start_index == 0) { |
| 196 | 197 | entry.used = false; |
| 197 | 198 | hm.size -= 1; |
| 198 | | return &entry.kv; |
| 199 | return removed_kv; |
| 199 | 200 | } |
| 200 | 201 | entry.* = next_entry.*; |
| 201 | 202 | entry.distance_from_start_index -= 1; |
| ... | ... | @@ -371,7 +372,10 @@ test "basic hash map usage" { |
| 371 | 372 | |
| 372 | 373 | testing.expect(map.contains(2)); |
| 373 | 374 | testing.expect(map.get(2).?.value == 22); |
| 374 | | _ = map.remove(2); |
| 375 | |
| 376 | const rmv1 = map.remove(2); |
| 377 | testing.expect(rmv1.?.key == 2); |
| 378 | testing.expect(rmv1.?.value == 22); |
| 375 | 379 | testing.expect(map.remove(2) == null); |
| 376 | 380 | testing.expect(map.get(2) == null); |
| 377 | 381 | } |