| ... | @@ -126,6 +126,14 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 | ... | @@ -126,6 +126,14 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 |
| 126 | }; | 126 | }; |
| 127 | } | 127 | } |
| 128 | | 128 | |
| | 129 | pub fn getOrPutValue(self: *Self, key: K, value: V) !*KV { |
| | 130 | const res = try self.getOrPut(key); |
| | 131 | if (!res.found_existing) |
| | 132 | res.kv.value = value; |
| | 133 | |
| | 134 | return res.kv; |
| | 135 | } |
| | 136 | |
| 129 | fn ensureCapacity(self: *Self) !void { | 137 | fn ensureCapacity(self: *Self) !void { |
| 130 | if (self.entries.len == 0) { | 138 | if (self.entries.len == 0) { |
| 131 | return self.initCapacity(16); | 139 | return self.initCapacity(16); |
| ... | @@ -354,6 +362,12 @@ test "basic hash map usage" { | ... | @@ -354,6 +362,12 @@ test "basic hash map usage" { |
| 354 | gop2.kv.value = 42; | 362 | gop2.kv.value = 42; |
| 355 | assert(map.get(99).?.value == 42); | 363 | assert(map.get(99).?.value == 42); |
| 356 | | 364 | |
| | 365 | const gop3 = try map.getOrPutValue(5, 5); |
| | 366 | assert(gop3.value == 77); |
| | 367 | |
| | 368 | const gop4 = try map.getOrPutValue(100, 41); |
| | 369 | assert(gop4.value == 41); |
| | 370 | |
| 357 | assert(map.contains(2)); | 371 | assert(map.contains(2)); |
| 358 | assert(map.get(2).?.value == 22); | 372 | assert(map.get(2).?.value == 22); |
| 359 | _ = map.remove(2); | 373 | _ = map.remove(2); |