1 module diamond.core.traits; 2 3 /// Creates a string to use with mixin that is an exact copy members of an enum 4 string createEnumAlias(T)(string name) 5 { 6 import std.traits : EnumMembers, OriginalType; 7 import std.conv : to; 8 import std..string : format; 9 import std.array : array, join; 10 import std.algorithm : map; 11 import std.meta : NoDuplicates; 12 13 return format("enum %s : %s { ", name, (OriginalType!T).stringof) ~ [NoDuplicates!(EnumMembers!T)] 14 .map! 15 ( 16 (member) 17 { 18 return format("%s = %s", to!string(member), cast(OriginalType!T)member); 19 } 20 ) 21 .array.join(",") ~ " }"; 22 } 23 24 /// Mixin template to handle fields of a type. 25 mixin template HandleFields(T, string handler) 26 { 27 string handleThem() 28 { 29 mixin HandleField!(T, [FieldNameTuple!T], handler); 30 31 return handle(); 32 } 33 } 34 35 /// Mixin template to handle a specific field of a fieldname collection. 36 mixin template HandleField 37 ( 38 T, 39 string[] fieldNames, 40 string handler 41 ) 42 { 43 import std.array : replace; 44 45 string handle() 46 { 47 string s = ""; 48 49 foreach (fieldName; fieldNames) 50 { 51 s ~= "{" ~ 52 handler 53 .replace("{{fieldName}}", fieldName) 54 .replace("{{fullName}}", T.stringof ~ "." ~ fieldName) 55 ~ "}"; 56 } 57 58 return s; 59 } 60 }