From 889c65bae695e88561a97b52fb9e029daac02c55 Mon Sep 17 00:00:00 2001 From: Sebastian Schepens Date: Mon, 22 Feb 2016 14:36:58 -0300 Subject: [PATCH] Added BodyInflate and WriteInflate to match BodyGunzip and WriteGunzip --- compress.go | 17 +++++++++++++++++ http.go | 32 ++++++++++++++++++-------------- 2 files changed, 35 insertions(+), 14 deletions(-) diff --git a/compress.go b/compress.go index 5b9e58d..c3b81cf 100644 --- a/compress.go +++ b/compress.go @@ -171,6 +171,23 @@ func WriteGunzip(w io.Writer, p []byte) (int, error) { return nn, err } +// WriteInflate writes inflated p to w and returns the number of uncompressed +// bytes written to w. +func WriteInflate(w io.Writer, p []byte) (int, error) { + r := &byteSliceReader{p} + zr, err := acquireFlateReader(r) + if err != nil { + return 0, err + } + n, err := copyZeroAlloc(w, zr) + releaseFlateReader(zr) + nn := int(n) + if int64(nn) != n { + return 0, fmt.Errorf("too much data inflated: %d", n) + } + return nn, err +} + // AppendGunzipBytes append gunzipped src to dst and returns the resulting dst. func AppendGunzipBytes(dst, src []byte) ([]byte, error) { w := &byteSliceWriter{dst} diff --git a/http.go b/http.go index d8685c5..47f8f52 100644 --- a/http.go +++ b/http.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "mime/multipart" "os" "sync" @@ -285,26 +284,31 @@ func gunzipData(p []byte) ([]byte, error) { return bb.B, nil } -// BodyInflate returns un-deflated body data. +// BodyInflate returns inflated body data. // // This method may be used if the response header contains -// 'Content-Encoding: deflate' for reading un-deflated response body. +// 'Content-Encoding: deflate' for reading inflated request body. +// Use Body for reading deflated request body. +func (resp *Request) BodyInflate() ([]byte, error) { + return inflateData(resp.Body()) +} + +// BodyInflate returns inflated body data. +// +// This method may be used if the response header contains +// 'Content-Encoding: deflate' for reading inflated response body. // Use Body for reading deflated response body. func (resp *Response) BodyInflate() ([]byte, error) { - // Do not care about memory allocations here, - // since flate is slow and generates a lot of memory allocations - // by itself. - r := bytes.NewBuffer(resp.body) - zr, err := acquireFlateReader(r) + return inflateData(resp.Body()) +} + +func inflateData(p []byte) ([]byte, error) { + var bb ByteBuffer + _, err := WriteInflate(&bb, p) if err != nil { return nil, err } - b, err := ioutil.ReadAll(zr) - releaseFlateReader(zr) - if err != nil { - return nil, err - } - return b, nil + return bb.B, nil } // BodyWriteTo writes request body to w.