Debian Codegraph @

writer.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 package gozstd
2
3 /*
4 #cgo CFLAGS: -O3
5
6 #define ZSTD_STATIC_LINKING_ONLY
•7 #include <zstd.h>
8 #include <zstd_errors.h>
9
10 #include <stdlib.h> // for malloc/free
11 #include <stdint.h> // for uintptr_t
12
13 // The following *_wrapper functions allow avoiding memory allocations
14 // durting calls from Go.
15 // See https://github.com/golang/go/issues/24450 .
16
17 static size_t ZSTD_CCtx_setParameter_wrapper(uintptr_t cs, ZSTD_cParameter param, int value) {
18 return ZSTD_CCtx_setParameter((ZSTD_CStream*)cs, param, value);
19 }
20
21 static size_t ZSTD_initCStream_wrapper(uintptr_t cs, int compressionLevel) {
22 return ZSTD_initCStream((ZSTD_CStream*)cs, compressionLevel);
23 }
24
25 static size_t ZSTD_CCtx_refCDict_wrapper(uintptr_t cc, uintptr_t dict) {
26 return ZSTD_CCtx_refCDict((ZSTD_CCtx*)cc, (ZSTD_CDict*)dict);
27 }
28
29 static size_t ZSTD_freeCStream_wrapper(uintptr_t cs) {
30 return ZSTD_freeCStream((ZSTD_CStream*)cs);
31 }
32
33 static size_t ZSTD_compressStream_wrapper(uintptr_t cs, uintptr_t output, uintptr_t input) {
34 return ZSTD_compressStream((ZSTD_CStream*)cs, (ZSTD_outBuffer*)output, (ZSTD_inBuffer*)input);
35 }
36
37 static size_t ZSTD_flushStream_wrapper(uintptr_t cs, uintptr_t output) {
38 return ZSTD_flushStream((ZSTD_CStream*)cs, (ZSTD_outBuffer*)output);
39 }
40
41 static size_t ZSTD_endStream_wrapper(uintptr_t cs, uintptr_t output) {
42 return ZSTD_endStream((ZSTD_CStream*)cs, (ZSTD_outBuffer*)output);
43 }
44
45 */
46 import "C"
47
48 import (
49 "fmt"
50 "io"
51 "runtime"
52 "unsafe"
53 )
54
55 var (
56 cstreamInBufSize = C.ZSTD_CStreamInSize()
57 cstreamOutBufSize = C.ZSTD_CStreamOutSize()
58 )
59
60 type cMemPtr *[1 << 30]byte
61
62 // Writer implements zstd writer.
63 type Writer struct {
64 w io.Writer
65 compressionLevel int
66 wlog int
67 cs *C.ZSTD_CStream
68 cd *CDict
69
70 inBuf *C.ZSTD_inBuffer
71 outBuf *C.ZSTD_outBuffer
72
73 inBufGo cMemPtr
74 outBufGo cMemPtr
75 }
76
77 // NewWriter returns new zstd writer writing compressed data to w.
78 //
79 // The returned writer must be closed with Close call in order
80 // to finalize the compressed stream.
81 //
82 // Call Release when the Writer is no longer needed.
83 func NewWriter(w io.Writer) *Writer {
84 return NewWriterParams(w, nil)
85 }
86
87 // NewWriterLevel returns new zstd writer writing compressed data to w
88 // at the given compression level.
89 //
90 // The returned writer must be closed with Close call in order
91 // to finalize the compressed stream.
92 //
93 // Call Release when the Writer is no longer needed.
94 func NewWriterLevel(w io.Writer, compressionLevel int) *Writer {
95 params := &WriterParams{
96 CompressionLevel: compressionLevel,
97 }
98 return NewWriterParams(w, params)
99 }
100
101 // NewWriterDict returns new zstd writer writing compressed data to w
102 // using the given cd.
103 //
104 // The returned writer must be closed with Close call in order
105 // to finalize the compressed stream.
106 //
107 // Call Release when the Writer is no longer needed.
108 func NewWriterDict(w io.Writer, cd *CDict) *Writer {
109 params := &WriterParams{
110 Dict: cd,
111 }
112 return NewWriterParams(w, params)
113 }
114
115 const (
116 // WindowLogMin is the minimum value of the windowLog parameter.
117 WindowLogMin = 10 // from zstd.h
118 // WindowLogMax32 is the maximum value of the windowLog parameter on 32-bit architectures.
119 WindowLogMax32 = 30 // from zstd.h
120 // WindowLogMax64 is the maximum value of the windowLog parameter on 64-bit architectures.
121 WindowLogMax64 = 31 // from zstd.h
122
123 // DefaultWindowLog is the default value of the windowLog parameter.
124 DefaultWindowLog = 0
125 )
126
127 // A WriterParams allows users to specify compression parameters by calling
128 // NewWriterParams.
129 //
130 // Calling NewWriterParams with a nil WriterParams is equivalent to calling
131 // NewWriter.
132 type WriterParams struct {
133 // Compression level. Special value 0 means 'default compression level'.
134 CompressionLevel int
135
136 // WindowLog. Must be clamped between WindowLogMin and WindowLogMin32/64.
137 // Special value 0 means 'use default windowLog'.
138 //
139 // Note: enabling log distance matching increases memory usage for both
140 // compressor and decompressor. When set to a value greater than 27, the
141 // decompressor requires special treatment.
142 WindowLog int
143
144 // Dict is optional dictionary used for compression.
145 Dict *CDict
146 }
147
148 // NewWriterParams returns new zstd writer writing compressed data to w
149 // using the given set of parameters.
150 //
151 // The returned writer must be closed with Close call in order
152 // to finalize the compressed stream.
153 //
154 // Call Release when the Writer is no longer needed.
155 func NewWriterParams(w io.Writer, params *WriterParams) *Writer {
156 if params == nil {
157 params = &WriterParams{}
158 }
159
160 cs := C.ZSTD_createCStream()
161 initCStream(cs, *params)
162
163 inBuf := (*C.ZSTD_inBuffer)(C.calloc(1, C.sizeof_ZSTD_inBuffer))
164 inBuf.src = C.calloc(1, cstreamInBufSize)
165 inBuf.size = 0
166 inBuf.pos = 0
167
168 outBuf := (*C.ZSTD_outBuffer)(C.calloc(1, C.sizeof_ZSTD_outBuffer))
169 outBuf.dst = C.calloc(1, cstreamOutBufSize)
170 outBuf.size = cstreamOutBufSize
171 outBuf.pos = 0
172
173 zw := &Writer{
174 w: w,
175 compressionLevel: params.CompressionLevel,
176 wlog: params.WindowLog,
177 cs: cs,
178 cd: params.Dict,
179 inBuf: inBuf,
180 outBuf: outBuf,
181 }
182
183 zw.inBufGo = cMemPtr(zw.inBuf.src)
184 zw.outBufGo = cMemPtr(zw.outBuf.dst)
185
186 runtime.SetFinalizer(zw, freeCStream)
187 return zw
188 }
189
190 // Reset resets zw to write to w using the given dictionary cd and the given
191 // compressionLevel. Use ResetWriterParams if you wish to change other
192 // parameters that were set via WriterParams.
193 func (zw *Writer) Reset(w io.Writer, cd *CDict, compressionLevel int) {
194 params := WriterParams{
195 CompressionLevel: compressionLevel,
196 WindowLog: zw.wlog,
197 Dict: cd,
198 }
199 zw.ResetWriterParams(w, &params)
200 }
201
202 // ResetWriterParams resets zw to write to w using the given set of parameters.
203 func (zw *Writer) ResetWriterParams(w io.Writer, params *WriterParams) {
204 zw.inBuf.size = 0
205 zw.inBuf.pos = 0
206 zw.outBuf.size = cstreamOutBufSize
207 zw.outBuf.pos = 0
208
209 zw.cd = params.Dict
210 initCStream(zw.cs, *params)
211
212 zw.w = w
213 }
214
215 func initCStream(cs *C.ZSTD_CStream, params WriterParams) {
216 if params.Dict != nil {
217 result := C.ZSTD_CCtx_refCDict_wrapper(
218 C.uintptr_t(uintptr(unsafe.Pointer(cs))),
219 C.uintptr_t(uintptr(unsafe.Pointer(params.Dict.p))))
220 ensureNoError("ZSTD_CCtx_refCDict", result)
221 } else {
222 result := C.ZSTD_initCStream_wrapper(
223 C.uintptr_t(uintptr(unsafe.Pointer(cs))),
224 C.int(params.CompressionLevel))
225 ensureNoError("ZSTD_initCStream", result)
226 }
227
228 result := C.ZSTD_CCtx_setParameter_wrapper(
229 C.uintptr_t(uintptr(unsafe.Pointer(cs))),
230 C.ZSTD_cParameter(C.ZSTD_c_windowLog),
231 C.int(params.WindowLog))
232 ensureNoError("ZSTD_CCtx_setParameter", result)
233 }
234
235 func freeCStream(v interface{}) {
236 v.(*Writer).Release()
237 }
238
239 // Release releases all the resources occupied by zw.
240 //
241 // zw cannot be used after the release.
242 func (zw *Writer) Release() {
243 if zw.cs == nil {
244 return
245 }
246
247 result := C.ZSTD_freeCStream_wrapper(
248 C.uintptr_t(uintptr(unsafe.Pointer(zw.cs))))
249 ensureNoError("ZSTD_freeCStream", result)
250 zw.cs = nil
251
252 C.free(unsafe.Pointer(zw.inBuf.src))
253 C.free(unsafe.Pointer(zw.inBuf))
254 zw.inBuf = nil
255
256 C.free(unsafe.Pointer(zw.outBuf.dst))
257 C.free(unsafe.Pointer(zw.outBuf))
258 zw.outBuf = nil
259
260 zw.w = nil
261 zw.cd = nil
262 }
263
264 // ReadFrom reads all the data from r and writes it to zw.
265 //
266 // Returns the number of bytes read from r.
267 //
268 // ReadFrom may not flush the compressed data to the underlying writer
269 // due to performance reasons.
270 // Call Flush or Close when the compressed data must propagate
271 // to the underlying writer.
272 func (zw *Writer) ReadFrom(r io.Reader) (int64, error) {
273 nn := int64(0)
274 for {
275 // Fill the inBuf.
276 for zw.inBuf.size < cstreamInBufSize {
277 n, err := r.Read(zw.inBufGo[zw.inBuf.size:cstreamInBufSize])
278
279 // Sometimes n > 0 even when Read() returns an error.
280 // This is true especially if the error is io.EOF.
281 zw.inBuf.size += C.size_t(n)
282 nn += int64(n)
283
284 if err != nil {
285 if err == io.EOF {
286 return nn, nil
287 }
288 return nn, err
289 }
290 }
291
292 // Flush the inBuf.
293 if err := zw.flushInBuf(); err != nil {
294 return nn, err
295 }
296 }
297 }
298
299 // Write writes p to zw.
300 //
301 // Write doesn't flush the compressed data to the underlying writer
302 // due to performance reasons.
303 // Call Flush or Close when the compressed data must propagate
304 // to the underlying writer.
305 func (zw *Writer) Write(p []byte) (int, error) {
306 pLen := len(p)
307 if pLen == 0 {
308 return 0, nil
309 }
310
311 for {
312 n := copy(zw.inBufGo[zw.inBuf.size:cstreamInBufSize], p)
313 zw.inBuf.size += C.size_t(n)
314 p = p[n:]
315 if len(p) == 0 {
316 // Fast path - just copy the data to input buffer.
317 return pLen, nil
318 }
319 if err := zw.flushInBuf(); err != nil {
320 return 0, err
321 }
322 }
323 }
324
325 func (zw *Writer) flushInBuf() error {
326 prevInBufPos := zw.inBuf.pos
327 result := C.ZSTD_compressStream_wrapper(
328 C.uintptr_t(uintptr(unsafe.Pointer(zw.cs))),
329 C.uintptr_t(uintptr(unsafe.Pointer(zw.outBuf))),
330 C.uintptr_t(uintptr(unsafe.Pointer(zw.inBuf))))
331 ensureNoError("ZSTD_compressStream", result)
332
333 // Move the remaining data to the start of inBuf.
334 copy(zw.inBufGo[:cstreamInBufSize], zw.inBufGo[zw.inBuf.pos:zw.inBuf.size])
335 zw.inBuf.size -= zw.inBuf.pos
336 zw.inBuf.pos = 0
337
338 if zw.outBuf.size-zw.outBuf.pos > zw.outBuf.pos && prevInBufPos != zw.inBuf.pos {
339 // There is enough space in outBuf and the last compression
340 // succeeded, so don't flush outBuf yet.
341 return nil
342 }
343
344 // Flush outBuf, since there is low space in it or the last compression
345 // attempt was unsuccessful.
346 return zw.flushOutBuf()
347 }
348
349 func (zw *Writer) flushOutBuf() error {
350 if zw.outBuf.pos == 0 {
351 // Nothing to flush.
352 return nil
353 }
354
355 outBuf := zw.outBufGo[:zw.outBuf.pos]
356 n, err := zw.w.Write(outBuf)
357 zw.outBuf.pos = 0
358 if err != nil {
359 return fmt.Errorf("cannot flush internal buffer to the underlying writer: %s", err)
360 }
361 if n != len(outBuf) {
362 panic(fmt.Errorf("BUG: the underlying writer violated io.Writer contract and didn't return error after writing incomplete data; written %d bytes; want %d bytes",
363 n, len(outBuf)))
364 }
365 return nil
366 }
367
368 // Flush flushes the remaining data from zw to the underlying writer.
369 func (zw *Writer) Flush() error {
370 // Flush inBuf.
371 for zw.inBuf.size > 0 {
372 if err := zw.flushInBuf(); err != nil {
373 return err
374 }
375 }
376
377 // Flush the internal buffer to outBuf.
378 for {
379 result := C.ZSTD_flushStream_wrapper(
380 C.uintptr_t(uintptr(unsafe.Pointer(zw.cs))),
381 C.uintptr_t(uintptr(unsafe.Pointer(zw.outBuf))))
382 ensureNoError("ZSTD_flushStream", result)
383 if err := zw.flushOutBuf(); err != nil {
384 return err
385 }
386 if result == 0 {
387 // No more data left in the internal buffer.
388 return nil
389 }
390 }
391 }
392
393 // Close finalizes the compressed stream and flushes all the compressed data
394 // to the underlying writer.
395 //
396 // It doesn't close the underlying writer passed to New* functions.
397 func (zw *Writer) Close() error {
398 if err := zw.Flush(); err != nil {
399 return err
400 }
401
402 for {
403 result := C.ZSTD_endStream_wrapper(
404 C.uintptr_t(uintptr(unsafe.Pointer(zw.cs))),
405 C.uintptr_t(uintptr(unsafe.Pointer(zw.outBuf))))
406 ensureNoError("ZSTD_endStream", result)
407 if err := zw.flushOutBuf(); err != nil {
408 return err
409 }
410 if result == 0 {
411 return nil
412 }
413 }
414 }