diff options
| author | Takeshi Yoneda <takeshi@tetrate.io> | 2021-08-09 14:39:26 +0900 |
|---|---|---|
| committer | Takeshi Yoneda <takeshi@tetrate.io> | 2021-08-09 14:39:26 +0900 |
| commit | 97560cd915008f04addc2c30af087aa89c162b02 (patch) | |
| tree | 8aed12c207ff84cc256a0c78955c23b61129ba22 /lib/std/array_hash_map.zig | |
| parent | 7814a2bd4a3ec22cd9548c622f7dc837dba968f7 (diff) | |
| parent | 799fedf612aa8742c446b015c12d21707a1dbec0 (diff) | |
| download | zig-97560cd915008f04addc2c30af087aa89c162b02.tar.gz zig-97560cd915008f04addc2c30af087aa89c162b02.zip | |
Merge remote-tracking branch 'origin' into libc-wasi-test
Diffstat (limited to 'lib/std/array_hash_map.zig')
| -rw-r--r-- | lib/std/array_hash_map.zig | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/lib/std/array_hash_map.zig b/lib/std/array_hash_map.zig index 9bcecab47e..4ca603d2e8 100644 --- a/lib/std/array_hash_map.zig +++ b/lib/std/array_hash_map.zig @@ -414,6 +414,12 @@ pub fn ArrayHashMap( pub fn pop(self: *Self) KV { return self.unmanaged.popContext(self.ctx); } + + /// Removes the last inserted `Entry` in the hash map and returns it if count is nonzero. + /// Otherwise returns null. + pub fn popOrNull(self: *Self) ?KV { + return self.unmanaged.popOrNullContext(self.ctx); + } }; } @@ -1181,6 +1187,17 @@ pub fn ArrayHashMapUnmanaged( }; } + /// Removes the last inserted `Entry` in the hash map and returns it if count is nonzero. + /// Otherwise returns null. + pub fn popOrNull(self: *Self) ?KV { + if (@sizeOf(ByIndexContext) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call popContext instead."); + return self.popOrNullContext(undefined); + } + pub fn popOrNullContext(self: *Self, ctx: Context) ?KV { + return if (self.entries.len == 0) null else self.popContext(ctx); + } + // ------------------ No pub fns below this point ------------------ fn fetchRemoveByKey(self: *Self, key: anytype, key_ctx: anytype, ctx: ByIndexContext, comptime removal_type: RemovalType) ?KV { @@ -2094,6 +2111,26 @@ test "pop" { } } +test "popOrNull" { + var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); + defer map.deinit(); + + // Insert just enough entries so that the map expands. Afterwards, + // pop all entries out of the map. + + var i: i32 = 0; + while (i < 9) : (i += 1) { + try testing.expect((try map.fetchPut(i, i)) == null); + } + + while (map.popOrNull()) |pop| { + try testing.expect(pop.key == i - 1 and pop.value == i - 1); + i -= 1; + } + + try testing.expect(map.count() == 0); +} + test "reIndex" { var map = ArrayHashMap(i32, i32, AutoContext(i32), true).init(std.testing.allocator); defer map.deinit(); |
