Debian Codegraph @

go/cbrotli/reader.go

raw symbols SCIP
1 // Copyright 2016 Google Inc. All Rights Reserved.
2 //
3 // Distributed under MIT license.
4 // See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
5
6 // Package cbrotli compresses and decompresses data with C-Brotli library.
7 package cbrotli
8
9 /*
10 #include <stddef.h>
11 #include <stdint.h>
12
13 #include <brotli/decode.h>
14
15 static BrotliDecoderResult DecompressStream(BrotliDecoderState* s,
16 uint8_t* out, size_t out_len,
17 const uint8_t* in, size_t in_len,
18 size_t* bytes_written,
19 size_t* bytes_consumed) {
20 size_t in_remaining = in_len;
21 size_t out_remaining = out_len;
22 BrotliDecoderResult result = BrotliDecoderDecompressStream(
23 s, &in_remaining, &in, &out_remaining, &out, NULL);
24 *bytes_written = out_len - out_remaining;
25 *bytes_consumed = in_len - in_remaining;
26 return result;
27 }
28 */
29 import "C"
30
31 import (
32 "bytes"
33 "errors"
34 "io"
35 "io/ioutil"
36 "runtime"
37 )
38
39 type decodeError C.BrotliDecoderErrorCode
40
41 func (err decodeError) Error() string {
42 return "cbrotli: " +
43 C.GoString(C.BrotliDecoderErrorString(C.BrotliDecoderErrorCode(err)))
44 }
45
46 var errExcessiveInput = errors.New("cbrotli: excessive input")
47 var errInvalidState = errors.New("cbrotli: invalid state")
48 var errReaderClosed = errors.New("cbrotli: Reader is closed")
49
50 // Reader implements io.ReadCloser by reading Brotli-encoded data from an
51 // underlying Reader.
52 type Reader struct {
53 src io.Reader
54 state *C.BrotliDecoderState
55 buf []byte // scratch space for reading from src
56 in []byte // current chunk to decode; usually aliases buf
57 pinner *runtime.Pinner // raw dictionary pinner
58 }
59
60 // readBufSize is a "good" buffer size that avoids excessive round-trips
61 // between C and Go but doesn't waste too much memory on buffering.
62 // It is arbitrarily chosen to be equal to the constant used in io.Copy.
63 const readBufSize = 32 * 1024
64
65 // NewReader initializes new Reader instance.
66 // Close MUST be called to free resources.
67 func NewReader(src io.Reader) *Reader {
68 return NewReaderWithRawDictionary(src, nil)
69 }
70
71 // NewReaderWithRawDictionary initializes new Reader instance with shared dictionary.
72 // Close MUST be called to free resources.
73 func NewReaderWithRawDictionary(src io.Reader, dictionary []byte) *Reader {
74 s := C.BrotliDecoderCreateInstance(nil, nil, nil)
75 var p *runtime.Pinner
76 if dictionary != nil {
77 p = new(runtime.Pinner)
78 p.Pin(&dictionary[0])
79 // TODO(eustas): use return value
80 C.BrotliDecoderAttachDictionary(s, C.BrotliSharedDictionaryType( /* RAW */ 0),
81 C.size_t(len(dictionary)), (*C.uint8_t)(&dictionary[0]))
82 }
83 return &Reader{
84 src: src,
85 state: s,
86 buf: make([]byte, readBufSize),
87 pinner: p,
88 }
89 }
90
91 // Close implements io.Closer. Close MUST be invoked to free native resources.
92 func (r *Reader) Close() error {
93 if r.state == nil {
94 return errReaderClosed
95 }
96 // Close despite the state; i.e. there might be some unread decoded data.
97 C.BrotliDecoderDestroyInstance(r.state)
98 r.state = nil
99 if r.pinner != nil {
100 r.pinner.Unpin()
101 r.pinner = nil
102 }
103 return nil
104 }
105
106 func (r *Reader) Read(p []byte) (n int, err error) {
107 if r.state == nil {
108 return 0, errReaderClosed
109 }
110 if int(C.BrotliDecoderHasMoreOutput(r.state)) == 0 && len(r.in) == 0 {
111 m, readErr := r.src.Read(r.buf)
112 if m == 0 {
113 if readErr != io.EOF {
114 return 0, readErr
115 }
116 if int(C.BrotliDecoderIsFinished(r.state)) == 0 {
117 return 0, io.ErrUnexpectedEOF
118 }
119 return 0, io.EOF
120 }
121 r.in = r.buf[:m]
122 }
123
124 if len(p) == 0 {
125 return 0, nil
126 }
127
128 for {
129 var written, consumed C.size_t
130 var data *C.uint8_t
131 if len(r.in) != 0 {
132 data = (*C.uint8_t)(&r.in[0])
133 }
134 result := C.DecompressStream(r.state,
135 (*C.uint8_t)(&p[0]), C.size_t(len(p)),
136 data, C.size_t(len(r.in)),
137 &written, &consumed)
138 r.in = r.in[int(consumed):]
139 n = int(written)
140
141 switch result {
142 case C.BROTLI_DECODER_RESULT_SUCCESS:
143 if len(r.in) > 0 {
144 return n, errExcessiveInput
145 }
146 return n, nil
147 case C.BROTLI_DECODER_RESULT_ERROR:
148 return n, decodeError(C.BrotliDecoderGetErrorCode(r.state))
149 case C.BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:
150 if n == 0 {
151 return 0, io.ErrShortBuffer
152 }
153 return n, nil
154 case C.BROTLI_DECODER_NEEDS_MORE_INPUT:
155 }
156
157 if len(r.in) != 0 {
158 return 0, errInvalidState
159 }
160
161 // Calling r.src.Read may block. Don't block if we have data to return.
162 if n > 0 {
163 return n, nil
164 }
165
166 // Top off the buffer.
167 encN, err := r.src.Read(r.buf)
168 if encN == 0 {
169 // Not enough data to complete decoding.
170 if err == io.EOF {
171 return 0, io.ErrUnexpectedEOF
172 }
173 return 0, err
174 }
175 r.in = r.buf[:encN]
176 }
177
178 return n, nil
179 }
180
181 // Decode decodes Brotli encoded data.
182 func Decode(encodedData []byte) ([]byte, error) {
183 return DecodeWithRawDictionary(encodedData, nil)
184 }
185
186 // DecodeWithRawDictionary decodes Brotli encoded data with shared dictionary.
187 func DecodeWithRawDictionary(encodedData []byte, dictionary []byte) ([]byte, error) {
188 s := C.BrotliDecoderCreateInstance(nil, nil, nil)
189 var p *runtime.Pinner
190 if dictionary != nil {
191 p = new(runtime.Pinner)
192 p.Pin(&dictionary[0])
193 // TODO(eustas): use return value
194 C.BrotliDecoderAttachDictionary(s, C.BrotliSharedDictionaryType( /* RAW */ 0),
195 C.size_t(len(dictionary)), (*C.uint8_t)(&dictionary[0]))
196 }
197 r := &Reader{
198 src: bytes.NewReader(nil),
199 state: s,
200 buf: make([]byte, 4), // arbitrarily small but nonzero so that r.src.Read returns io.EOF
201 in: encodedData,
202 pinner: p,
203 }
204 defer r.Close()
205 out, err := ioutil.ReadAll(r)
206 if err != nil {
207 return nil, err
208 }
209 return out, nil
210 }