1 module boilerplate.toString.bitflags;
2 
3 import std.typecons : BitFlags;
4 
5 void toString(T: const BitFlags!Enum, Enum)(const T field, scope void delegate(const(char)[]) sink)
6 {
7     import std.conv : to;
8     import std.traits : EnumMembers;
9 
10     bool firstMember = true;
11 
12     sink(Enum.stringof);
13     sink("(");
14 
15     static foreach (member; EnumMembers!Enum)
16     {
17         if (field & member)
18         {
19             if (firstMember)
20             {
21                 firstMember = false;
22             }
23             else
24             {
25                 sink(", ");
26             }
27 
28             enum name = to!string(member);
29 
30             sink(name);
31         }
32     }
33     sink(")");
34 }
35 
36 @("can format bitflags")
37 unittest
38 {
39     import unit_threaded.should : shouldEqual;
40 
41     string generatedString;
42 
43     scope sink = (const(char)[] fragment) {
44         generatedString ~= fragment;
45     };
46 
47     enum Enum
48     {
49         A = 1,
50         B = 2,
51     }
52 
53     const BitFlags!Enum flags = BitFlags!Enum(Enum.A, Enum.B);
54 
55     toString(flags, sink);
56 
57     generatedString.shouldEqual("Enum(A, B)");
58 }