reader.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package brotli
  2. import (
  3. "errors"
  4. "io"
  5. )
  6. type decodeError int
  7. func (err decodeError) Error() string {
  8. return "brotli: " + string(decoderErrorString(int(err)))
  9. }
  10. var errExcessiveInput = errors.New("brotli: excessive input")
  11. var errInvalidState = errors.New("brotli: invalid state")
  12. // readBufSize is a "good" buffer size that avoids excessive round-trips
  13. // between C and Go but doesn't waste too much memory on buffering.
  14. // It is arbitrarily chosen to be equal to the constant used in io.Copy.
  15. const readBufSize = 32 * 1024
  16. // NewReader creates a new Reader reading the given reader.
  17. func NewReader(src io.Reader) *Reader {
  18. r := new(Reader)
  19. r.Reset(src)
  20. return r
  21. }
  22. // Reset discards the Reader's state and makes it equivalent to the result of
  23. // its original state from NewReader, but writing to src instead.
  24. // This permits reusing a Reader rather than allocating a new one.
  25. // Error is always nil
  26. func (r *Reader) Reset(src io.Reader) error {
  27. decoderStateInit(r)
  28. r.src = src
  29. if r.buf == nil {
  30. r.buf = make([]byte, readBufSize)
  31. }
  32. return nil
  33. }
  34. func (r *Reader) Read(p []byte) (n int, err error) {
  35. if !decoderHasMoreOutput(r) && len(r.in) == 0 {
  36. m, readErr := r.src.Read(r.buf)
  37. if m == 0 {
  38. // If readErr is `nil`, we just proxy underlying stream behavior.
  39. return 0, readErr
  40. }
  41. r.in = r.buf[:m]
  42. }
  43. if len(p) == 0 {
  44. return 0, nil
  45. }
  46. for {
  47. var written uint
  48. in_len := uint(len(r.in))
  49. out_len := uint(len(p))
  50. in_remaining := in_len
  51. out_remaining := out_len
  52. result := decoderDecompressStream(r, &in_remaining, &r.in, &out_remaining, &p)
  53. written = out_len - out_remaining
  54. n = int(written)
  55. switch result {
  56. case decoderResultSuccess:
  57. if len(r.in) > 0 {
  58. return n, errExcessiveInput
  59. }
  60. return n, nil
  61. case decoderResultError:
  62. return n, decodeError(decoderGetErrorCode(r))
  63. case decoderResultNeedsMoreOutput:
  64. if n == 0 {
  65. return 0, io.ErrShortBuffer
  66. }
  67. return n, nil
  68. case decoderNeedsMoreInput:
  69. }
  70. if len(r.in) != 0 {
  71. return 0, errInvalidState
  72. }
  73. // Calling r.src.Read may block. Don't block if we have data to return.
  74. if n > 0 {
  75. return n, nil
  76. }
  77. // Top off the buffer.
  78. encN, err := r.src.Read(r.buf)
  79. if encN == 0 {
  80. // Not enough data to complete decoding.
  81. if err == io.EOF {
  82. return 0, io.ErrUnexpectedEOF
  83. }
  84. return 0, err
  85. }
  86. r.in = r.buf[:encN]
  87. }
  88. }