Skip to content

Commit

Permalink
Fix struct copy construction in nogc_new
Browse files Browse the repository at this point in the history
  • Loading branch information
LunaTheFoxgirl committed Jul 27, 2024
1 parent d9b310f commit 943df69
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion source/numem/mem/package.d
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ version(Have_tinyd_rt) {
auto __gc_new(T, Args...)(Args args) {
return new T(args);
}
} else import std.conv : emplace;
} else {
import std.conv : emplace;
import core.lifetime : copyEmplace;
}

nothrow @nogc:

Expand Down Expand Up @@ -110,6 +113,8 @@ T* nogc_new(T, Args...)(Args args) if (is(T == struct)) {
T* obj = cast(T*)rawMemory;
static if (hasUDA!(T, AllowInitEmpty) && args.length == 0) {
nogc_emplace!T(obj);
} static if (args.length == 1 && is(typeof(args[0]) == T)) {
nogc_copyemplace(obj, args[0]);
} else {
nogc_emplace!T(obj, args);
}
Expand All @@ -121,6 +126,20 @@ T* nogc_new(T, Args...)(Args args) if (is(T == struct)) {
}
}

@("Alloc struct")
unittest {
struct A {
int x;
}

A a = A(128);
auto b = nogc_new!A(a);
b.x = 42;

assert(a.x == 128);
assert(b.x == 42);
}

/**
Allocates a new class on the heap.
Immediately exits the application if out of memory.
Expand Down Expand Up @@ -267,6 +286,11 @@ void nogc_delete(T)(ref T obj_) {
}
}

auto nogc_copyemplace(T)(T* target, ref T source) {
alias t = typeof(&copyEmplace!(T, T));
return assumeNothrowNoGC!t(&copyEmplace!(T, T))(source, *target);
}

/**
nogc emplace function
*/
Expand Down

0 comments on commit 943df69

Please sign in to comment.