authorgravatar for motiejus@jakstys.ltMotiejus Jakštys <motiejus@jakstys.lt> 2022-02-28 19:37:53+02:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-02-28 15:51:58-05:00
logd1a46548349a902c30057b3ba66ebad9bc25bdd2
tree1a1c3c29278ab06c204a01d2f23ddc8366146ed5
parent2dd5e8b6f865a24498da06a9a0ce3609d23662c9

std.BufSet: add clone and cloneWithAllocator

Following how ArrayList and HashMap does things. This is useful when one wants to, ahem, clone the BufSet.

1 files changed, 37 insertions(+), 0 deletions(-)

lib/std/buf_set.zig+37
......@@ -71,6 +71,26 @@ pub const BufSet = struct {
7171 return self.hash_map.allocator;
7272 }
7373
74 /// Creates a copy of this BufSet, using a specified allocator.
75 pub fn cloneWithAllocator(
76 self: *const BufSet,
77 new_allocator: Allocator,
78 ) Allocator.Error!BufSet {
79 var cloned_hashmap = try self.hash_map.cloneWithAllocator(new_allocator);
80 var cloned = BufSet{ .hash_map = cloned_hashmap };
81 var it = self.hash_map.keyIterator();
82 while (it.next()) |key_ptr| {
83 key_ptr.* = try cloned.copy(key_ptr.*);
84 }
85
86 return cloned;
87 }
88
89 /// Creates a copy of this BufSet, using the same allocator.
90 pub fn clone(self: *const BufSet) Allocator.Error!BufSet {
91 return self.cloneWithAllocator(self.allocator());
92 }
93
7494 fn free(self: *const BufSet, value: []const u8) void {
7595 self.hash_map.allocator.free(value);
7696 }
......@@ -95,3 +115,20 @@ test "BufSet" {
95115 try bufset.insert("y");
96116 try bufset.insert("z");
97117}
118
119test "BufSet clone" {
120 var original = BufSet.init(testing.allocator);
121 defer original.deinit();
122 try original.insert("x");
123
124 var cloned = try original.clone();
125 defer cloned.deinit();
126 cloned.remove("x");
127 try testing.expect(original.count() == 1);
128 try testing.expect(cloned.count() == 0);
129
130 try testing.expectError(
131 error.OutOfMemory,
132 original.cloneWithAllocator(testing.failing_allocator),
133 );
134}