authorgravatar for 23013931+mpfaff@users.noreply.github.comMichael Pfaff <23013931+mpfaff@users.noreply.github.com> 2023-11-21 13:23:53+00:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-11-21 13:23:53+00:00
log478c89b46f07ee6870ff1492d6a1ebeed350e6eb
treebd8d21e5aec4d939fc9cd87c06d292ea0dc1065e
parenta58ecf7b090f744975cf3816204fe0e891ff73ba
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

std.heap: Use @alignOf(T) rather than 0 if not manually overridden for alignment of MemoryPool items


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

lib/std/heap/memory_pool.zig+29-2
...@@ -42,12 +42,15 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type...@@ -42,12 +42,15 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type
42 /// as `@sizeOf(Item)` as the pool also uses the items for internal means.42 /// as `@sizeOf(Item)` as the pool also uses the items for internal means.
43 pub const item_size = @max(@sizeOf(Node), @sizeOf(Item));43 pub const item_size = @max(@sizeOf(Node), @sizeOf(Item));
4444
45 // This needs to be kept in sync with Node.
46 const node_alignment = @alignOf(*anyopaque);
47
45 /// Alignment of the memory pool items. This is not necessarily the same48 /// Alignment of the memory pool items. This is not necessarily the same
46 /// as `@alignOf(Item)` as the pool also uses the items for internal means.49 /// as `@alignOf(Item)` as the pool also uses the items for internal means.
47 pub const item_alignment = @max(@alignOf(Node), pool_options.alignment orelse 0);50 pub const item_alignment = @max(node_alignment, pool_options.alignment orelse @alignOf(Item));
4851
49 const Node = struct {52 const Node = struct {
50 next: ?*@This(),53 next: ?*align(item_alignment) @This(),
51 };54 };
52 const NodePtr = *align(item_alignment) Node;55 const NodePtr = *align(item_alignment) Node;
53 const ItemPtr = *align(item_alignment) Item;56 const ItemPtr = *align(item_alignment) Item;
...@@ -187,3 +190,27 @@ test "memory pool: growable" {...@@ -187,3 +190,27 @@ test "memory pool: growable" {
187190
188 try std.testing.expectError(error.OutOfMemory, pool.create());191 try std.testing.expectError(error.OutOfMemory, pool.create());
189}192}
193
194test "memory pool: greater than pointer default alignment" {
195 const Foo = struct {
196 data: u64 align(16),
197 };
198
199 var pool = MemoryPool(Foo).init(std.testing.allocator);
200 defer pool.deinit();
201
202 const foo: *Foo = try pool.create();
203 _ = foo;
204}
205
206test "memory pool: greater than pointer manual alignment" {
207 const Foo = struct {
208 data: u64,
209 };
210
211 var pool = MemoryPoolAligned(Foo, 16).init(std.testing.allocator);
212 defer pool.deinit();
213
214 const foo: *align(16) Foo = try pool.create();
215 _ = foo;
216}