| ... | @@ -71,6 +71,26 @@ pub const BufSet = struct { | ... | @@ -71,6 +71,26 @@ pub const BufSet = struct { |
| 71 | return self.hash_map.allocator; | 71 | return self.hash_map.allocator; |
| 72 | } | 72 | } |
| 73 | | 73 | |
| | 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 | |
| 74 | fn free(self: *const BufSet, value: []const u8) void { | 94 | fn free(self: *const BufSet, value: []const u8) void { |
| 75 | self.hash_map.allocator.free(value); | 95 | self.hash_map.allocator.free(value); |
| 76 | } | 96 | } |
| ... | @@ -95,3 +115,20 @@ test "BufSet" { | ... | @@ -95,3 +115,20 @@ test "BufSet" { |
| 95 | try bufset.insert("y"); | 115 | try bufset.insert("y"); |
| 96 | try bufset.insert("z"); | 116 | try bufset.insert("z"); |
| 97 | } | 117 | } |
| | 118 | |
| | 119 | test "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 | } |