From 8644899714246fb4408a8c3e52004618590ea827 Mon Sep 17 00:00:00 2001 From: Vivianne Langdon Date: Tue, 26 Jul 2022 23:24:58 -0700 Subject: [PATCH] support getting ptrs or values, consistent between queue and table --- src/containers/queue.zig | 18 +++++++++++++++--- src/containers/table.zig | 14 +++++++++++--- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/containers/queue.zig b/src/containers/queue.zig index a3fcb90..4c5a95e 100644 --- a/src/containers/queue.zig +++ b/src/containers/queue.zig @@ -77,7 +77,9 @@ pub fn Queue(comptime T: type) type { self.backing[dst & mask] = val; } - pub fn popOrNull(self: *Self) ?T { + /// Pop pointer to the memory. This may be invalidated on any insert or remove, + /// so should be copied or discarded before that point. + pub fn popPtrOrNull(self: *Self) ?*T { if (self.size() <= 0) { return null; } @@ -88,11 +90,21 @@ pub fn Queue(comptime T: type) type { self.reads += 1; // (Same as % self.backing.len because power of 2) - return self.backing[src & mask]; + return &self.backing[src & mask]; + } + + /// Pop pointer to the memory, but panic if null. This may be invalidated on any insert or remove, + /// so should be copied or discarded before that point. + pub fn popPtr(self: *Self) *T { + return self.popPtrOrNull() orelse unreachable; + } + + pub fn popOrNull(self: *Self) ?T { + return if (self.popPtrOrNull()) |ptr| ptr.* else null; } pub fn pop(self: *Self) T { - return self.popOrNull() orelse unreachable; + return self.popPtr().*; } }; } diff --git a/src/containers/table.zig b/src/containers/table.zig index e48989c..ce46b8f 100644 --- a/src/containers/table.zig +++ b/src/containers/table.zig @@ -156,10 +156,14 @@ pub fn Table(comptime K: type, comptime V: type) type { return val; } - pub fn get(self: *Self, id: Id) ?*V { + pub fn getPtr(self: *Self, id: Id) ?*V { return if (self.exists(id)) &(self.values.items[id.index] orelse unreachable) else null; } + pub fn get(self: *Self, id: Id) ?V { + return if (self.getPtr(id)) |ptr| ptr.* else null; + } + pub fn find(self: *Self, key: K) ?Id { if (self.lookup.get(key)) |index| { const gen = self.gens.items[index]; @@ -265,7 +269,7 @@ test "table across generation" { try std.testing.expectEqual(@as(u8, 1), second_result.id.gen); try std.testing.expect(!table.exists(first_result.id)); - try std.testing.expectEqual(@as(?*TestVal, null), table.get(first_result.id)); + try std.testing.expectEqual(@as(?*TestVal, null), table.getPtr(first_result.id)); } test "table iteration" { @@ -402,7 +406,11 @@ pub fn RefTable(comptime K: type, comptime V: type) type { return result; } - pub fn get(self: *Self, id: Id) ?*V { + pub fn getPtr(self: *Self, id: Id) ?*V { + return self.table.getPtr(id); + } + + pub fn get(self: *Self, id: Id) ?V { return self.table.get(id); }