Skip to content

Commit 8b413e8

Browse files
authored
Merge pull request #9793 from ellemouton/tlvSizeBigSize
tlv: catch unhandled type in SizeBigSize
2 parents 67a40c9 + ecb9755 commit 8b413e8

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

tlv/primitive.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -375,16 +375,22 @@ func DBigSize(r io.Reader, val interface{}, buf *[8]byte, l uint64) error {
375375
return NewTypeForDecodingErr(val, "BigSize", l, 8)
376376
}
377377

378+
// constraintUint32Or64 is a type constraint for uint32 or uint64 types.
379+
type constraintUint32Or64 interface {
380+
uint32 | uint64
381+
}
382+
378383
// SizeBigSize returns a SizeFunc that can compute the length of BigSize.
379-
func SizeBigSize(val interface{}) SizeFunc {
384+
func SizeBigSize[T constraintUint32Or64](val *T) SizeFunc {
380385
var size uint64
381386

382-
if i, ok := val.(*uint32); ok {
383-
size = VarIntSize(uint64(*i))
384-
}
385-
386-
if i, ok := val.(*uint64); ok {
387+
switch i := any(val).(type) {
388+
case *uint32:
387389
size = VarIntSize(uint64(*i))
390+
case *uint64:
391+
size = VarIntSize(*i)
392+
default:
393+
panic(fmt.Sprintf("unexpected type %T for SizeBigSize", val))
388394
}
389395

390396
return func() uint64 {

tlv/record.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -273,14 +273,14 @@ func SortRecords(records []Record) {
273273
//
274274
// NOTE: for uint32, we would only gain space reduction if the encoded value is
275275
// no greater than 65535, which requires at most 3 bytes to encode.
276-
func MakeBigSizeRecord(typ Type, val interface{}) Record {
276+
func MakeBigSizeRecord[T constraintUint32Or64](typ Type, val *T) Record {
277277
var (
278278
staticSize uint64
279279
sizeFunc SizeFunc
280280
encoder Encoder
281281
decoder Decoder
282282
)
283-
switch val.(type) {
283+
switch any(val).(type) {
284284
case *uint32:
285285
sizeFunc = SizeBigSize(val)
286286
encoder = EBigSize

0 commit comments

Comments
 (0)