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