Skip to content

Commit 4a09c7d

Browse files
ljmf000xEAB
authored andcommitted
chore(allocator): make and makeArray should allocate aligned memory
Signed-off-by: Luís Ferreira <[email protected]>
1 parent 262645b commit 4a09c7d

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
@@ -1170,7 +1170,10 @@ auto make(T, Allocator, A...)(auto ref Allocator alloc, auto ref A args)
11701170
import std.algorithm.comparison : max;
11711171
static if (!is(T == class) && !is(T == interface) && A.length == 0
11721172
&& __traits(compiles, {T t;}) && __traits(isZeroInit, T)
1173-
&& is(typeof(alloc.allocateZeroed(size_t.max))))
1173+
&& is(typeof(alloc.allocateZeroed(size_t.max)))
1174+
&& (!is(typeof(alloc.alignedAllocate(size_t.max, uint.max))) ||
1175+
( is(typeof(alloc.alignedAllocate(size_t.max, uint.max))) && Allocator.alignment == T.alignof)
1176+
))
11741177
{
11751178
auto m = alloc.allocateZeroed(max(T.sizeof, 1));
11761179
return (() @trusted => cast(T*) m.ptr)();
@@ -1180,7 +1183,22 @@ auto make(T, Allocator, A...)(auto ref Allocator alloc, auto ref A args)
11801183
import core.internal.lifetime : emplaceRef;
11811184
import core.lifetime : emplace;
11821185

1183-
auto m = alloc.allocate(max(stateSize!T, 1));
1186+
static if (is(typeof(alloc.alignedAllocate(size_t.max, uint.max))))
1187+
{
1188+
static if(is(T == class))
1189+
{
1190+
import std.traits : classInstanceAlignment;
1191+
auto m = alloc.alignedAllocate(max(stateSize!T, 1), classInstanceAlignment!T);
1192+
}
1193+
else
1194+
{
1195+
auto m = alloc.alignedAllocate(max(stateSize!T, 1), T.alignof);
1196+
}
1197+
}
1198+
else
1199+
{
1200+
auto m = alloc.allocate(max(stateSize!T, 1));
1201+
}
11841202
if (!m.ptr) return null;
11851203

11861204
// make can only be @safe if emplace or emplaceRef is `pure`
@@ -1593,14 +1611,20 @@ T[] makeArray(T, Allocator)(auto ref Allocator alloc, size_t length)
15931611
if (overflow) return null;
15941612
}
15951613

1596-
static if (__traits(isZeroInit, T) && hasMember!(Allocator, "allocateZeroed"))
1614+
static if (__traits(isZeroInit, T)
1615+
&& hasMember!(Allocator, "allocateZeroed")
1616+
&& !hasMember!(Allocator, "alignedAllocate")
1617+
)
15971618
{
15981619
auto m = alloc.allocateZeroed(nAlloc);
15991620
return (() @trusted => cast(T[]) m)();
16001621
}
16011622
else
16021623
{
1603-
auto m = alloc.allocate(nAlloc);
1624+
static if (hasMember!(Allocator, "alignedAllocate"))
1625+
auto m = alloc.alignedAllocate(nAlloc, T.alignof);
1626+
else
1627+
auto m = alloc.allocate(nAlloc);
16041628
if (!m.ptr) return null;
16051629
alias U = Unqual!T;
16061630
return () @trusted { return cast(T[]) uninitializedFillDefault(cast(U[]) m); }();

0 commit comments

Comments
 (0)