std.ArrayHashMap: popOrNul() -> pop()

This commit is contained in:
Meghan Denny
2025-02-02 00:03:19 -08:00
committed by Andrew Kelley
parent 84d2c6dc72
commit a8af36ab10
6 changed files with 15 additions and 47 deletions

View File

@@ -485,15 +485,10 @@ pub fn ArrayHashMapWithAllocator(
return self.unmanaged.shrinkAndFreeContext(self.allocator, new_len, self.ctx);
}
/// Removes the last inserted `Entry` in the hash map and returns it.
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);
pub fn pop(self: *Self) ?KV {
return self.unmanaged.popContext(self.ctx);
}
};
}
@@ -1468,12 +1463,14 @@ pub fn ArrayHashMapUnmanaged(
}
/// Removes the last inserted `Entry` in the hash map and returns it.
pub fn pop(self: *Self) KV {
/// Otherwise returns null.
pub fn pop(self: *Self) ?KV {
if (@sizeOf(ByIndexContext) != 0)
@compileError("Cannot infer context " ++ @typeName(Context) ++ ", call popContext instead.");
return self.popContext(undefined);
}
pub fn popContext(self: *Self, ctx: Context) KV {
pub fn popContext(self: *Self, ctx: Context) ?KV {
if (self.entries.len == 0) return null;
self.pointer_stability.lock();
defer self.pointer_stability.unlock();
@@ -1487,17 +1484,6 @@ 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);
}
fn fetchRemoveByKey(
self: *Self,
key: anytype,
@@ -2425,7 +2411,7 @@ test "shrink" {
}
}
test "pop" {
test "pop()" {
var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
@@ -2437,25 +2423,7 @@ test "pop" {
try testing.expect((try map.fetchPut(i, i)) == null);
}
while (i > 0) : (i -= 1) {
const pop = map.pop();
try testing.expect(pop.key == i - 1 and pop.value == i - 1);
}
}
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| {
while (map.pop()) |pop| {
try testing.expect(pop.key == i - 1 and pop.value == i - 1);
i -= 1;
}