Round body buffer size to powers of 2

This commit is contained in:
Aliaksandr Valialkin
2015-10-26 15:40:30 +02:00
parent 658c8a1172
commit 77405b69f5
2 changed files with 33 additions and 1 deletions
+14 -1
View File
@@ -274,7 +274,7 @@ func readBodyFixedSize(r *bufio.Reader, n int, buf []byte) ([]byte, error) {
bufLen := len(buf)
bufCap := bufLen + n
if cap(buf) < bufCap {
b := make([]byte, bufLen, bufCap)
b := make([]byte, bufLen, round2(bufCap))
copy(b, buf)
buf = b
}
@@ -349,3 +349,16 @@ func parseChunkSize(r *bufio.Reader) (int, error) {
}
return n, nil
}
func round2(n int) int {
if n <= 0 {
return 0
}
n--
x := uint(0)
for n > 0 {
n >>= 1
x++
}
return 1 << x
}
+19
View File
@@ -10,6 +10,25 @@ import (
"time"
)
func TestRound2(t *testing.T) {
testRound2(t, 0, 0)
testRound2(t, 1, 1)
testRound2(t, 2, 2)
testRound2(t, 3, 4)
testRound2(t, 4, 4)
testRound2(t, 5, 8)
testRound2(t, 7, 8)
testRound2(t, 8, 8)
testRound2(t, 9, 16)
testRound2(t, 0x10001, 0x20000)
}
func testRound2(t *testing.T, n, expectedRound2 int) {
if round2(n) != expectedRound2 {
t.Fatalf("Unexpected round2(%d)=%d. Expected %d", n, round2(n), expectedRound2)
}
}
func TestResponseReadTimeout(t *testing.T) {
resp := &Response{}