aboutsummaryrefslogtreecommitdiff
path: root/lib/std/buf_set.zig
diff options
context:
space:
mode:
authorAndrew Kelley <andrew@ziglang.org>2022-07-01 15:52:54 -0700
committerAndrew Kelley <andrew@ziglang.org>2022-07-01 15:52:54 -0700
commitc89dd15e1be4959800dc7092d7dd4375253db7bc (patch)
treeca184ae53592efa21e67128a5f891d642d7f1118 /lib/std/buf_set.zig
parent5466e87fce581f2ef90ac23bb80b1dbc05836fc6 (diff)
parent2360f8c490f3ec684ed64ff28e8c1fade249070b (diff)
downloadzig-c89dd15e1be4959800dc7092d7dd4375253db7bc.tar.gz
zig-c89dd15e1be4959800dc7092d7dd4375253db7bc.zip
Merge remote-tracking branch 'origin/master' into llvm14
Diffstat (limited to 'lib/std/buf_set.zig')
-rw-r--r--lib/std/buf_set.zig50
1 files changed, 50 insertions, 0 deletions
diff --git a/lib/std/buf_set.zig b/lib/std/buf_set.zig
index e68b24fbcc..9d6d7ed1e6 100644
--- a/lib/std/buf_set.zig
+++ b/lib/std/buf_set.zig
@@ -71,6 +71,26 @@ pub const BufSet = struct {
return self.hash_map.allocator;
}
+ /// Creates a copy of this BufSet, using a specified allocator.
+ pub fn cloneWithAllocator(
+ self: *const BufSet,
+ new_allocator: Allocator,
+ ) Allocator.Error!BufSet {
+ var cloned_hashmap = try self.hash_map.cloneWithAllocator(new_allocator);
+ var cloned = BufSet{ .hash_map = cloned_hashmap };
+ var it = cloned.hash_map.keyIterator();
+ while (it.next()) |key_ptr| {
+ key_ptr.* = try cloned.copy(key_ptr.*);
+ }
+
+ return cloned;
+ }
+
+ /// Creates a copy of this BufSet, using the same allocator.
+ pub fn clone(self: *const BufSet) Allocator.Error!BufSet {
+ return self.cloneWithAllocator(self.allocator());
+ }
+
fn free(self: *const BufSet, value: []const u8) void {
self.hash_map.allocator.free(value);
}
@@ -95,3 +115,33 @@ test "BufSet" {
try bufset.insert("y");
try bufset.insert("z");
}
+
+test "BufSet clone" {
+ var original = BufSet.init(testing.allocator);
+ defer original.deinit();
+ try original.insert("x");
+
+ var cloned = try original.clone();
+ defer cloned.deinit();
+ cloned.remove("x");
+ try testing.expect(original.count() == 1);
+ try testing.expect(cloned.count() == 0);
+
+ try testing.expectError(
+ error.OutOfMemory,
+ original.cloneWithAllocator(testing.failing_allocator),
+ );
+}
+
+test "BufSet.clone with arena" {
+ var allocator = std.testing.allocator;
+ var arena = std.heap.ArenaAllocator.init(allocator);
+ defer arena.deinit();
+
+ var buf = BufSet.init(allocator);
+ defer buf.deinit();
+ try buf.insert("member1");
+ try buf.insert("member2");
+
+ _ = try buf.cloneWithAllocator(arena.allocator());
+}