[Semi-OT] to!string(enumType)

Stefan Koch via Digitalmars-d digitalmars-d at puremagic.com
Thu May 18 16:42:25 PDT 2017


On Thursday, 18 May 2017 at 22:31:47 UTC, Stefan Koch wrote:

> Granted this version will result in undefined behavior if you 
> pass something like (cast(ET) 3) to it.
> But the 55x increase in compilation speed is well worth it :)

This code will replicate to!string behavior perfectly but will 
only take 30 milliseconds to compile:

string enumToString(E)(E v)
{
     static assert(is(E == enum), "emumToString is only meant for 
enums");
     mixin({
     string result = "switch(v) {\n";
     foreach(m;[__traits(allMembers, E)])
     {
         result ~= "\tcase E." ~ m ~ " :\n"
             ~ "\t\treturn \"" ~ m ~ "\";\n";
     }
     result ~= "\tdefault: break;\n";
     result ~= "}\n";
     enum headLength = E.stringof.length + "cast()".length;
     result ~= `
     enum headLength = ` ~ headLength.stringof ~ `;
     uint val = v;
     char[` ~ (headLength + 10).stringof ~ `] res = "cast(` ~ 
E.stringof ~ `)";
     uint log10Val = (val < 10) ? 0 : (val < 100) ? 1 : (val < 
1000) ? 2 : (val < 10000) ? 3
         : (val < 100000) ? 4 : (val < 1000000) ? 5 : (val < 
10000000) ? 6
         : (val < 100000000) ? 7 : (val < 1000000000) ? 8 : 9;
     foreach(i;0 .. log10Val + 1)
     {
         res[headLength + log10Val - i] = cast(char) ('0' + (val % 
10));
         val /= 10;
     }

     return res[0 .. headLength + log10Val + 1].idup;
`;
    return result;
     } ());
}




More information about the Digitalmars-d mailing list