Debian Codegraph @

go/cbrotli/writer.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
7
8 /*
9 #include <stdbool.h>
10 #include <stddef.h>
11 #include <stdint.h>
12
13 #include <brotli/encode.h>
14
15 struct CompressStreamResult {
16 size_t bytes_consumed;
17 const uint8_t* output_data;
18 size_t output_data_size;
19 int success;
20 int has_more;
21 };
22
23 static struct CompressStreamResult CompressStream(
24 BrotliEncoderState* s, BrotliEncoderOperation op,
25 const uint8_t* data, size_t data_size) {
26 struct CompressStreamResult result;
27 size_t available_in = data_size;
28 const uint8_t* next_in = data;
29 size_t available_out = 0;
30 result.success = BrotliEncoderCompressStream(s, op,
31 &available_in, &next_in, &available_out, 0, 0) ? 1 : 0;
32 result.bytes_consumed = data_size - available_in;
33 result.output_data = 0;
34 result.output_data_size = 0;
35 if (result.success) {
36 result.output_data = BrotliEncoderTakeOutput(s, &result.output_data_size);
37 }
38 result.has_more = BrotliEncoderHasMoreOutput(s) ? 1 : 0;
39 return result;
40 }
41 */
42 import "C"
43
44 import (
45 "bytes"
46 "errors"
47 "io"
48 "runtime"
49 "unsafe"
50 )
51
52 // PreparedDictionary is a handle to native object.
53 type PreparedDictionary struct {
54 opaque *C.BrotliEncoderPreparedDictionary
55 pinner *runtime.Pinner
56 }
57
58 // DictionaryType is type for shared dictionary
59 type DictionaryType int
60
61 const (
62 // DtRaw denotes LZ77 prefix dictionary
63 DtRaw DictionaryType = 0
64 // DtSerialized denotes serialized format
65 DtSerialized DictionaryType = 1
66 )
67
68 // NewPreparedDictionary prepares dictionary data for encoder.
69 // Same instance can be used for multiple encoding sessions.
70 // Close MUST be called to free resources.
71 func NewPreparedDictionary(data []byte, dictionaryType DictionaryType, quality int) *PreparedDictionary {
72 var ptr *C.uint8_t
73 if len(data) != 0 {
74 ptr = (*C.uint8_t)(&data[0])
75 }
76 p := new(runtime.Pinner)
77 p.Pin(&data[0])
78 d := C.BrotliEncoderPrepareDictionary(C.BrotliSharedDictionaryType(dictionaryType), C.size_t(len(data)), ptr, C.int(quality), nil, nil, nil)
79 return &PreparedDictionary{
80 opaque: d,
81 pinner: p,
82 }
83 }
84
85 // Close frees C resources.
86 // IMPORTANT: calling Close until all encoders that use that dictionary are closed as well will
87 // cause crash.
88 func (p *PreparedDictionary) Close() error {
89 // C-Brotli tolerates `nil` pointer here.
90 C.BrotliEncoderDestroyPreparedDictionary(p.opaque)
91 p.opaque = nil
92 p.pinner.Unpin()
93 return nil
94 }
95
96 // WriterOptions configures Writer.
97 type WriterOptions struct {
98 // Quality controls the compression-speed vs compression-density trade-offs.
99 // The higher the quality, the slower the compression. Range is 0 to 11.
100 Quality int
101 // LGWin is the base 2 logarithm of the sliding window size.
102 // Range is 10 to 24. 0 indicates automatic configuration based on Quality.
103 LGWin int
104 // Prepared shared dictionary
105 Dictionary *PreparedDictionary
106 }
107
108 // Writer implements io.WriteCloser by writing Brotli-encoded data to an
109 // underlying Writer.
110 type Writer struct {
111 healthy bool
112 dst io.Writer
113 state *C.BrotliEncoderState
114 buf, encoded []byte
115 }
116
117 var (
118 errEncode = errors.New("cbrotli: encode error")
119 errWriterClosed = errors.New("cbrotli: Writer is closed")
120 errWriterUnhealthy = errors.New("cbrotli: Writer is unhealthy")
121 )
122
123 // NewWriter initializes new Writer instance.
124 // Close MUST be called to free resources.
125 func NewWriter(dst io.Writer, options WriterOptions) *Writer {
126 state := C.BrotliEncoderCreateInstance(nil, nil, nil)
127 healthy := state != nil
128 if C.BrotliEncoderSetParameter(
129 state, C.BROTLI_PARAM_QUALITY, (C.uint32_t)(options.Quality)) == 0 {
130 healthy = false
131 }
132 if options.LGWin > 0 {
133 if C.BrotliEncoderSetParameter(
134 state, C.BROTLI_PARAM_LGWIN, (C.uint32_t)(options.LGWin)) == 0 {
135 healthy = false
136 }
137 }
138 if options.Dictionary != nil {
139 if C.BrotliEncoderAttachPreparedDictionary(state, options.Dictionary.opaque) == 0 {
140 healthy = false
141 }
142 }
143 return &Writer{
144 healthy: healthy,
145 dst: dst,
146 state: state,
147 }
148 }
149
150 func (w *Writer) writeChunk(p []byte, op C.BrotliEncoderOperation) (n int, err error) {
151 if !w.healthy {
152 return 0, errWriterUnhealthy
153 }
154 if w.state == nil {
155 return 0, errWriterClosed
156 }
157
158 for {
159 var data *C.uint8_t
160 if len(p) != 0 {
161 data = (*C.uint8_t)(&p[0])
162 }
163 result := C.CompressStream(w.state, op, data, C.size_t(len(p)))
164 if result.success == 0 {
165 return n, errEncode
166 }
167 p = p[int(result.bytes_consumed):]
168 n += int(result.bytes_consumed)
169
170 length := int(result.output_data_size)
171 if length != 0 {
172 // It is a workaround for non-copying-wrapping of native memory.
173 // C-encoder never pushes output block longer than ((2 << 25) + 502).
174 // TODO(eustas): use natural wrapper, when it becomes available, see
175 // https://golang.org/issue/13656.
176 output := (*[1 << 30]byte)(unsafe.Pointer(result.output_data))[:length:length]
177 _, err = w.dst.Write(output)
178 if err != nil {
179 return n, err
180 }
181 }
182 if len(p) == 0 && result.has_more == 0 {
183 return n, nil
184 }
185 }
186 }
187
188 // Flush outputs encoded data for all input provided to Write. The resulting
189 // output can be decoded to match all input before Flush, but the stream is
190 // not yet complete until after Close.
191 // Flush has a negative impact on compression.
192 func (w *Writer) Flush() error {
193 _, err := w.writeChunk(nil, C.BROTLI_OPERATION_FLUSH)
194 return err
195 }
196
197 // Close flushes remaining data to the decorated writer and frees C resources.
198 func (w *Writer) Close() error {
199 // If stream is already closed, it is reported by `writeChunk`.
200 _, err := w.writeChunk(nil, C.BROTLI_OPERATION_FINISH)
201 // C-Brotli tolerates `nil` pointer here.
202 C.BrotliEncoderDestroyInstance(w.state)
203 w.state = nil
204 return err
205 }
206
207 // Write implements io.Writer. Flush or Close must be called to ensure that the
208 // encoded bytes are actually flushed to the underlying Writer.
209 func (w *Writer) Write(p []byte) (n int, err error) {
210 return w.writeChunk(p, C.BROTLI_OPERATION_PROCESS)
211 }
212
213 // Encode returns content encoded with Brotli.
214 func Encode(content []byte, options WriterOptions) ([]byte, error) {
215 var buf bytes.Buffer
216 writer := NewWriter(&buf, options)
217 _, err := writer.Write(content)
218 if closeErr := writer.Close(); err == nil {
219 err = closeErr
220 }
221 return buf.Bytes(), err
222 }