encoder_options.go 11 KB

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