forked from quic-go/quic-go
quicvarint: refactor ifs into a switch statement (#5012)
No functional change expected.
This commit is contained in:
@@ -125,17 +125,18 @@ func AppendWithLen(b []byte, i uint64, length int) []byte {
|
||||
if l > length {
|
||||
panic(fmt.Sprintf("cannot encode %d in %d bytes", i, length))
|
||||
}
|
||||
if length == 2 {
|
||||
switch length {
|
||||
case 2:
|
||||
b = append(b, 0b01000000)
|
||||
} else if length == 4 {
|
||||
case 4:
|
||||
b = append(b, 0b10000000)
|
||||
} else if length == 8 {
|
||||
case 8:
|
||||
b = append(b, 0b11000000)
|
||||
}
|
||||
for j := 1; j < length-l; j++ {
|
||||
for range length - l - 1 {
|
||||
b = append(b, 0)
|
||||
}
|
||||
for j := 0; j < l; j++ {
|
||||
for j := range l {
|
||||
b = append(b, uint8(i>>(8*(l-1-j))))
|
||||
}
|
||||
return b
|
||||
|
||||
@@ -253,7 +253,28 @@ func benchmarkAppend(b *testing.B, inputs []benchmarkValue) {
|
||||
buf = Append(buf, inputs[index].v)
|
||||
|
||||
if !bytes.Equal(buf, inputs[index].b) {
|
||||
b.Fatalf("expected to write %v, wrote %v", inputs[i].b, buf)
|
||||
b.Fatalf("expected to write %v, wrote %v", inputs[index].b, buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAppendWithLen(b *testing.B) {
|
||||
b.Run("1-byte", func(b *testing.B) { benchmarkAppendWithLen(b, randomValues(min(b.N, 1024), maxVarInt1)) })
|
||||
b.Run("2-byte", func(b *testing.B) { benchmarkAppendWithLen(b, randomValues(min(b.N, 1024), maxVarInt2)) })
|
||||
b.Run("4-byte", func(b *testing.B) { benchmarkAppendWithLen(b, randomValues(min(b.N, 1024), maxVarInt4)) })
|
||||
b.Run("8-byte", func(b *testing.B) { benchmarkAppendWithLen(b, randomValues(min(b.N, 1024), maxVarInt8)) })
|
||||
}
|
||||
|
||||
func benchmarkAppendWithLen(b *testing.B, inputs []benchmarkValue) {
|
||||
buf := make([]byte, 8)
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
buf = buf[:0]
|
||||
index := i % 1024
|
||||
buf = AppendWithLen(buf, inputs[index].v, len(inputs[index].b))
|
||||
|
||||
if !bytes.Equal(buf, inputs[index].b) {
|
||||
b.Fatalf("expected to write %v, wrote %v", inputs[index].b, buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user