authorgravatar for thatlemon@gmail.comLemonBoy <thatlemon@gmail.com> 2020-09-02 10:51:15+02:00
committergravatar for thatlemon@gmail.comLemonBoy <thatlemon@gmail.com> 2020-09-02 11:11:57+02:00
log5f31d54064b204910c18667d0b68b8bf2b57cffb
treed13c9564e976e8b34aea6c196410830f792370c5
parent73a8c9beaa63c48b6ddaeec8d2a67b239f0dec92

std: ArrayList.initCapacity now respects the specified cap

Don't use the user-supplied cap as starting point for a resize. Doing so overallocates memory and thus negates the whole point of specifying a precise cap value.

1 files changed, 10 insertions(+), 2 deletions(-)

lib/std/array_list.zig+10-2
...@@ -46,7 +46,11 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {...@@ -46,7 +46,11 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
46 /// Deinitialize with `deinit` or use `toOwnedSlice`.46 /// Deinitialize with `deinit` or use `toOwnedSlice`.
47 pub fn initCapacity(allocator: *Allocator, num: usize) !Self {47 pub fn initCapacity(allocator: *Allocator, num: usize) !Self {
48 var self = Self.init(allocator);48 var self = Self.init(allocator);
49 try self.ensureCapacity(num);49
50 const new_memory = try self.allocator.allocAdvanced(T, alignment, num, .at_least);
51 self.items.ptr = new_memory.ptr;
52 self.capacity = new_memory.len;
53
50 return self;54 return self;
51 }55 }
5256
...@@ -366,7 +370,11 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ...@@ -366,7 +370,11 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
366 /// Deinitialize with `deinit` or use `toOwnedSlice`.370 /// Deinitialize with `deinit` or use `toOwnedSlice`.
367 pub fn initCapacity(allocator: *Allocator, num: usize) !Self {371 pub fn initCapacity(allocator: *Allocator, num: usize) !Self {
368 var self = Self{};372 var self = Self{};
369 try self.ensureCapacity(allocator, num);373
374 const new_memory = try self.allocator.allocAdvanced(T, alignment, num, .at_least);
375 self.items.ptr = new_memory.ptr;
376 self.capacity = new_memory.len;
377
370 return self;378 return self;
371 }379 }
372380