Skip to content

Commit

Permalink
Add function for calculating serialised/RLP length without encoding d…
Browse files Browse the repository at this point in the history
…ata (#775)

* Add function for calculating serialised/RLP length without encoding data

Ackn:
  Thanks to Chirag

* Add unit test
  • Loading branch information
mjfh authored Feb 19, 2025
1 parent 00977da commit 8a45206
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions eth/rlp/writer.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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()
14 changes: 14 additions & 0 deletions tests/rlp/test_object_serialization.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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()

0 comments on commit 8a45206

Please sign in to comment.