Skip to content

Commit 66e6b82

Browse files
committed
chore(allocator): make and makeArray should allocate aligned memory
Signed-off-by: Luís Ferreira <contact@lsferreira.net>
1 parent bee0ae0 commit 66e6b82

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

std/experimental/allocator/package.d

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,7 +1157,10 @@ auto make(T, Allocator, A...)(auto ref Allocator alloc, auto ref A args)
11571157
import std.algorithm.comparison : max;
11581158
static if (!is(T == class) && !is(T == interface) && A.length == 0
11591159
&& __traits(compiles, {T t;}) && __traits(isZeroInit, T)
1160-
&& is(typeof(alloc.allocateZeroed(size_t.max))))
1160+
&& is(typeof(alloc.allocateZeroed(size_t.max)))
1161+
&& (!is(typeof(alloc.alignedAllocate(size_t.max, uint.max))) ||
1162+
( is(typeof(alloc.alignedAllocate(size_t.max, uint.max))) && Allocator.alignment == T.alignof)
1163+
))
11611164
{
11621165
auto m = alloc.allocateZeroed(max(T.sizeof, 1));
11631166
return (() @trusted => cast(T*) m.ptr)();
@@ -1167,7 +1170,22 @@ auto make(T, Allocator, A...)(auto ref Allocator alloc, auto ref A args)
11671170
import core.internal.lifetime : emplaceRef;
11681171
import core.lifetime : emplace;
11691172

1170-
auto m = alloc.allocate(max(stateSize!T, 1));
1173+
static if (is(typeof(alloc.alignedAllocate(size_t.max, uint.max))))
1174+
{
1175+
static if(is(T == class))
1176+
{
1177+
import std.traits : classInstanceAlignment;
1178+
auto m = alloc.alignedAllocate(max(stateSize!T, 1), classInstanceAlignment!T);
1179+
}
1180+
else
1181+
{
1182+
auto m = alloc.alignedAllocate(max(stateSize!T, 1), T.alignof);
1183+
}
1184+
}
1185+
else
1186+
{
1187+
auto m = alloc.allocate(max(stateSize!T, 1));
1188+
}
11711189
if (!m.ptr) return null;
11721190

11731191
// make can only be @safe if emplace or emplaceRef is `pure`
@@ -1580,14 +1598,20 @@ T[] makeArray(T, Allocator)(auto ref Allocator alloc, size_t length)
15801598
if (overflow) return null;
15811599
}
15821600

1583-
static if (__traits(isZeroInit, T) && hasMember!(Allocator, "allocateZeroed"))
1601+
static if (__traits(isZeroInit, T)
1602+
&& hasMember!(Allocator, "allocateZeroed")
1603+
&& !hasMember!(Allocator, "alignedAllocate")
1604+
)
15841605
{
15851606
auto m = alloc.allocateZeroed(nAlloc);
15861607
return (() @trusted => cast(T[]) m)();
15871608
}
15881609
else
15891610
{
1590-
auto m = alloc.allocate(nAlloc);
1611+
static if (hasMember!(Allocator, "alignedAllocate"))
1612+
auto m = alloc.alignedAllocate(nAlloc, T.alignof);
1613+
else
1614+
auto m = alloc.allocate(nAlloc);
15911615
if (!m.ptr) return null;
15921616
alias U = Unqual!T;
15931617
return () @trusted { return cast(T[]) uninitializedFillDefault(cast(U[]) m); }();

0 commit comments

Comments
 (0)