wrap objects and tuples in lists by default

This commit is contained in:
Zahary Karadjov 2018-03-13 18:16:53 +02:00
parent 34f1bee50d
commit 0b516cb2b6
3 changed files with 21 additions and 4 deletions

12
rlp.nim
View File

@ -279,9 +279,17 @@ proc read*[E](rlp: var Rlp, T: typedesc[seq[E]]): T =
for elem in rlp: for elem in rlp:
result.add rlp.read(E) result.add rlp.read(E)
proc read*(rlp: var Rlp, T: typedesc[object|tuple]): T = proc read*(rlp: var Rlp, T: typedesc[object|tuple],
wrappedInList = wrapObjectsInList): T =
mixin enumerateRlpFields, read mixin enumerateRlpFields, read
if wrappedInList:
var
payloadOffset = rlp.payloadOffset()
payloadEnd = rlp.position + payloadOffset + rlp.payloadBytesCount()
rlp.position += payloadOffset
template op(field) = template op(field) =
field = rlp.read(type(field)) field = rlp.read(type(field))
@ -306,7 +314,7 @@ proc decode*(bytes: openarray[byte]): RlpNode =
bytesCopy = @bytes bytesCopy = @bytes
rlp = rlpFromBytes initBytesRange(bytesCopy) rlp = rlpFromBytes initBytesRange(bytesCopy)
return rlp.toNodes return rlp.toNodes
template decode*(bytes: BytesRange, T: typedesc): untyped = template decode*(bytes: BytesRange, T: typedesc): untyped =
var rlp = rlpFromBytes bytes var rlp = rlpFromBytes bytes

View File

@ -25,6 +25,9 @@ type
Integer* = SomeOrdinal or IntLike or uint or uint64 Integer* = SomeOrdinal or IntLike or uint or uint64
const
wrapObjectsInList* = true
proc bytesNeeded(num: Integer): int = proc bytesNeeded(num: Integer): int =
var n = num var n = num
while n != 0: while n != 0:
@ -172,8 +175,15 @@ proc append*[T](self; list: seq[T]) =
for i in 0 ..< list.len: for i in 0 ..< list.len:
self.append list[i] self.append list[i]
proc append*(self; data: object|tuple) = proc append*(self; data: object|tuple, wrapInList = wrapObjectsInList) =
mixin enumerateRlpFields, append mixin enumerateRlpFields, append
if wrapInList:
var fieldsCount = 0
template countFields(x) = inc fieldsCount
enumerateRlpFields(data, countFields)
self.startList(fieldsCount)
template op(x) = append(self, x) template op(x) = append(self, x)
enumerateRlpFields(data, op) enumerateRlpFields(data, op)

View File

@ -30,7 +30,6 @@ test "encoding and decoding an object":
f: Foo(x: 5'u64, y: "hocus pocus", z: @[100, 200, 300])) f: Foo(x: 5'u64, y: "hocus pocus", z: @[100, 200, 300]))
var bytes = encode(originalBar) var bytes = encode(originalBar)
var r = rlpFromBytes(bytes) var r = rlpFromBytes(bytes)
var restoredBar = r.read(Bar) var restoredBar = r.read(Bar)