Phobos' std.conv.to-conversion from enum to string doesn't scale beyond hundreds of enumerators
Per Nordlöw
per.nordlow at gmail.com
Thu Jun 21 22:46:23 UTC 2018
I've discovered the annoying fact that std.conv.to doesn't scale
for enum to string conversion when the enum has hundreds of
members. This because of a call to `NoDuplicates` which has (at
least) O(n*log(n) time and space complexity.
So I've come up with
/** Faster implementation of `std.conv.to`.
*/
string toString(T)(T value) @safe pure nothrow @nogc
if (is(T == enum))
{
final switch (value)
{
static foreach (member; __traits(allMembers, T))
{
case __traits(getMember, T, member):
return member;
}
}
}
///
@safe pure nothrow @nogc unittest
{
enum E { unknown, x, y, z, }
assert(E.x.toString == "x");
assert(E.y.toString == "y");
assert(E.z.toString == "z");
}
The question know is: How do I make this support enums with
enumerator aliases without needing to call `NoDuplicates`?
For instance, this should work
///
@safe pure nothrow @nogc unittest
{
enum E { unknown, x, y, z, z_ = z, }
assert(E.x.toString == "x");
assert(E.y.toString == "y");
assert(E.z.toString == "z");
assert(E.z_.toString == "z");
}
More information about the Digitalmars-d
mailing list