From 6a08e1fea4b288a619839a4a761db86c05252a08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Ludwig?= Date: Sun, 21 Oct 2018 21:37:46 +0200 Subject: [PATCH] Make get!T nogc. --- source/taggedalgebraic.d | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/source/taggedalgebraic.d b/source/taggedalgebraic.d index bd4cc79..0c1b18f 100644 --- a/source/taggedalgebraic.d +++ b/source/taggedalgebraic.d @@ -147,7 +147,7 @@ struct TaggedAlgebraic(U) if (is(U == union) || is(U == struct)) else static if (is(typeof(to!T(trustedGet!(fieldNames[i]))))) { return to!T(trustedGet!(fieldNames[i])); } else { - assert(false, "Cannot cast a " ~ m_kind.to!string + assert(false, "Cannot cast a " ~ fieldNames[i] ~ " value of type " ~ FT.stringof ~ " to " ~ T.stringof); } } @@ -168,7 +168,7 @@ struct TaggedAlgebraic(U) if (is(U == union) || is(U == struct)) else static if (is(typeof(to!T(trustedGet!(fieldNames[i]))))) { return to!T(trustedGet!(fieldNames[i])); } else { - assert(false, "Cannot cast a " ~ m_kind.to!string + assert(false, "Cannot cast a " ~ fieldNames[i] ~ " value of type" ~ FT.stringof ~ " to " ~ T.stringof); } } @@ -223,13 +223,13 @@ struct TaggedAlgebraic(U) if (is(U == union) || is(U == struct)) } /// -unittest +@safe unittest { import taggedalgebraic; struct Foo { string name; - void bar() {} + void bar() @safe {} } union Base { @@ -778,17 +778,31 @@ static if (__VERSION__ >= 2072) { ref inout(T) get(T, U)(ref inout(TaggedAlgebraic!U) ta) { import std.format : format; - assert(hasType!(T, U)(ta), () { scope (failure) assert(false); return format("Trying to get %s but have %s.", T.stringof, ta.kind); } ()); + assert(hasType!(T, U)(ta), "Type mismatch!"); return ta.trustedGet!T; } /// ditto inout(T) get(T, U)(inout(TaggedAlgebraic!U) ta) { import std.format : format; - assert(hasType!(T, U)(ta), () { scope (failure) assert(false); return format("Trying to get %s but have %s.", T.stringof, ta.kind); } ()); + assert(hasType!(T, U)(ta), "Type mismatch!"); return ta.trustedGet!T; } +@nogc @safe nothrow unittest { + struct Fields { + int a; + float b; + } + alias TA = TaggedAlgebraic!Fields; + auto ta = TA(1); + assert(ta.get!int == 1); + ta.get!int = 2; + assert(ta.get!int == 2); + ta = TA(1.0); + assert(ta.get!float == 1.0); +} + /** Calls a the given callback with the static type of the contained value.