1 module lantern.util; 2 3 import core.time; 4 5 import std.typecons; 6 7 template MemberTypeOf(T) 8 { 9 alias MemberTypeOf(string name) = typeof(__traits(getMember, T.init, name)); 10 } 11 12 template FieldTypeOf(T) 13 { 14 alias FieldTypeOf(string name) = typeof({ 15 auto value = __traits(getMember, T.init, name); 16 return value; 17 }()); 18 } 19 20 unittest 21 { 22 struct Test 23 { 24 int n; 25 26 float test() 27 { 28 return 1.0f; 29 } 30 } 31 32 alias MemberType = MemberTypeOf!Test; 33 alias FieldType = FieldTypeOf!Test; 34 35 static assert(is(MemberType!"n" == int)); 36 static assert(is(FieldType!"n" == int)); 37 38 alias F = float(); 39 static assert(is(MemberType!"test" == F)); 40 static assert(is(FieldType!"test" == float)); 41 } 42 43 Nullable!Duration toDuration()(Nullable!long d) 44 { 45 if (d.isNull) 46 return Nullable!Duration.init; 47 48 return nullable(d.get().hnsecs); 49 } 50 51 unittest 52 { 53 Nullable!long a; 54 Nullable!long b = 1.hnsecs.total!"hnsecs"; 55 Nullable!long c = 10.seconds.total!"hnsecs"; 56 57 assert(a.toDuration().isNull); 58 assert(b.toDuration() == nullable(1.hnsecs)); 59 assert(c.toDuration() == nullable(10.seconds)); 60 } 61 62 Nullable!Duration toDuration()(Nullable!real d) 63 { 64 if (d.isNull) 65 return Nullable!Duration.init; 66 67 import std.math : round; 68 69 return nullable((cast(long) round(d.get())).hnsecs); 70 } 71 72 unittest 73 { 74 Nullable!real a; 75 Nullable!real b = 1.hnsecs.total!"hnsecs"; 76 Nullable!real c = 10.seconds.total!"hnsecs"; 77 78 assert(a.toDuration().isNull); 79 assert(b.toDuration() == nullable(1.hnsecs)); 80 assert(c.toDuration() == nullable(10.seconds)); 81 }