diff --git a/eth/rlp/writer.nim b/eth/rlp/writer.nim index dabf22f7..811568aa 100644 --- a/eth/rlp/writer.nim +++ b/eth/rlp/writer.nim @@ -276,3 +276,17 @@ macro encodeList*(args: varargs[untyped]): seq[byte] = var `writer` = initRlpList(`listLen`) `body` move(finish(`writer`)) + + +proc getEncodedLength*[T](v: T): int = + mixin append + + const nestedListsDepth = countNestedListsDepth(T) + when nestedListsDepth > 0: + var tracker = StaticRlpLengthTracker[nestedListsDepth]() + elif nestedListsDepth == 0: + var tracker = DynamicRlpLengthTracker() + + tracker.initLengthTracker() + tracker.append(v) + return tracker.finish() diff --git a/tests/rlp/test_object_serialization.nim b/tests/rlp/test_object_serialization.nim index 31ee914a..f6388bf4 100644 --- a/tests/rlp/test_object_serialization.nim +++ b/tests/rlp/test_object_serialization.nim @@ -83,4 +83,18 @@ proc suite() = Foo.rlpFieldsCount == 3 Transaction.rlpFieldsCount == 3 + test "RLP size w/o data encoding": + var + originalBar = Bar(b: "abracadabra", + f: Foo(x: 5'u64, y: "hocus pocus", z: @[uint64 100, 200, 300])) + originalBarBytes = encode(originalBar) + + origVal = CustomSerialized(customFoo: Foo(x: 10'u64, y: "y", z: @[]), ignored: 5) + origValBytes = encode(origVal) + + check: + originalBarBytes.len == originalBar.getEncodedLength + origValBytes.len == origVal.getEncodedLength + + suite()