blob: 2ac9cd2dd30ad21589fd5942851688a08da196db [file] [log] [blame]
Scott Bakered4efab2020-01-13 19:12:25 -08001// 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 "fmt"
10 "runtime"
11)
12
13// DOption is an option for creating a decoder.
14type DOption func(*decoderOptions) error
15
16// options retains accumulated state of multiple options.
17type decoderOptions struct {
18 lowMem bool
19 concurrent int
20 maxDecodedSize uint64
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 fmt.Errorf("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 fmt.Errorf("WithDecoderMaxmemory must be less than 1 << 63")
64 }
65 o.maxDecodedSize = n
66 return nil
67 }
68}