]> git.feebdaed.xyz Git - 0xmirror/quic-go.git/commitdiff
quicvarint: improve panic message for numbers larger 2^62 (#5410)
authorMarten Seemann <martenseemann@gmail.com>
Thu, 30 Oct 2025 14:24:10 +0000 (15:24 +0100)
committerGitHub <noreply@github.com>
Thu, 30 Oct 2025 14:24:10 +0000 (15:24 +0100)
quicvarint/varint.go
quicvarint/varint_test.go

index 38fe864fdf2e99ea915b72d62fc6e9c395f85a47..52fb153c7a05d9650e5811697a697a5b9d58281c 100644 (file)
@@ -20,6 +20,14 @@ const (
        maxVarInt8 = 4611686018427387903
 )
 
+type varintLengthError struct {
+       Num uint64
+}
+
+func (e *varintLengthError) Error() string {
+       return fmt.Sprintf("value doesn't fit into 62 bits: %d", e.Num)
+}
+
 // Read reads a number in the QUIC varint format from r.
 func Read(r io.ByteReader) (uint64, error) {
        firstByte, err := r.ReadByte()
@@ -118,7 +126,7 @@ func Append(b []byte, i uint64) []byte {
                        uint8(i >> 24), uint8(i >> 16), uint8(i >> 8), uint8(i),
                }...)
        }
-       panic(fmt.Sprintf("%#x doesn't fit into 62 bits", i))
+       panic(&varintLengthError{Num: i})
 }
 
 // AppendWithLen append i in the QUIC varint format with the desired length.
@@ -168,8 +176,5 @@ func Len(i uint64) int {
        }
        // Don't use a fmt.Sprintf here to format the error message.
        // The function would then exceed the inlining budget.
-       panic(struct {
-               message string
-               num     uint64
-       }{"value doesn't fit into 62 bits: ", i})
+       panic(&varintLengthError{Num: i})
 }
index 8db63f8fe020b85a128e71e63cd249519c42fafb..7c0116eedea26128cc7c57ed31004d39afa810ec 100644 (file)
@@ -2,6 +2,7 @@ package quicvarint
 
 import (
        "bytes"
+       "fmt"
        "io"
        "math/rand/v2"
        "testing"
@@ -125,7 +126,10 @@ func TestVarintEncoding(t *testing.T) {
        }
 
        t.Run("panics when given a too large number (> 62 bit)", func(t *testing.T) {
-               require.Panics(t, func() { Append(nil, maxVarInt8+1) })
+               require.PanicsWithError(t,
+                       fmt.Sprintf("value doesn't fit into 62 bits: %d", maxVarInt8+1),
+                       func() { Append(nil, maxVarInt8+1) },
+               )
        })
 }
 
@@ -203,7 +207,10 @@ func TestLen(t *testing.T) {
        }
 
        t.Run("panics on too large number", func(t *testing.T) {
-               require.Panics(t, func() { Len(maxVarInt8 + 1) })
+               require.PanicsWithError(t,
+                       fmt.Sprintf("value doesn't fit into 62 bits: %d", maxVarInt8+1),
+                       func() { Len(maxVarInt8 + 1) },
+               )
        })
 }