1 module dpq2.types.from_d_types; 2 3 @safe: 4 5 import dpq2; 6 import std.bitmanip: nativeToBigEndian; 7 import std.traits: isNumeric; 8 9 @property Value toValue(T)(T v) 10 if(isNumeric!(T)) 11 { 12 return Value(v.nativeToBigEndian.dup, detectOidType!T, false, ValueFormat.BINARY); 13 } 14 15 unittest 16 { 17 { 18 Value v = toValue(cast(short) 123); 19 20 assert(v.oidType == OidType.Int2); 21 assert(v.as!short == 123); 22 } 23 24 { 25 Value v = toValue(-123.456); 26 27 assert(v.oidType == OidType.Float8); 28 assert(v.as!double == -123.456); 29 } 30 } 31 32 @property Value toValue(T)(T v, ValueFormat valueFormat = ValueFormat.BINARY) @trusted 33 if(is(T == string)) 34 { 35 if(valueFormat == ValueFormat.TEXT) v = v~'\0'; // for prepareArgs only 36 37 ubyte[] buf = cast(ubyte[]) v; 38 39 return Value(buf, detectOidType!T, false, valueFormat); 40 } 41 42 unittest 43 { 44 Value v = toValue("Test string"); 45 46 assert(v.oidType == OidType.Text); 47 assert(v.as!string == "Test string"); 48 } 49 50 private OidType detectOidType(T)() 51 { 52 with(OidType) 53 { 54 static if(is(T == string)){ return Text; } else 55 static if(is(T == short)){ return Int2; } else 56 static if(is(T == int)){ return Int4; } else 57 static if(is(T == long)){ return Int8; } else 58 static if(is(T == float)){ return Float4; } else 59 static if(is(T == double)){ return Float8; } else 60 61 static assert(false, "Unsupported D type: "~T.stringof); 62 } 63 }