Skip to content
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
18 changes: 12 additions & 6 deletions tlv/primitive.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,16 +375,22 @@ func DBigSize(r io.Reader, val interface{}, buf *[8]byte, l uint64) error {
return NewTypeForDecodingErr(val, "BigSize", l, 8)
}

// constraintUint32Or64 is a type constraint for uint32 or uint64 types.
type constraintUint32Or64 interface {
uint32 | uint64
}

// SizeBigSize returns a SizeFunc that can compute the length of BigSize.
func SizeBigSize(val interface{}) SizeFunc {
func SizeBigSize[T constraintUint32Or64](val *T) SizeFunc {
var size uint64

if i, ok := val.(*uint32); ok {
size = VarIntSize(uint64(*i))
}

if i, ok := val.(*uint64); ok {
switch i := any(val).(type) {
case *uint32:
size = VarIntSize(uint64(*i))
case *uint64:
size = VarIntSize(*i)
default:
panic(fmt.Sprintf("unexpected type %T for SizeBigSize", val))
}

return func() uint64 {
Expand Down
4 changes: 2 additions & 2 deletions tlv/record.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,14 +273,14 @@ func SortRecords(records []Record) {
//
// NOTE: for uint32, we would only gain space reduction if the encoded value is
// no greater than 65535, which requires at most 3 bytes to encode.
func MakeBigSizeRecord(typ Type, val interface{}) Record {
func MakeBigSizeRecord[T constraintUint32Or64](typ Type, val *T) Record {
var (
staticSize uint64
sizeFunc SizeFunc
encoder Encoder
decoder Decoder
)
switch val.(type) {
switch any(val).(type) {
case *uint32:
sizeFunc = SizeBigSize(val)
encoder = EBigSize
Expand Down
Loading