• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..17-May-2021-

internal/xxhash/H17-May-2021-617433

README.mdH A D17-May-202120.4 KiB407294

bitreader.goH A D17-May-20213.3 KiB137100

bitwriter.goH A D17-May-20214.5 KiB170131

blockdec.goH A D17-May-202118.5 KiB740619

blockenc.goH A D17-May-202121.8 KiB855713

blocktype_string.goH A D17-May-20212.7 KiB8661

bytebuf.goH A D17-May-20212.3 KiB12898

bytereader.goH A D17-May-20212 KiB8959

decoder.goH A D17-May-202112.8 KiB547406

decoder_options.goH A D17-May-20212.3 KiB8556

dict.goH A D17-May-20212.8 KiB123101

enc_base.goH A D17-May-20213.7 KiB156121

enc_better.goH A D17-May-202115.9 KiB596452

enc_dfast.goH A D17-May-202118.6 KiB714527

enc_fast.goH A D17-May-202116.4 KiB662512

encoder.goH A D17-May-202113.3 KiB571470

encoder_options.goH A D17-May-20218.8 KiB283188

framedec.goH A D17-May-202111.9 KiB495400

frameenc.goH A D17-May-20213.3 KiB138116

fse_decoder.goH A D17-May-202110.6 KiB386293

fse_encoder.goH A D17-May-202119.1 KiB727600

fse_predefined.goH A D17-May-20215.2 KiB159112

hash.goH A D17-May-20212.6 KiB7844

history.goH A D17-May-20212.3 KiB9065

seqdec.goH A D17-May-202112.9 KiB486369

seqenc.goH A D17-May-20213.2 KiB11682

snappy.goH A D17-May-202112.8 KiB437346

zstd.goH A D17-May-20214.5 KiB14580

README.md

