1 module dpq2.conv.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, detectOidTypeFromNative!T, false, ValueFormat.BINARY);
13 }
14 
15 @property Value toValue(T)(T v, ValueFormat valueFormat = ValueFormat.BINARY) @trusted
16 if(is(T == string))
17 {
18     if(valueFormat == ValueFormat.TEXT) v = v~'\0'; // for prepareArgs only
19 
20     ubyte[] buf = cast(ubyte[]) v;
21 
22     return Value(buf, detectOidTypeFromNative!T, false, valueFormat);
23 }
24 
25 @property Value toValue(T)(T v)
26 if(is(T == ubyte[]))
27 {
28     return Value(v, detectOidTypeFromNative!T, false, ValueFormat.BINARY);
29 }
30 
31 @property Value toValue(T)(T v) @trusted
32 if(is(T == bool))
33 {
34     ubyte[] buf;
35     buf.length = 1;
36     buf[0] = (v ? 1 : 0);
37 
38     return Value(buf, detectOidTypeFromNative!T, false, ValueFormat.BINARY);
39 }
40 
41 unittest
42 {
43     {
44         Value v = toValue(cast(short) 123);
45 
46         assert(v.oidType == OidType.Int2);
47         assert(v.as!short == 123);
48     }
49 
50     {
51         Value v = toValue(-123.456);
52 
53         assert(v.oidType == OidType.Float8);
54         assert(v.as!double == -123.456);
55     }
56 
57     {
58         Value v = toValue("Test string");
59 
60         assert(v.oidType == OidType.Text);
61         assert(v.as!string == "Test string");
62     }
63 
64     {
65         ubyte[] buf = [0, 1, 2, 3, 4, 5];
66         Value v = toValue(buf.dup);
67 
68         assert(v.oidType == OidType.ByteArray);
69         assert(v.as!(const ubyte[]) == buf);
70     }
71 
72     {
73         Value t = toValue(true);
74         Value f = toValue(false);
75 
76         assert(t.as!bool == true);
77         assert(f.as!bool == false);
78     }
79 }