encoder_options.go 10 KB

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