brotli/reader.go

93 lines
2.0 KiB
Go
Raw Normal View History

2019-03-07 04:08:24 +03:00
package brotli
import (
"errors"
"io"
)
type decodeError int
func (err decodeError) Error() string {
2019-03-16 03:24:40 +03:00
return "brotli: " + string(decoderErrorString(int(err)))
2019-03-07 04:08:24 +03:00
}
var errExcessiveInput = errors.New("brotli: excessive input")
var errInvalidState = errors.New("brotli: invalid state")
var errReaderClosed = errors.New("brotli: Reader is closed")
// readBufSize is a "good" buffer size that avoids excessive round-trips
// between C and Go but doesn't waste too much memory on buffering.
// It is arbitrarily chosen to be equal to the constant used in io.Copy.
const readBufSize = 32 * 1024
// NewReader initializes new Reader instance.
func NewReader(src io.Reader) *Reader {
r := new(Reader)
2019-03-16 04:00:20 +03:00
decoderStateInit(r)
2019-03-07 04:08:24 +03:00
r.src = src
r.buf = make([]byte, readBufSize)
return r
}
func (r *Reader) Read(p []byte) (n int, err error) {
2019-03-16 03:24:40 +03:00
if !decoderHasMoreOutput(r) && len(r.in) == 0 {
2019-03-07 04:08:24 +03:00
m, readErr := r.src.Read(r.buf)
if m == 0 {
// If readErr is `nil`, we just proxy underlying stream behavior.
return 0, readErr
}
r.in = r.buf[:m]
}
if len(p) == 0 {
return 0, nil
}
for {
var written uint
in_len := uint(len(r.in))
out_len := uint(len(p))
in_remaining := in_len
out_remaining := out_len
2019-03-16 03:24:40 +03:00
result := decoderDecompressStream(r, &in_remaining, &r.in, &out_remaining, &p)
2019-03-07 04:08:24 +03:00
written = out_len - out_remaining
n = int(written)
switch result {
2019-03-16 03:24:40 +03:00
case decoderResultSuccess:
2019-03-07 04:08:24 +03:00
if len(r.in) > 0 {
return n, errExcessiveInput
}
return n, nil
2019-03-16 03:24:40 +03:00
case decoderResultError:
return n, decodeError(decoderGetErrorCode(r))
case decoderResultNeedsMoreOutput:
2019-03-07 04:08:24 +03:00
if n == 0 {
return 0, io.ErrShortBuffer
}
return n, nil
2019-03-16 03:24:40 +03:00
case decoderNeedsMoreInput:
2019-03-07 04:08:24 +03:00
}
if len(r.in) != 0 {
return 0, errInvalidState
}
// Calling r.src.Read may block. Don't block if we have data to return.
if n > 0 {
return n, nil
}
// Top off the buffer.
encN, err := r.src.Read(r.buf)
if encN == 0 {
// Not enough data to complete decoding.
if err == io.EOF {
return 0, io.ErrUnexpectedEOF
}
return 0, err
}
r.in = r.buf[:encN]
}
}