Skip to content

Commit

Permalink
Add LenSize function (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan4th authored Mar 7, 2024
1 parent d7d0c46 commit 0863cfc
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
26 changes: 26 additions & 0 deletions codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,29 @@ func TestCompactBigInt(t *testing.T) {
require.NoError(t, err)
require.EqualValues(t, encoded, rst)
}

func TestLenSize(t *testing.T) {
for _, l := range []uint32{
0,
1,
16,
64,
65,
1<<14 - 1,
1 << 14,
1 << 20,
1 << 30,
1 << 31,
1<<32 - 1,
} {
var b bytes.Buffer
n, err := EncodeLen(NewEncoder(&b), l, 1<<32-1)
require.NoError(t, err)
require.Equal(t, uint32(b.Len()), LenSize(l))
require.Equal(t, uint32(n), LenSize(l))
decoded, n, err := DecodeLen(NewDecoder(&b), 1<<32-1)
require.NoError(t, err)
require.Equal(t, l, decoded)
require.Equal(t, uint32(n), LenSize(l))
}
}
14 changes: 14 additions & 0 deletions encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,3 +311,17 @@ func EncodeStruct[V any, H EncodablePtr[V]](e *Encoder, value V) (int, error) {
}
return n, nil
}

// LenSize returns the size in bytes required to encode a length value.
func LenSize(v uint32) uint32 {
switch {
case v <= maxUint6:
return 1
case v <= maxUint14:
return 2
case v <= maxUint30:
return 4
default:
return 5
}
}

0 comments on commit 0863cfc

Please sign in to comment.