authorgravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2020-07-06 16:51:53+03:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2020-07-06 16:51:53+03:00
log485231deaef9b12e013d423facdef1624f16014b
tree0cf50809b974d64abee76366487f1266b4aa8a6a
parentabcd4ea5d88541a21062e63fe427b2d2ea16a041
signaturelock-open Commit is signed but in an unrecognized format.

fix HashMap.clone()


1 files changed, 26 insertions(+), 6 deletions(-)

lib/std/hash_map.zig+26-6
...@@ -529,12 +529,13 @@ pub fn HashMapUnmanaged(...@@ -529,12 +529,13 @@ pub fn HashMapUnmanaged(
529 }529 }
530530
531 pub fn clone(self: Self, allocator: *Allocator) !Self {531 pub fn clone(self: Self, allocator: *Allocator) !Self {
532 // TODO this can be made more efficient by directly allocating532 var other: Self = .{};
533 // the memory slices and memcpying the elements.533 try other.entries.appendSlice(allocator, self.entries.items);
534 var other = Self.init();534
535 try other.initCapacity(allocator, self.entries.len);535 if (self.index_header) |header| {
536 for (self.entries.items) |entry| {536 const new_header = try IndexHeader.alloc(allocator, header.indexes_len);
537 other.putAssumeCapacityNoClobber(entry.key, entry.value);537 other.insertAllEntriesIntoNewHeader(new_header);
538 other.index_header = new_header;
538 }539 }
539 return other;540 return other;
540 }541 }
...@@ -976,6 +977,25 @@ test "ensure capacity" {...@@ -976,6 +977,25 @@ test "ensure capacity" {
976 testing.expect(initial_capacity == map.capacity());977 testing.expect(initial_capacity == map.capacity());
977}978}
978979
980test "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
979pub fn getHashPtrAddrFn(comptime K: type) (fn (K) u32) {999pub fn getHashPtrAddrFn(comptime K: type) (fn (K) u32) {
980 return struct {1000 return struct {
981 fn hash(key: K) u32 {1001 fn hash(key: K) u32 {