1# zstd
2
3[Zstandard](https://facebook.github.io/zstd/) is a real-time compression algorithm, providing high compression ratios.
4It offers a very wide range of compression / speed trade-off, while being backed by a very fast decoder.
5A high performance compression algorithm is implemented. For now focused on speed.
6
7This package provides [compression](#Compressor) to and [decompression](#Decompressor) of Zstandard content.
8
9This package is pure Go and without use of "unsafe".
10
11The `zstd` package is provided as open source software using a Go standard license.
12
13Currently the package is heavily optimized for 64 bit processors and will be significantly slower on 32 bit processors.
14
15## Installation
16
17Install using `go get -u github.com/klauspost/compress`. The package is located in `github.com/klauspost/compress/zstd`.
18
19Godoc Documentation: https://godoc.org/github.com/klauspost/compress/zstd
20
21
22## Compressor
23
24### Status:
25
26STABLE - there may always be subtle bugs, a wide variety of content has been tested and the library is actively
27used by several projects. This library is being continuously [fuzz-tested](https://github.com/klauspost/compress-fuzz),
28kindly supplied by [fuzzit.dev](https://fuzzit.dev/).
29
30There may still be specific combinations of data types/size/settings that could lead to edge cases,
31so as always, testing is recommended.
32
33For now, a high speed (fastest) and medium-fast (default) compressor has been implemented.
34
35The "Fastest" compression ratio is roughly equivalent to zstd level 1.
36The "Default" compression ratio is roughly equivalent to zstd level 3 (default).
37
38In terms of speed, it is typically 2x as fast as the stdlib deflate/gzip in its fastest mode.
39The compression ratio compared to stdlib is around level 3, but usually 3x as fast.
40
41Compared to cgo zstd, the speed is around level 3 (default), but compression slightly worse, between level 1&2.
42
43
44### Usage
45
46An Encoder can be used for either compressing a stream via the
47`io.WriteCloser` interface supported by the Encoder or as multiple independent
48tasks via the `EncodeAll` function.
49Smaller encodes are encouraged to use the EncodeAll function.
50Use `NewWriter` to create a new instance that can be used for both.
51
52To create a writer with default options, do like this:
53
54```Go
55// Compress input to output.
56func Compress(in io.Reader, out io.Writer) error {
57    w, err := NewWriter(output)
58    if err != nil {
59        return err
60    }
61    _, err := io.Copy(w, input)
62    if err != nil {
63        enc.Close()
64        return err
65    }
66    return enc.Close()
67}
68```
69
70Now you can encode by writing data to `enc`. The output will be finished writing when `Close()` is called.
71Even if your encode fails, you should still call `Close()` to release any resources that may be held up.
72
73The above is fine for big encodes. However, whenever possible try to *reuse* the writer.
74
75To reuse the encoder, you can use the `Reset(io.Writer)` function to change to another output.
76This will allow the encoder to reuse all resources and avoid wasteful allocations.
77
78Currently stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part
79of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change
80in the future. So if you want to limit concurrency for future updates, specify the concurrency
81you would like.
82
83You can specify your desired compression level using `WithEncoderLevel()` option. Currently only pre-defined
84compression settings can be specified.
85
86#### Future Compatibility Guarantees
87
88This will be an evolving project. When using this package it is important to note that both the compression efficiency and speed may change.
89
90The goal will be to keep the default efficiency at the default zstd (level 3).
91However the encoding should never be assumed to remain the same,
92and you should not use hashes of compressed output for similarity checks.
93
94The Encoder can be assumed to produce the same output from the exact same code version.
95However, the may be modes in the future that break this,
96although they will not be enabled without an explicit option.
97
98This encoder is not designed to (and will probably never) output the exact same bitstream as the reference encoder.
99
100Also note, that the cgo decompressor currently does not [report all errors on invalid input](https://github.com/DataDog/zstd/issues/59),
101[omits error checks](https://github.com/DataDog/zstd/issues/61), [ignores checksums](https://github.com/DataDog/zstd/issues/43)
102and seems to ignore concatenated streams, even though [it is part of the spec](https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frames).
103
104#### Blocks
105
106For compressing small blocks, the returned encoder has a function called `EncodeAll(src, dst []byte) []byte`.
107
108`EncodeAll` will encode all input in src and append it to dst.
109This function can be called concurrently, but each call will only run on a single goroutine.
110
111Encoded blocks can be concatenated and the result will be the combined input stream.
112Data compressed with EncodeAll can be decoded with the Decoder, using either a stream or `DecodeAll`.
113
114Especially when encoding blocks you should take special care to reuse the encoder.
115This will effectively make it run without allocations after a warmup period.
116To make it run completely without allocations, supply a destination buffer with space for all content.
117
118```Go
119import "github.com/klauspost/compress/zstd"
120
121// Create a writer that caches compressors.
122// For this operation type we supply a nil Reader.
123var encoder, _ = zstd.NewWriter(nil)
124
125// Compress a buffer.
126// If you have a destination buffer, the allocation in the call can also be eliminated.
127func Compress(src []byte) []byte {
128    return encoder.EncodeAll(src, make([]byte, 0, len(src)))
129}
130```
131
132You can control the maximum number of concurrent encodes using the `WithEncoderConcurrency(n)`
133option when creating the writer.
134
135Using the Encoder for both a stream and individual blocks concurrently is safe.
136
137### Performance
138
139I have collected some speed examples to compare speed and compression against other compressors.
140
141* `file` is the input file.
142* `out` is the compressor used. `zskp` is this package. `zstd` is the Datadog cgo library. `gzstd/gzkp` is gzip standard and this library.
143* `level` is the compression level used. For `zskp` level 1 is "fastest", level 2 is "default".
144* `insize`/`outsize` is the input/output size.
145* `millis` is the number of milliseconds used for compression.
146* `mb/s` is megabytes (2^20 bytes) per second.
147
148```
149Silesia Corpus:
150http://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip
151
152This package:
153file    out     level   insize      outsize     millis  mb/s
154silesia.tar zskp    1   211947520   73101992    643     313.87
155silesia.tar zskp    2   211947520   67504318    969     208.38
156silesia.tar zskp    3   211947520   65177448    1899    106.44
157
158cgo zstd:
159silesia.tar zstd    1   211947520   73605392    543     371.56
160silesia.tar zstd    3   211947520   66793289    864     233.68
161silesia.tar zstd    6   211947520   62916450    1913    105.66
162
163gzip, stdlib/this package:
164silesia.tar gzstd   1   211947520   80007735    1654    122.21
165silesia.tar gzkp    1   211947520   80369488    1168    173.06
166
167GOB stream of binary data. Highly compressible.
168https://files.klauspost.com/compress/gob-stream.7z
169
170file        out     level   insize  outsize     millis  mb/s
171gob-stream  zskp    1   1911399616  235022249   3088    590.30
172gob-stream  zskp    2   1911399616  205669791   3786    481.34
173gob-stream  zskp    3   1911399616  185792019   9324    195.48
174gob-stream  zstd    1   1911399616  249810424   2637    691.26
175gob-stream  zstd    3   1911399616  208192146   3490    522.31
176gob-stream  zstd    6   1911399616  193632038   6687    272.56
177gob-stream  gzstd   1   1911399616  357382641   10251   177.82
178gob-stream  gzkp    1   1911399616  362156523   5695    320.08
179
180The test data for the Large Text Compression Benchmark is the first
18110^9 bytes of the English Wikipedia dump on Mar. 3, 2006.
182http://mattmahoney.net/dc/textdata.html
183
184file    out level   insize      outsize     millis  mb/s
185enwik9  zskp    1   1000000000  343848582   3609    264.18
186enwik9  zskp    2   1000000000  317276632   5746    165.97
187enwik9  zskp    3   1000000000  294540704   11725   81.34
188enwik9  zstd    1   1000000000  358072021   3110    306.65
189enwik9  zstd    3   1000000000  313734672   4784    199.35
190enwik9  zstd    6   1000000000  295138875   10290   92.68
191enwik9  gzstd   1   1000000000  382578136   9604    99.30
192enwik9  gzkp    1   1000000000  383825945   6544    145.73
193
194Highly compressible JSON file.
195https://files.klauspost.com/compress/github-june-2days-2019.json.zst
196
197file                        out level   insize      outsize     millis  mb/s
198github-june-2days-2019.json zskp    1   6273951764  699045015   10620   563.40
199github-june-2days-2019.json zskp    2   6273951764  617881763   11687   511.96
200github-june-2days-2019.json zskp    3   6273951764  537511906   29252   204.54
201github-june-2days-2019.json zstd    1   6273951764  766284037   8450    708.00
202github-june-2days-2019.json zstd    3   6273951764  661889476   10927   547.57
203github-june-2days-2019.json zstd    6   6273951764  642756859   22996   260.18
204github-june-2days-2019.json gzstd   1   6273951764  1164400847  29948   199.79
205github-june-2days-2019.json gzkp    1   6273951764  1128755542  19236   311.03
206
207VM Image, Linux mint with a few installed applications:
208https://files.klauspost.com/compress/rawstudio-mint14.7z
209
210file                    out level   insize      outsize     millis  mb/s
211rawstudio-mint14.tar    zskp    1   8558382592  3667489370  20210   403.84
212rawstudio-mint14.tar    zskp    2   8558382592  3364592300  31873   256.07
213rawstudio-mint14.tar    zskp    3   8558382592  3224594213  71751   113.75
214rawstudio-mint14.tar    zstd    1   8558382592  3609250104  17136   476.27
215rawstudio-mint14.tar    zstd    3   8558382592  3341679997  29262   278.92
216rawstudio-mint14.tar    zstd    6   8558382592  3235846406  77904   104.77
217rawstudio-mint14.tar    gzstd   1   8558382592  3926257486  57722   141.40
218rawstudio-mint14.tar    gzkp    1   8558382592  3970463184  41749   195.49
219
220CSV data:
221https://files.klauspost.com/compress/nyc-taxi-data-10M.csv.zst
222
223file                    out level   insize      outsize     millis  mb/s
224nyc-taxi-data-10M.csv   zskp    1   3325605752  641339945   8925    355.35
225nyc-taxi-data-10M.csv   zskp    2   3325605752  591748091   11268   281.44
226nyc-taxi-data-10M.csv   zskp    3   3325605752  538490114   19880   159.53
227nyc-taxi-data-10M.csv   zstd    1   3325605752  687399637   8233    385.18
228nyc-taxi-data-10M.csv   zstd    3   3325605752  598514411   10065   315.07
229nyc-taxi-data-10M.csv   zstd    6   3325605752  570522953   20038   158.27
230nyc-taxi-data-10M.csv   gzstd   1   3325605752  928656485   23876   132.83
231nyc-taxi-data-10M.csv   gzkp    1   3325605752  924718719   16388   193.53
232```
233
234## Decompressor
235
236Staus: STABLE - there may still be subtle bugs, but a wide variety of content has been tested.
237
238This library is being continuously [fuzz-tested](https://github.com/klauspost/compress-fuzz),
239kindly supplied by [fuzzit.dev](https://fuzzit.dev/).
240The main purpose of the fuzz testing is to ensure that it is not possible to crash the decoder,
241or run it past its limits with ANY input provided.
242
243### Usage
244
245The package has been designed for two main usages, big streams of data and smaller in-memory buffers.
246There are two main usages of the package for these. Both of them are accessed by creating a `Decoder`.
247
248For streaming use a simple setup could look like this:
249
250```Go
251import "github.com/klauspost/compress/zstd"
252
253func Decompress(in io.Reader, out io.Writer) error {
254    d, err := zstd.NewReader(in)
255    if err != nil {
256        return err
257    }
258    defer d.Close()
259
260    // Copy content...
261    _, err = io.Copy(out, d)
262    return err
263}
264```
265
266It is important to use the "Close" function when you no longer need the Reader to stop running goroutines.
267See "Allocation-less operation" below.
268
269For decoding buffers, it could look something like this:
270
271```Go
272import "github.com/klauspost/compress/zstd"
273
274// Create a reader that caches decompressors.
275// For this operation type we supply a nil Reader.
276var decoder, _ = zstd.NewReader(nil)
277
278// Decompress a buffer. We don't supply a destination buffer,
279// so it will be allocated by the decoder.
280func Decompress(src []byte) ([]byte, error) {
281    return decoder.DecodeAll(src, nil)
282}
283```
284
285Both of these cases should provide the functionality needed.
286The decoder can be used for *concurrent* decompression of multiple buffers.
287It will only allow a certain number of concurrent operations to run.
288To tweak that yourself use the `WithDecoderConcurrency(n)` option when creating the decoder.
289
290### Dictionaries
291
292Data compressed with [dictionaries](https://github.com/facebook/zstd#the-case-for-small-data-compression) can be decompressed.
293
294Dictionaries are added individually to Decoders.
295Dictionaries are generated by the `zstd --train` command and contains an initial state for the decoder.
296To add a dictionary use the `WithDecoderDicts(dicts ...[]byte)` option with the dictionary data.
297Several dictionaries can be added at once.
298
299The dictionary will be used automatically for the data that specifies them.
300A re-used Decoder will still contain the dictionaries registered.
301
302When registering multiple dictionaries with the same ID, the last one will be used.
303
304It is possible to use dictionaries when compressing data.
305
306To enable a dictionary use `WithEncoderDict(dict []byte)`. Here only one dictionary will be used
307and it will likely be used even if it doesn't improve compression.
308
309The used dictionary must be used to decompress the content.
310
311For any real gains, the dictionary should be built with similar data.
312If an unsuitable dictionary is used the output may be slightly larger than using no dictionary.
313Use the [zstd commandline tool](https://github.com/facebook/zstd/releases) to build a dictionary from sample data.
314For information see [zstd dictionary information](https://github.com/facebook/zstd#the-case-for-small-data-compression).
315
316For now there is a fixed startup performance penalty for compressing content with dictionaries.
317This will likely be improved over time. Just be aware to test performance when implementing.
318
319### Allocation-less operation
320
321The decoder has been designed to operate without allocations after a warmup.
322
323This means that you should *store* the decoder for best performance.
324To re-use a stream decoder, use the `Reset(r io.Reader) error` to switch to another stream.
325A decoder can safely be re-used even if the previous stream failed.
326
327To release the resources, you must call the `Close()` function on a decoder.
328After this it can *no longer be reused*, but all running goroutines will be stopped.
329So you *must* use this if you will no longer need the Reader.
330
331For decompressing smaller buffers a single decoder can be used.
332When decoding buffers, you can supply a destination slice with length 0 and your expected capacity.
333In this case no unneeded allocations should be made.
334
335### Concurrency
336
337The buffer decoder does everything on the same goroutine and does nothing concurrently.
338It can however decode several buffers concurrently. Use `WithDecoderConcurrency(n)` to limit that.
339
340The stream decoder operates on
341
342* One goroutine reads input and splits the input to several block decoders.
343* A number of decoders will decode blocks.
344* A goroutine coordinates these blocks and sends history from one to the next.
345
346So effectively this also means the decoder will "read ahead" and prepare data to always be available for output.
347
348Since "blocks" are quite dependent on the output of the previous block stream decoding will only have limited concurrency.
349
350In practice this means that concurrency is often limited to utilizing about 2 cores effectively.
351
352
353### Benchmarks
354
355These are some examples of performance compared to [datadog cgo library](https://github.com/DataDog/zstd).
356
357The first two are streaming decodes and the last are smaller inputs.
358
359```
360BenchmarkDecoderSilesia-8                          3     385000067 ns/op     550.51 MB/s        5498 B/op          8 allocs/op
361BenchmarkDecoderSilesiaCgo-8                       6     197666567 ns/op    1072.25 MB/s      270672 B/op          8 allocs/op
362
363BenchmarkDecoderEnwik9-8                           1    2027001600 ns/op     493.34 MB/s       10496 B/op         18 allocs/op
364BenchmarkDecoderEnwik9Cgo-8                        2     979499200 ns/op    1020.93 MB/s      270672 B/op          8 allocs/op
365
366Concurrent performance:
367
368BenchmarkDecoder_DecodeAllParallel/kppkn.gtb.zst-16                28915         42469 ns/op    4340.07 MB/s         114 B/op          0 allocs/op
369BenchmarkDecoder_DecodeAllParallel/geo.protodata.zst-16           116505          9965 ns/op    11900.16 MB/s         16 B/op          0 allocs/op
370BenchmarkDecoder_DecodeAllParallel/plrabn12.txt.zst-16              8952        134272 ns/op    3588.70 MB/s         915 B/op          0 allocs/op
371BenchmarkDecoder_DecodeAllParallel/lcet10.txt.zst-16               11820        102538 ns/op    4161.90 MB/s         594 B/op          0 allocs/op
372BenchmarkDecoder_DecodeAllParallel/asyoulik.txt.zst-16             34782         34184 ns/op    3661.88 MB/s          60 B/op          0 allocs/op
373BenchmarkDecoder_DecodeAllParallel/alice29.txt.zst-16              27712         43447 ns/op    3500.58 MB/s          99 B/op          0 allocs/op
374BenchmarkDecoder_DecodeAllParallel/html_x_4.zst-16                 62826         18750 ns/op    21845.10 MB/s        104 B/op          0 allocs/op
375BenchmarkDecoder_DecodeAllParallel/paper-100k.pdf.zst-16          631545          1794 ns/op    57078.74 MB/s          2 B/op          0 allocs/op
376BenchmarkDecoder_DecodeAllParallel/fireworks.jpeg.zst-16         1690140           712 ns/op    172938.13 MB/s         1 B/op          0 allocs/op
377BenchmarkDecoder_DecodeAllParallel/urls.10K.zst-16                 10432        113593 ns/op    6180.73 MB/s        1143 B/op          0 allocs/op
378BenchmarkDecoder_DecodeAllParallel/html.zst-16                    113206         10671 ns/op    9596.27 MB/s          15 B/op          0 allocs/op
379BenchmarkDecoder_DecodeAllParallel/comp-data.bin.zst-16          1530615           779 ns/op    5229.49 MB/s           0 B/op          0 allocs/op
380
381BenchmarkDecoder_DecodeAllParallelCgo/kppkn.gtb.zst-16             65217         16192 ns/op    11383.34 MB/s         46 B/op          0 allocs/op
382BenchmarkDecoder_DecodeAllParallelCgo/geo.protodata.zst-16        292671          4039 ns/op    29363.19 MB/s          6 B/op          0 allocs/op
383BenchmarkDecoder_DecodeAllParallelCgo/plrabn12.txt.zst-16          26314         46021 ns/op    10470.43 MB/s        293 B/op          0 allocs/op
384BenchmarkDecoder_DecodeAllParallelCgo/lcet10.txt.zst-16            33897         34900 ns/op    12227.96 MB/s        205 B/op          0 allocs/op
385BenchmarkDecoder_DecodeAllParallelCgo/asyoulik.txt.zst-16         104348         11433 ns/op    10949.01 MB/s         20 B/op          0 allocs/op
386BenchmarkDecoder_DecodeAllParallelCgo/alice29.txt.zst-16           75949         15510 ns/op    9805.60 MB/s          32 B/op          0 allocs/op
387BenchmarkDecoder_DecodeAllParallelCgo/html_x_4.zst-16             173910          6756 ns/op    60624.29 MB/s         37 B/op          0 allocs/op
388BenchmarkDecoder_DecodeAllParallelCgo/paper-100k.pdf.zst-16       923076          1339 ns/op    76474.87 MB/s          1 B/op          0 allocs/op
389BenchmarkDecoder_DecodeAllParallelCgo/fireworks.jpeg.zst-16       922920          1351 ns/op    91102.57 MB/s          2 B/op          0 allocs/op
390BenchmarkDecoder_DecodeAllParallelCgo/urls.10K.zst-16              27649         43618 ns/op    16096.19 MB/s        407 B/op          0 allocs/op
391BenchmarkDecoder_DecodeAllParallelCgo/html.zst-16                 279073          4160 ns/op    24614.18 MB/s          6 B/op          0 allocs/op
392BenchmarkDecoder_DecodeAllParallelCgo/comp-data.bin.zst-16        749938          1579 ns/op    2581.71 MB/s           0 B/op          0 allocs/op
393```
394
395This reflects the performance around May 2020, but this may be out of date.
396
397# Contributions
398
399Contributions are always welcome.
400For new features/fixes, remember to add tests and for performance enhancements include benchmarks.
401
402For sending files for reproducing errors use a service like [goobox](https://goobox.io/#/upload) or similar to share your files.
403
404For general feedback and experience reports, feel free to open an issue or write me on [Twitter](https://twitter.com/sh0dan).
405
406This package includes the excellent [`github.com/cespare/xxhash`](https://github.com/cespare/xxhash) package Copyright (c) 2016 Caleb Spare.
407