diff --git a/http.go b/http.go index 1b2b92c..eb487dd 100644 --- a/http.go +++ b/http.go @@ -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 +} diff --git a/http_test.go b/http_test.go index 6740ec2..c618b65 100644 --- a/http_test.go +++ b/http_test.go @@ -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{}