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

This commit is contained in:
Michael Pfaff 2023-11-21 13:23:53 +00:00 committed by GitHub
parent a58ecf7b09
commit 478c89b46f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -42,12 +42,15 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type
/// as `@sizeOf(Item)` as the pool also uses the items for internal means. /// as `@sizeOf(Item)` as the pool also uses the items for internal means.
pub const item_size = @max(@sizeOf(Node), @sizeOf(Item)); pub const item_size = @max(@sizeOf(Node), @sizeOf(Item));
// This needs to be kept in sync with Node.
const node_alignment = @alignOf(*anyopaque);
/// Alignment of the memory pool items. This is not necessarily the same /// Alignment of the memory pool items. This is not necessarily the same
/// as `@alignOf(Item)` as the pool also uses the items for internal means. /// as `@alignOf(Item)` as the pool also uses the items for internal means.
pub const item_alignment = @max(@alignOf(Node), pool_options.alignment orelse 0); pub const item_alignment = @max(node_alignment, pool_options.alignment orelse @alignOf(Item));
const Node = struct { const Node = struct {
next: ?*@This(), next: ?*align(item_alignment) @This(),
}; };
const NodePtr = *align(item_alignment) Node; const NodePtr = *align(item_alignment) Node;
const ItemPtr = *align(item_alignment) Item; const ItemPtr = *align(item_alignment) Item;
@ -187,3 +190,27 @@ test "memory pool: growable" {
try std.testing.expectError(error.OutOfMemory, pool.create()); try std.testing.expectError(error.OutOfMemory, pool.create());
} }
test "memory pool: greater than pointer default alignment" {
const Foo = struct {
data: u64 align(16),
};
var pool = MemoryPool(Foo).init(std.testing.allocator);
defer pool.deinit();
const foo: *Foo = try pool.create();
_ = foo;
}
test "memory pool: greater than pointer manual alignment" {
const Foo = struct {
data: u64,
};
var pool = MemoryPoolAligned(Foo, 16).init(std.testing.allocator);
defer pool.deinit();
const foo: *align(16) Foo = try pool.create();
_ = foo;
}