Skip to content

Commit

Permalink
add support for serializing and deserializing records
Browse files Browse the repository at this point in the history
  • Loading branch information
Elijah Stone committed Jun 30, 2021
1 parent 9ba3a85 commit 6ff46c0
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/dpq2/conv/from_d_types.d
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,35 @@ if (is(Unqual!T == Json))
return r;
}

Value toRecordValue(Value[] elements)
{
import std.array : appender;
auto buffer = appender!(ubyte[])();
buffer ~= nativeToBigEndian!int(cast(int)elements.length)[];
foreach (element; elements)
{
buffer ~= nativeToBigEndian!int(element.oidType)[];
if (element.isNull) {
buffer ~= nativeToBigEndian!int(-1)[];
} else {
buffer ~= nativeToBigEndian!int(cast(int)element.data.length)[];
buffer ~= element.data;
}
}

return Value(buffer.data.idup, OidType.Record);
}

version(unittest)
import dpq2.conv.to_d_types : as;
import dpq2.conv.to_d_types : as, deserializeRecord;

unittest
{
import std.stdio;
Value[] vals = [toValue(17.34), toValue(Nullable!long(17)), toValue(Nullable!long.init)];
Value v = vals.toRecordValue;
assert(deserializeRecord(v) == vals);
}

unittest
{
Expand Down
41 changes: 41 additions & 0 deletions src/dpq2/conv/to_d_types.d
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,47 @@ if(!is(T : const(char)[]) && !is(T == Bson) && !is(T == Nullable!R,R))
assertThrown!AE(v.as!int);
}

Value[] deserializeRecord(in Value v)
{
if(!(v.oidType == OidType.Record))
throwTypeComplaint(v.oidType, "record", __FILE__, __LINE__);

if(!(v.data.length >= uint.sizeof))
throw new AE(ET.SIZE_MISMATCH,
"Value length isn't enough to hold a size", __FILE__, __LINE__);

immutable(ubyte)[] data = v.data;
uint entries = bigEndianToNative!uint(v.data[0 .. uint.sizeof]);
data = data[uint.sizeof .. $];

Value[] ret = new Value[entries];

foreach (ref res; ret) {
if (!(data.length >= 2*int.sizeof))
throw new AE(ET.SIZE_MISMATCH,
"Value length isn't enough to hold an oid and a size", __FILE__, __LINE__);
OidType oidType = cast(OidType)bigEndianToNative!int(data[0 .. int.sizeof]);
data = data[int.sizeof .. $];
int size = bigEndianToNative!int(data[0 .. int.sizeof]);
data = data[int.sizeof .. $];

if (size == -1)
{
res = Value(null, oidType, true);
continue;
}
assert(size >= 0);
if (!(data.length >= size))
throw new AE(ET.SIZE_MISMATCH,
"Value length isn't enough to hold object body", __FILE__, __LINE__);
immutable(ubyte)[] resData = data[0 .. size];
data = data[size .. $];
res = Value(resData, oidType);
}

return ret;
}

package:

/*
Expand Down

0 comments on commit 6ff46c0

Please sign in to comment.