Skip to content

Update uintsize implementation #2590

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions x/merkledb/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"errors"
"io"
"math"
"math/bits"
"sync"

"golang.org/x/exp/maps"
Expand Down Expand Up @@ -101,14 +102,10 @@ func (c *codecImpl) childSize(index byte, childEntry *child) int {

// based on the current implementation of codecImpl.encodeUint which uses binary.PutUvarint
func (*codecImpl) uintSize(value uint64) int {
// binary.PutUvarint repeatedly divides by 128 until the value is under 128,
// so count the number of times that will occur
i := 0
for value >= 0x80 {
value >>= 7
i++
}
return i + 1
if value == 0 {
return 1
}
return (bits.Len64(value) + 6) / 7
}

func (c *codecImpl) keySize(p Key) int {
Expand Down
21 changes: 17 additions & 4 deletions x/merkledb/codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,22 @@ func TestCodecDecodeKeyLengthOverflowRegression(t *testing.T) {

func TestUintSize(t *testing.T) {
c := codec.(*codecImpl)
for i := uint64(0); i < math.MaxInt16; i++ {
expectedSize := c.uintSize(i)
actualSize := binary.PutUvarint(make([]byte, binary.MaxVarintLen64), i)
require.Equal(t, expectedSize, actualSize, i)

// Test lower bound
expectedSize := c.uintSize(0)
actualSize := binary.PutUvarint(make([]byte, binary.MaxVarintLen64), 0)
require.Equal(t, expectedSize, actualSize)

// Test upper bound
expectedSize = c.uintSize(math.MaxUint64)
actualSize = binary.PutUvarint(make([]byte, binary.MaxVarintLen64), math.MaxUint64)
require.Equal(t, expectedSize, actualSize)

// Test powers of 2
for power := 0; power < 64; power++ {
n := uint64(1) << uint(power)
expectedSize := c.uintSize(n)
actualSize := binary.PutUvarint(make([]byte, binary.MaxVarintLen64), n)
require.Equal(t, expectedSize, actualSize, power)
}
}