Enum

Template housing optimised functions to get the string name of an enum member, or the enum member of a name string.

std.conv.to is typically the go-to for this job; however it quickly bloats the binary and is not performant on larger enums.

@safe
template Enum (
E
) if (
is(E == enum)
) {}

Members

Functions

fromString
E fromString(string enumstring)

Takes the member of an enum by string and returns that enum member.

toString
string toString(E value)

The inverse of fromString, this function takes an enum member value and returns its string identifier.

Parameters

E

enum to base this template on.

Examples

import std.conv : ConvException;
import std.exception  : assertThrown;

{
    enum T
    {
        UNSET,
        QUERY,
        PRIVMSG,
        RPL_ENDOFMOTD
    }

    static assert(Enum!T.fromString("QUERY") == T.QUERY);
    static assert(Enum!T.fromString("PRIVMSG") == T.PRIVMSG);
    static assert(Enum!T.fromString("RPL_ENDOFMOTD") == T.RPL_ENDOFMOTD);
    static assert(Enum!T.fromString("UNSET") == T.UNSET);
    assertThrown!ConvException(Enum!T.fromString("DOESNTEXIST"));  // needs @system

    static assert(Enum!T.toString(T.QUERY) == "QUERY");
    static assert(Enum!T.toString(T.PRIVMSG) == "PRIVMSG");
    static assert(Enum!T.toString(T.RPL_ENDOFMOTD) == "RPL_ENDOFMOTD");
    static assert(Enum!T.toString(cast(T)1234) == "cast(T)1234");
}
{
    enum E
    {
        abc = "abc",
        def = "def",
        ghi = "ghi",
    }

    static assert(Enum!E.fromString("abc") == E.abc);
    static assert(Enum!E.fromString("def") == E.def);
    static assert(Enum!E.fromString("ghi") == E.ghi);
    assertThrown!ConvException(Enum!E.fromString("jkl"));  // as above

    static assert(Enum!E.toString(E.abc) == "abc");
    static assert(Enum!E.toString(E.def) == "def");
    static assert(Enum!E.toString(E.ghi) == "ghi");
    static assert(Enum!E.toString(cast(E)"jkl") == "cast(E)\"jkl\"");
}

Meta