Skip to content

Commit

Permalink
Add minSize helper (#103)
Browse files Browse the repository at this point in the history
Introduces `minSize` as a counterpart to `maxSize` (#20).
  • Loading branch information
etan-status authored Jan 10, 2025
1 parent 4bb7d23 commit 6106cee
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
24 changes: 24 additions & 0 deletions ssz_serialization/types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,30 @@ func fixedPortionSize*(T0: type): int {.compileTime.} =
else:
unsupported T0

func minSize*(T0: type): int {.compileTime.} =
mixin enumAllSerializedFields, toSszType

type T = type toSszType(declval T0)

when isFixedSize(T):
fixedPortionSize(T)
elif T is array|HashArray:
type E = ElemType(T)
static: doAssert not isFixedSize(E)
T.len * (offsetSize + minSize(E))
elif T is List|HashList:
0
elif T is BitList:
1 # Trailing 1-bit
elif T is object:
var res = fixedPortionSize(T)
enumAllSerializedFields(T):
when not isFixedSize(FieldType):
res += minSize(FieldType)
res
else:
unsupported T0

func maxSize*(T0: type): int {.compileTime.} =
mixin enumAllSerializedFields, toSszType

Expand Down
17 changes: 17 additions & 0 deletions tests/test_ssz_serialization.nim
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ static:
doAssert fixedPortionSize(array[SomeEnum, DistinctInt]) == 24
doAssert fixedPortionSize(array[3..5, List[byte, 256]]) == 12

doAssert minSize(array[10, bool]) == 10
doAssert minSize(array[SomeEnum, uint64]) == 24
doAssert minSize(array[SomeEnum, DistinctInt]) == 24
doAssert minSize(array[3..5, List[byte, 256]]) == 3 * 4

doAssert maxSize(array[10, bool]) == 10
doAssert maxSize(array[SomeEnum, uint64]) == 24
doAssert maxSize(array[SomeEnum, DistinctInt]) == 24
Expand All @@ -62,18 +67,30 @@ static:
doAssert isFixedSize(Simple) == true
doAssert isFixedSize(List[bool, 128]) == false

doAssert minSize(array[20, bool]) == 20
doAssert minSize(Simple) == 1 + 256 + 256
doAssert minSize(List[bool, 128]) == 0

doAssert maxSize(array[20, bool]) == 20
doAssert maxSize(Simple) == 1 + 256 + 256
doAssert maxSize(List[bool, 128]) == 128

doAssert isFixedSize(NonFixed) == false

doAssert minSize(NonFixed) == 4

doAssert maxSize(NonFixed) == 4 + 1024 * 8

doAssert minSize(array[20, BitList[24]]) == 20 * (4 + 1)
doAssert minSize(HashList[BitList[24], 20]) == 0
doAssert minSize(HashList[NonFixed, 20]) == 0

doAssert maxSize(array[20, BitList[24]]) == 20 * (4 + 4)
doAssert maxSize(HashList[BitList[24], 20]) == 20 * (4 + 4)
doAssert maxSize(HashList[NonFixed, 20]) == 20 * (4 + (4 + 1024 * 8))

reject fixedPortionSize(int)
reject minSize(int)
reject maxSize(int)

type
Expand Down

0 comments on commit 6106cee

Please sign in to comment.