| ... | ... | @@ -529,12 +529,13 @@ pub fn HashMapUnmanaged( |
| 529 | 529 | } |
| 530 | 530 | |
| 531 | 531 | pub fn clone(self: Self, allocator: *Allocator) !Self { |
| 532 | | // TODO this can be made more efficient by directly allocating |
| 533 | | // the memory slices and memcpying the elements. |
| 534 | | var other = Self.init(); |
| 535 | | try other.initCapacity(allocator, self.entries.len); |
| 536 | | for (self.entries.items) |entry| { |
| 537 | | other.putAssumeCapacityNoClobber(entry.key, entry.value); |
| 532 | var other: Self = .{}; |
| 533 | try other.entries.appendSlice(allocator, self.entries.items); |
| 534 | |
| 535 | if (self.index_header) |header| { |
| 536 | const new_header = try IndexHeader.alloc(allocator, header.indexes_len); |
| 537 | other.insertAllEntriesIntoNewHeader(new_header); |
| 538 | other.index_header = new_header; |
| 538 | 539 | } |
| 539 | 540 | return other; |
| 540 | 541 | } |
| ... | ... | @@ -976,6 +977,25 @@ test "ensure capacity" { |
| 976 | 977 | testing.expect(initial_capacity == map.capacity()); |
| 977 | 978 | } |
| 978 | 979 | |
| 980 | test "clone" { |
| 981 | var original = AutoHashMap(i32, i32).init(std.testing.allocator); |
| 982 | defer original.deinit(); |
| 983 | |
| 984 | // put more than `linear_scan_max` so we can test that the index header is properly cloned |
| 985 | var i: u8 = 0; |
| 986 | while (i < 10) : (i += 1) { |
| 987 | try original.putNoClobber(i, i * 10); |
| 988 | } |
| 989 | |
| 990 | var copy = try original.clone(); |
| 991 | defer copy.deinit(); |
| 992 | |
| 993 | i = 0; |
| 994 | while (i < 10) : (i += 1) { |
| 995 | testing.expect(copy.get(i).? == i * 10); |
| 996 | } |
| 997 | } |
| 998 | |
| 979 | 999 | pub fn getHashPtrAddrFn(comptime K: type) (fn (K) u32) { |
| 980 | 1000 | return struct { |
| 981 | 1001 | fn hash(key: K) u32 { |