Implement formatting for enums

This commit is contained in:
Eugen Wissner 2018-02-01 16:29:13 +01:00
parent 048ddf21ff
commit cbc68c2c43
2 changed files with 36 additions and 1 deletions

View File

@ -737,10 +737,20 @@ private ref String printToString(string fmt, Args...)(return ref String result,
{ {
result.insertBack("null"); result.insertBack("null");
} }
else static if(is(Unqual!Arg == bool)) // Boolean else static if (is(Unqual!Arg == bool)) // Boolean
{ {
result.insertBack(args[0] ? "true" : "false"); result.insertBack(args[0] ? "true" : "false");
} }
else static if (is(Arg == enum)) // Enum
{
foreach (m; __traits(allMembers, Arg))
{
if (args[0] == __traits(getMember, Arg, m))
{
result.insertBack(m);
}
}
}
else static if (isSomeChar!Arg || isSomeString!Arg) // String or char else static if (isSomeChar!Arg || isSomeString!Arg) // String or char
{ {
result.insertBack(args[0]); result.insertBack(args[0]);
@ -810,6 +820,20 @@ package(tanya) String format(string fmt, Args...)(auto ref Args args)
return printToString!fmt(formatted, args); return printToString!fmt(formatted, args);
} }
// Enum.
@nogc nothrow pure @safe unittest
{
enum E1 : int
{
one,
two,
}
assert(format!"{}"(E1.one) == "one");
const E1 e1;
assert(format!"{}"(e1) == "one");
}
// One argument tests. // One argument tests.
@nogc pure @safe unittest @nogc pure @safe unittest
{ {

View File

@ -308,6 +308,17 @@ enum bool isClass(T) = is(T == class);
*/ */
enum bool isStruct(T) = is(T == struct); enum bool isStruct(T) = is(T == struct);
/**
* Tests whether $(D_PARAM T) is a enum.
*
* Params:
* T = A type.
*
* Returns: $(D_KEYWORD true) if $(D_PARAM T) is an enum,
* $(D_KEYWORD false) otherwise.
*/
enum bool isEnum(T) = is(T == enum);
/** /**
* Determines whether $(D_PARAM T) is a polymorphic type, i.e. a * Determines whether $(D_PARAM T) is a polymorphic type, i.e. a
* $(D_KEYWORD class) or an $(D_KEYWORD interface). * $(D_KEYWORD class) or an $(D_KEYWORD interface).