encoder_options.go 9.9 KB

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