Debian Codegraph @

zstd/encoder_options.go

raw
1 package zstd
2
3 import (
4 "errors"
5 "fmt"
6 "math"
7 "math/bits"
8 "runtime"
9 "strings"
10 )
11
12 // EOption is an option for creating a encoder.
13 type EOption func(*encoderOptions) error
14
15 // options retains accumulated state of multiple options.
16 type encoderOptions struct {
17 resetOpt bool
18 concurrent int
19 level EncoderLevel
20 single *bool
21 pad int
22 blockSize int
23 windowSize int
24 crc bool
25 fullZero bool
26 noEntropy bool
27 allLitEntropy bool
28 customWindow bool
29 customALEntropy bool
30 customBlockSize bool
31 lowMem bool
32 dict *dict
33 concurrentBlocks bool
34 }
35
36 func (o *encoderOptions) setDefault() {
37 *o = encoderOptions{
38 concurrent: runtime.GOMAXPROCS(0),
39 crc: true,
40 single: nil,
41 blockSize: maxCompressedBlockSize,
42 windowSize: 8 << 20,
43 level: SpeedDefault,
44 allLitEntropy: false,
45 lowMem: false,
46 fullZero: true,
47 }
48 }
49
50 // encoder returns an encoder with the selected options.
51 func (o encoderOptions) encoder() encoder {
52 switch o.level {
53 case SpeedFastest:
54 if o.dict != nil {
55 return &fastEncoderDict{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}}
56 }
57 return &fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}
58
59 case SpeedDefault:
60 if o.dict != nil {
61 return &doubleFastEncoderDict{fastEncoderDict: fastEncoderDict{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}}}
62 }
63 return &doubleFastEncoder{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}}
64 case SpeedBetterCompression:
65 if o.dict != nil {
66 return &betterFastEncoderDict{betterFastEncoder: betterFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}}
67 }
68 return &betterFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}
69 case SpeedBestCompression:
70 return &bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}
71 }
72 panic("unknown compression level")
73 }
74
75 // WithEncoderCRC will add CRC value to output.
76 // Output will be 4 bytes larger.
77 // Can be changed with ResetWithOptions.
78 func WithEncoderCRC(b bool) EOption {
79 return func(o *encoderOptions) error { o.crc = b; return nil }
80 }
81
82 // WithEncoderConcurrency will set the concurrency,
83 // meaning the maximum number of encoders to run concurrently.
84 // The value supplied must be at least 0.
85 // When a value of 0 is provided GOMAXPROCS will be used.
86 // For streams, setting a value of 1 will disable async compression.
87 // By default this will be set to GOMAXPROCS.
88 // Cannot be changed with ResetWithOptions.
89 func WithEncoderConcurrency(n int) EOption {
90 return func(o *encoderOptions) error {
91 if n < 0 {
92 return errors.New("concurrency must at least 0")
93 }
94 if n == 0 {
95 n = runtime.GOMAXPROCS(0)
96 }
97 if o.resetOpt && n != o.concurrent {
98 return errors.New("WithEncoderConcurrency cannot be changed on Reset")
99 }
100 o.concurrent = n
101 return nil
102 }
103 }
104
105 // WithWindowSize will set the maximum allowed back-reference distance.
106 // The value must be a power of two between MinWindowSize and MaxWindowSize.
107 // A larger value will enable better compression but allocate more memory and,
108 // for above-default values, take considerably longer.
109 // The default value is determined by the compression level and max 8MB.
110 // Cannot be changed with ResetWithOptions.
111 func WithWindowSize(n int) EOption {
112 return func(o *encoderOptions) error {
113 switch {
114 case n < MinWindowSize:
115 return fmt.Errorf("window size must be at least %d", MinWindowSize)
116 case n > MaxWindowSize:
117 return fmt.Errorf("window size must be at most %d", MaxWindowSize)
118 case (n & (n - 1)) != 0:
119 return errors.New("window size must be a power of 2")
120 }
121 if o.resetOpt && n != o.windowSize {
122 return errors.New("WithWindowSize cannot be changed on Reset")
123 }
124
125 o.windowSize = n
126 o.customWindow = true
127 if o.blockSize > o.windowSize {
128 o.blockSize = o.windowSize
129 o.customBlockSize = true
130 }
131 return nil
132 }
133 }
134
135 // WithEncoderPadding will add padding to all output so the size will be a multiple of n.
136 // This can be used to obfuscate the exact output size or make blocks of a certain size.
137 // The contents will be a skippable frame, so it will be invisible by the decoder.
138 // n must be > 0 and <= 1GB, 1<<30 bytes.
139 // The padded area will be filled with data from crypto/rand.Reader.
140 // If `EncodeAll` is used with data already in the destination, the total size will be multiple of this.
141 // Can be changed with ResetWithOptions.
142 func WithEncoderPadding(n int) EOption {
143 return func(o *encoderOptions) error {
144 if n <= 0 {
145 return fmt.Errorf("padding must be at least 1")
146 }
147 // No need to waste our time.
148 if n == 1 {
149 n = 0
150 }
151 if n > 1<<30 {
152 return fmt.Errorf("padding must less than 1GB (1<<30 bytes) ")
153 }
154 o.pad = n
155 return nil
156 }
157 }
158
159 // EncoderLevel predefines encoder compression levels.
160 // Only use the constants made available, since the actual mapping
161 // of these values are very likely to change and your compression could change
162 // unpredictably when upgrading the library.
163 type EncoderLevel int
164
165 const (
166 speedNotSet EncoderLevel = iota
167
168 // SpeedFastest will choose the fastest reasonable compression.
169 // This is roughly equivalent to the fastest Zstandard mode.
170 SpeedFastest
171
172 // SpeedDefault is the default "pretty fast" compression option.
173 // This is roughly equivalent to the default Zstandard mode (level 3).
174 SpeedDefault
175
176 // SpeedBetterCompression will yield better compression than the default.
177 // Currently it is about zstd level 7-8 with ~ 2x-3x the default CPU usage.
178 // By using this, notice that CPU usage may go up in the future.
179 SpeedBetterCompression
180
181 // SpeedBestCompression will choose the best available compression option.
182 // This will offer the best compression no matter the CPU cost.
183 SpeedBestCompression
184
185 // speedLast should be kept as the last actual compression option.
186 // The is not for external usage, but is used to keep track of the valid options.
187 speedLast
188 )
189
190 // EncoderLevelFromString will convert a string representation of an encoding level back
191 // to a compression level. The compare is not case sensitive.
192 // If the string wasn't recognized, (false, SpeedDefault) will be returned.
193 func EncoderLevelFromString(s string) (bool, EncoderLevel) {
194 for l := speedNotSet + 1; l < speedLast; l++ {
195 if strings.EqualFold(s, l.String()) {
196 return true, l
197 }
198 }
199 return false, SpeedDefault
200 }
201
202 // EncoderLevelFromZstd will return an encoder level that closest matches the compression
203 // ratio of a specific zstd compression level.
204 // Many input values will provide the same compression level.
205 func EncoderLevelFromZstd(level int) EncoderLevel {
206 switch {
207 case level < 3:
208 return SpeedFastest
209 case level >= 3 && level < 6:
210 return SpeedDefault
211 case level >= 6 && level < 10:
212 return SpeedBetterCompression
213 default:
214 return SpeedBestCompression
215 }
216 }
217
218 // String provides a string representation of the compression level.
219 func (e EncoderLevel) String() string {
220 switch e {
221 case SpeedFastest:
222 return "fastest"
223 case SpeedDefault:
224 return "default"
225 case SpeedBetterCompression:
226 return "better"
227 case SpeedBestCompression:
228 return "best"
229 default:
230 return "invalid"
231 }
232 }
233
234 // WithEncoderLevel specifies a predefined compression level.
235 // Cannot be changed with ResetWithOptions.
236 func WithEncoderLevel(l EncoderLevel) EOption {
237 return func(o *encoderOptions) error {
238 switch {
239 case l <= speedNotSet || l >= speedLast:
240 return fmt.Errorf("unknown encoder level")
241 }
242 if o.resetOpt && l != o.level {
243 return errors.New("WithEncoderLevel cannot be changed on Reset")
244 }
245 o.level = l
246 if !o.customWindow {
247 switch o.level {
248 case SpeedFastest:
249 o.windowSize = 4 << 20
250 if !o.customBlockSize {
251 o.blockSize = 1 << 16
252 }
253 case SpeedDefault:
254 o.windowSize = 8 << 20
255 case SpeedBetterCompression:
256 o.windowSize = 8 << 20
257 case SpeedBestCompression:
258 o.windowSize = 8 << 20
259 }
260 }
261 if !o.customALEntropy {
262 o.allLitEntropy = l > SpeedDefault
263 }
264
265 return nil
266 }
267 }
268
269 // WithZeroFrames will encode 0 length input as full frames.
270 // This can be needed for compatibility with zstandard usage,
271 // but is not needed for this package.
272 // Can be changed with ResetWithOptions.
273 func WithZeroFrames(b bool) EOption {
274 return func(o *encoderOptions) error {
275 o.fullZero = b
276 return nil
277 }
278 }
279
280 // WithAllLitEntropyCompression will apply entropy compression if no matches are found.
281 // Disabling this will skip incompressible data faster, but in cases with no matches but
282 // skewed character distribution compression is lost.
283 // Default value depends on the compression level selected.
284 // Can be changed with ResetWithOptions.
285 func WithAllLitEntropyCompression(b bool) EOption {
286 return func(o *encoderOptions) error {
287 o.customALEntropy = true
288 o.allLitEntropy = b
289 return nil
290 }
291 }
292
293 // WithNoEntropyCompression will always skip entropy compression of literals.
294 // This can be useful if content has matches, but unlikely to benefit from entropy
295 // compression. Usually the slight speed improvement is not worth enabling this.
296 // Can be changed with ResetWithOptions.
297 func WithNoEntropyCompression(b bool) EOption {
298 return func(o *encoderOptions) error {
299 o.noEntropy = b
300 return nil
301 }
302 }
303
304 // WithSingleSegment will set the "single segment" flag when EncodeAll is used.
305 // If this flag is set, data must be regenerated within a single continuous memory segment.
306 // In this case, Window_Descriptor byte is skipped, but Frame_Content_Size is necessarily present.
307 // As a consequence, the decoder must allocate a memory segment of size equal or larger than size of your content.
308 // In order to preserve the decoder from unreasonable memory requirements,
309 // a decoder is allowed to reject a compressed frame which requests a memory size beyond decoder's authorized range.
310 // For broader compatibility, decoders are recommended to support memory sizes of at least 8 MB.
311 // This is only a recommendation, each decoder is free to support higher or lower limits, depending on local limitations.
312 // If this is not specified, block encodes will automatically choose this based on the input size and the window size.
313 // This setting has no effect on streamed encodes.
314 // Can be changed with ResetWithOptions.
315 func WithSingleSegment(b bool) EOption {
316 return func(o *encoderOptions) error {
317 o.single = &b
318 return nil
319 }
320 }
321
322 // WithLowerEncoderMem will trade in some memory cases trade less memory usage for
323 // slower encoding speed.
324 // This will not change the window size which is the primary function for reducing
325 // memory usage. See WithWindowSize.
326 // Cannot be changed with ResetWithOptions.
327 func WithLowerEncoderMem(b bool) EOption {
328 return func(o *encoderOptions) error {
329 if o.resetOpt && b != o.lowMem {
330 return errors.New("WithLowerEncoderMem cannot be changed on Reset")
331 }
332 o.lowMem = b
333 return nil
334 }
335 }
336
337 // WithConcurrentBlocks enables job-based parallel compression for streams.
338 // When enabled and concurrent > 1, input is split into large sections (jobs)
339 // that are compressed simultaneously by multiple goroutines.
340 // Each non-first job receives an overlap prefix from the previous job for match context.
341 // Output is flushed in order, producing a valid single-frame zstd stream.
342 //
343 // Currently disabled when used with dictionary encoding.
344 // Cannot be changed with ResetWithOptions.
345 func WithConcurrentBlocks(b bool) EOption {
346 return func(o *encoderOptions) error {
347 if o.resetOpt && b != o.concurrentBlocks {
348 return errors.New("WithConcurrentBlocks cannot be changed on Reset")
349 }
350 o.concurrentBlocks = b
351 return nil
352 }
353 }
354
355 // jobSize returns the input section size per parallel job.
356 func (o *encoderOptions) jobSize() int {
357 s := max(o.windowSize*4, 512<<10)
358 return s
359 }
360
361 // overlapSize returns the overlap prefix size for parallel jobs.
362 func (o *encoderOptions) overlapSize() int {
363 switch o.level {
364 case SpeedBestCompression:
365 return o.windowSize / 2
366 case SpeedBetterCompression:
367 return o.windowSize / 4
368 default:
369 return o.windowSize / 8
370 }
371 }
372
373 // WithEncoderDict allows to register a dictionary that will be used for the encode.
374 //
375 // The slice dict must be in the [dictionary format] produced by
376 // "zstd --train" from the Zstandard reference implementation.
377 //
378 // The encoder *may* choose to use no dictionary instead for certain payloads.
379 // Can be changed with ResetWithOptions.
380 //
381 // [dictionary format]: https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary-format
382 func WithEncoderDict(dict []byte) EOption {
383 return func(o *encoderOptions) error {
384 d, err := loadDict(dict)
385 if err != nil {
386 return err
387 }
388 o.dict = d
389 return nil
390 }
391 }
392
393 // WithEncoderDictRaw registers a dictionary that may be used by the encoder.
394 //
395 // The slice content may contain arbitrary data. It will be used as an initial
396 // history.
397 // Can be changed with ResetWithOptions.
398 func WithEncoderDictRaw(id uint32, content []byte) EOption {
399 return func(o *encoderOptions) error {
400 if bits.UintSize > 32 && uint(len(content)) > dictMaxLength {
401 return fmt.Errorf("dictionary of size %d > 2GiB too large", len(content))
402 }
403 o.dict = &dict{id: id, content: content, offsets: [3]int{1, 4, 8}}
404 return nil
405 }
406 }
407
408 // WithEncoderDictDelete clears the dictionary, so no dictionary will be used.
409 // Should be used with ResetWithOptions.
410 func WithEncoderDictDelete() EOption {
411 return func(o *encoderOptions) error {
412 o.dict = nil
413 return nil
414 }
415 }