blob: c0fd058c28f50f4d9f5ff2078ad6628342c621ae [file] [log] [blame]
khenaidoo106c61a2021-08-11 18:05:46 -04001// Copyright 2019+ Klaus Post. All rights reserved.
2// License information can be found in the LICENSE file.
3// Based on work by Yann Collet, released under BSD License.
4
5package zstd
6
7import (
8 "errors"
9 "runtime"
10)
11
12// DOption is an option for creating a decoder.
13type DOption func(*decoderOptions) error
14
15// options retains accumulated state of multiple options.
16type decoderOptions struct {
17 lowMem bool
18 concurrent int
19 maxDecodedSize uint64
20 dicts []dict
21}
22
23func (o *decoderOptions) setDefault() {
24 *o = decoderOptions{
25 // use less ram: true for now, but may change.
26 lowMem: true,
27 concurrent: runtime.GOMAXPROCS(0),
28 }
29 o.maxDecodedSize = 1 << 63
30}
31
32// WithDecoderLowmem will set whether to use a lower amount of memory,
33// but possibly have to allocate more while running.
34func WithDecoderLowmem(b bool) DOption {
35 return func(o *decoderOptions) error { o.lowMem = b; return nil }
36}
37
38// WithDecoderConcurrency will set the concurrency,
39// meaning the maximum number of decoders to run concurrently.
40// The value supplied must be at least 1.
41// By default this will be set to GOMAXPROCS.
42func WithDecoderConcurrency(n int) DOption {
43 return func(o *decoderOptions) error {
44 if n <= 0 {
45 return errors.New("concurrency must be at least 1")
46 }
47 o.concurrent = n
48 return nil
49 }
50}
51
52// WithDecoderMaxMemory allows to set a maximum decoded size for in-memory
53// non-streaming operations or maximum window size for streaming operations.
54// This can be used to control memory usage of potentially hostile content.
55// For streaming operations, the maximum window size is capped at 1<<30 bytes.
56// Maximum and default is 1 << 63 bytes.
57func WithDecoderMaxMemory(n uint64) DOption {
58 return func(o *decoderOptions) error {
59 if n == 0 {
60 return errors.New("WithDecoderMaxMemory must be at least 1")
61 }
62 if n > 1<<63 {
63 return errors.New("WithDecoderMaxmemory must be less than 1 << 63")
64 }
65 o.maxDecodedSize = n
66 return nil
67 }
68}
69
70// WithDecoderDicts allows to register one or more dictionaries for the decoder.
71// If several dictionaries with the same ID is provided the last one will be used.
72func WithDecoderDicts(dicts ...[]byte) DOption {
73 return func(o *decoderOptions) error {
74 for _, b := range dicts {
75 d, err := loadDict(b)
76 if err != nil {
77 return err
78 }
79 o.dicts = append(o.dicts, *d)
80 }
81 return nil
82 }
83}