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 ( 23 isSupportedType!T, 24 "'%s' is not supported by StringSerialiser".format(T.stringof)); 25 26 alias RT = Nullable!(ubyte[]); 27 28 if (isAnyNull(val)) 29 return RT.init; 30 31 return RT(val.representation.dup); 32 } 33 34 static T deserialise(T)(const (ubyte)[] bytes) 35 { 36 static assert ( 37 isSupportedType!T, 38 "'%s' is not supported by StringSerialiser".format(T.stringof)); 39 40 // Is casting good enough? Let's hope so 41 return cast(T) bytes; 42 } 43 44 static Oid oidForType(T)() 45 { 46 return Type.TEXT; 47 } 48 49 static string nameForType(T)() 50 { 51 return "TEXT"; 52 } 53 54 static void ensureExistence(T)(Connection c) 55 { 56 return; 57 } 58 } 59 60 unittest 61 { 62 import std.stdio; 63 64 writeln(" * StringSerialiser"); 65 66 string str = "1234567890qwertyuiop[]asdfghjkl;'zxcvbnm,./ščžèéêëē"; 67 auto serialised = StringSerialiser.serialise(str); 68 assert(str == StringSerialiser.deserialise!string(serialised)); 69 }