Add function for calculating serialised/RLP length without encoding data (#775)

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

Ackn:
  Thanks to Chirag

* Add unit test
This commit is contained in:
Jordan Hrycaj 2025-02-19 18:45:58 +00:00 committed by GitHub
parent 00977da1a0
commit 8a452063e7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 0 deletions

View File

@ -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()

View File

@ -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()