1 /// 2 module dpq.serialisers..string; 3 4 import dpq.serialisation; 5 import dpq.connection : Connection; 6 import std.string : representation; 7 import std.traits; 8 import std.conv : to; 9 import std.typecons : Nullable; 10 import libpq.libpq : Oid; 11 import dpq.value : Type; 12 13 struct StringSerialiser 14 { 15 static bool isSupportedType(T)() 16 { 17 return isSomeString!T; 18 } 19 20 static Nullable!(ubyte[]) serialise(T)(T val) 21 { 22 static assert(isSupportedType!T, "'%s' is not supported by StringSerialiser".format(T.stringof)); 23 24 alias RT = Nullable!(ubyte[]); 25 26 if (isAnyNull(val)) 27 return RT.init; 28 29 return RT(val.representation.dup); 30 } 31 32 static T deserialise(T)(const(ubyte)[] bytes) 33 { 34 static assert(isSupportedType!T, "'%s' is not supported by StringSerialiser".format(T.stringof)); 35 36 // Is casting good enough? Let's hope so 37 return cast(T)bytes; 38 } 39 40 static Oid oidForType(T)() 41 { 42 return Type.TEXT; 43 } 44 45 static string nameForType(T)() 46 { 47 return "TEXT"; 48 } 49 50 static void ensureExistence(T)(Connection c) 51 { 52 return; 53 } 54 } 55 56 unittest 57 { 58 import std.stdio; 59 60 writeln(" * StringSerialiser"); 61 62 string str = "1234567890qwertyuiop[]asdfghjkl;'zxcvbnm,./ščžèéêëē"; 63 auto serialised = StringSerialiser.serialise(str); 64 assert(str == StringSerialiser.deserialise!string(serialised.get)); 65 }