deflate.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Copyright (c) 2015 Klaus Post
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file.
  5. package flate
  6. import (
  7. "errors"
  8. "fmt"
  9. "io"
  10. "math"
  11. "github.com/klauspost/compress/internal/le"
  12. )
  13. const (
  14. NoCompression = 0
  15. BestSpeed = 1
  16. BestCompression = 9
  17. DefaultCompression = -1
  18. // HuffmanOnly disables Lempel-Ziv match searching and only performs Huffman
  19. // entropy encoding. This mode is useful in compressing data that has
  20. // already been compressed with an LZ style algorithm (e.g. Snappy or LZ4)
  21. // that lacks an entropy encoder. Compression gains are achieved when
  22. // certain bytes in the input stream occur more frequently than others.
  23. //
  24. // Note that HuffmanOnly produces a compressed output that is
  25. // RFC 1951 compliant. That is, any valid DEFLATE decompressor will
  26. // continue to be able to decompress this output.
  27. HuffmanOnly = -2
  28. ConstantCompression = HuffmanOnly // compatibility alias.
  29. logWindowSize = 15
  30. windowSize = 1 << logWindowSize
  31. windowMask = windowSize - 1
  32. logMaxOffsetSize = 15 // Standard DEFLATE
  33. minMatchLength = 4 // The smallest match that the compressor looks for
  34. maxMatchLength = 258 // The longest match for the compressor
  35. minOffsetSize = 1 // The shortest offset that makes any sense
  36. // The maximum number of tokens we will encode at the time.
  37. // Smaller sizes usually creates less optimal blocks.
  38. // Bigger can make context switching slow.
  39. // We use this for levels 7-9, so we make it big.
  40. maxFlateBlockTokens = 1 << 15
  41. maxStoreBlockSize = 65535
  42. hashBits = 17 // After 17 performance degrades
  43. hashSize = 1 << hashBits
  44. hashMask = (1 << hashBits) - 1
  45. hashShift = (hashBits + minMatchLength - 1) / minMatchLength
  46. maxHashOffset = 1 << 28
  47. skipNever = math.MaxInt32
  48. debugDeflate = false
  49. )
  50. type compressionLevel struct {
  51. good, lazy, nice, chain, fastSkipHashing, level int
  52. }
  53. // Compression levels have been rebalanced from zlib deflate defaults
  54. // to give a bigger spread in speed and compression.
  55. // See https://blog.klauspost.com/rebalancing-deflate-compression-levels/
  56. var levels = []compressionLevel{
  57. {}, // 0
  58. // Level 1-6 uses specialized algorithm - values not used
  59. {0, 0, 0, 0, 0, 1},
  60. {0, 0, 0, 0, 0, 2},
  61. {0, 0, 0, 0, 0, 3},
  62. {0, 0, 0, 0, 0, 4},
  63. {0, 0, 0, 0, 0, 5},
  64. {0, 0, 0, 0, 0, 6},
  65. // Levels 7-9 use increasingly more lazy matching
  66. // and increasingly stringent conditions for "good enough".
  67. {8, 12, 16, 24, skipNever, 7},
  68. {16, 30, 40, 64, skipNever, 8},
  69. {32, 258, 258, 1024, skipNever, 9},
  70. }
  71. // advancedState contains state for the advanced levels, with bigger hash tables, etc.
  72. type advancedState struct {
  73. // deflate state
  74. length int
  75. offset int
  76. maxInsertIndex int
  77. chainHead int
  78. hashOffset int
  79. ii uint16 // position of last match, intended to overflow to reset.
  80. // input window: unprocessed data is window[index:windowEnd]
  81. index int
  82. hashMatch [maxMatchLength + minMatchLength]uint32
  83. // Input hash chains
  84. // hashHead[hashValue] contains the largest inputIndex with the specified hash value
  85. // If hashHead[hashValue] is within the current window, then
  86. // hashPrev[hashHead[hashValue] & windowMask] contains the previous index
  87. // with the same hash value.
  88. hashHead [hashSize]uint32
  89. hashPrev [windowSize]uint32
  90. }
  91. type compressor struct {
  92. compressionLevel
  93. h *huffmanEncoder
  94. w *huffmanBitWriter
  95. // compression algorithm
  96. fill func(*compressor, []byte) int // copy data to window
  97. step func(*compressor) // process window
  98. window []byte
  99. windowEnd int
  100. blockStart int // window index where current tokens start
  101. err error
  102. // queued output tokens
  103. tokens tokens
  104. fast fastEnc
  105. state *advancedState
  106. sync bool // requesting flush
  107. byteAvailable bool // if true, still need to process window[index-1].
  108. }
  109. func (d *compressor) fillDeflate(b []byte) int {
  110. s := d.state
  111. if s.index >= 2*windowSize-(minMatchLength+maxMatchLength) {
  112. // shift the window by windowSize
  113. //copy(d.window[:], d.window[windowSize:2*windowSize])
  114. *(*[windowSize]byte)(d.window) = *(*[windowSize]byte)(d.window[windowSize:])
  115. s.index -= windowSize
  116. d.windowEnd -= windowSize
  117. if d.blockStart >= windowSize {
  118. d.blockStart -= windowSize
  119. } else {
  120. d.blockStart = math.MaxInt32
  121. }
  122. s.hashOffset += windowSize
  123. if s.hashOffset > maxHashOffset {
  124. delta := s.hashOffset - 1
  125. s.hashOffset -= delta
  126. s.chainHead -= delta
  127. // Iterate over slices instead of arrays to avoid copying
  128. // the entire table onto the stack (Issue #18625).
  129. for i, v := range s.hashPrev[:] {
  130. if int(v) > delta {
  131. s.hashPrev[i] = uint32(int(v) - delta)
  132. } else {
  133. s.hashPrev[i] = 0
  134. }
  135. }
  136. for i, v := range s.hashHead[:] {
  137. if int(v) > delta {
  138. s.hashHead[i] = uint32(int(v) - delta)
  139. } else {
  140. s.hashHead[i] = 0
  141. }
  142. }
  143. }
  144. }
  145. n := copy(d.window[d.windowEnd:], b)
  146. d.windowEnd += n
  147. return n
  148. }
  149. func (d *compressor) writeBlock(tok *tokens, index int, eof bool) error {
  150. if index > 0 || eof {
  151. var window []byte
  152. if d.blockStart <= index {
  153. window = d.window[d.blockStart:index]
  154. }
  155. d.blockStart = index
  156. //d.w.writeBlock(tok, eof, window)
  157. d.w.writeBlockDynamic(tok, eof, window, d.sync)
  158. return d.w.err
  159. }
  160. return nil
  161. }
  162. // writeBlockSkip writes the current block and uses the number of tokens
  163. // to determine if the block should be stored on no matches, or
  164. // only huffman encoded.
  165. func (d *compressor) writeBlockSkip(tok *tokens, index int, eof bool) error {
  166. if index > 0 || eof {
  167. if d.blockStart <= index {
  168. window := d.window[d.blockStart:index]
  169. // If we removed less than a 64th of all literals
  170. // we huffman compress the block.
  171. if int(tok.n) > len(window)-int(tok.n>>6) {
  172. d.w.writeBlockHuff(eof, window, d.sync)
  173. } else {
  174. // Write a dynamic huffman block.
  175. d.w.writeBlockDynamic(tok, eof, window, d.sync)
  176. }
  177. } else {
  178. d.w.writeBlock(tok, eof, nil)
  179. }
  180. d.blockStart = index
  181. return d.w.err
  182. }
  183. return nil
  184. }
  185. // fillWindow will fill the current window with the supplied
  186. // dictionary and calculate all hashes.
  187. // This is much faster than doing a full encode.
  188. // Should only be used after a start/reset.
  189. func (d *compressor) fillWindow(b []byte) {
  190. // Do not fill window if we are in store-only or huffman mode.
  191. if d.level <= 0 && d.level > -MinCustomWindowSize {
  192. return
  193. }
  194. if d.fast != nil {
  195. // encode the last data, but discard the result
  196. if len(b) > maxMatchOffset {
  197. b = b[len(b)-maxMatchOffset:]
  198. }
  199. d.fast.Encode(&d.tokens, b)
  200. d.tokens.Reset()
  201. return
  202. }
  203. s := d.state
  204. // If we are given too much, cut it.
  205. if len(b) > windowSize {
  206. b = b[len(b)-windowSize:]
  207. }
  208. // Add all to window.
  209. n := copy(d.window[d.windowEnd:], b)
  210. // Calculate 256 hashes at the time (more L1 cache hits)
  211. loops := (n + 256 - minMatchLength) / 256
  212. for j := range loops {
  213. startindex := j * 256
  214. end := min(startindex+256+minMatchLength-1, n)
  215. tocheck := d.window[startindex:end]
  216. dstSize := len(tocheck) - minMatchLength + 1
  217. if dstSize <= 0 {
  218. continue
  219. }
  220. dst := s.hashMatch[:dstSize]
  221. bulkHash4(tocheck, dst)
  222. var newH uint32
  223. for i, val := range dst {
  224. di := i + startindex
  225. newH = val & hashMask
  226. // Get previous value with the same hash.
  227. // Our chain should point to the previous value.
  228. s.hashPrev[di&windowMask] = s.hashHead[newH]
  229. // Set the head of the hash chain to us.
  230. s.hashHead[newH] = uint32(di + s.hashOffset)
  231. }
  232. }
  233. // Update window information.
  234. d.windowEnd += n
  235. s.index = n
  236. }
  237. // Try to find a match starting at index whose length is greater than prevSize.
  238. // We only look at chainCount possibilities before giving up.
  239. // pos = s.index, prevHead = s.chainHead-s.hashOffset, prevLength=minMatchLength-1, lookahead
  240. func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, offset int, ok bool) {
  241. minMatchLook := min(lookahead, maxMatchLength)
  242. win := d.window[0 : pos+minMatchLook]
  243. // We quit when we get a match that's at least nice long
  244. nice := min(d.nice, len(win)-pos)
  245. // If we've got a match that's good enough, only look in 1/4 the chain.
  246. tries := d.chain
  247. length = minMatchLength - 1
  248. wEnd := win[pos+length]
  249. wPos := win[pos:]
  250. minIndex := max(pos-windowSize, 0)
  251. offset = 0
  252. if d.chain < 100 {
  253. for i := prevHead; tries > 0; tries-- {
  254. if wEnd == win[i+length] {
  255. n := matchLen(win[i:i+minMatchLook], wPos)
  256. if n > length {
  257. length = n
  258. offset = pos - i
  259. ok = true
  260. if n >= nice {
  261. // The match is good enough that we don't try to find a better one.
  262. break
  263. }
  264. wEnd = win[pos+n]
  265. }
  266. }
  267. if i <= minIndex {
  268. // hashPrev[i & windowMask] has already been overwritten, so stop now.
  269. break
  270. }
  271. i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset
  272. if i < minIndex {
  273. break
  274. }
  275. }
  276. return
  277. }
  278. // Minimum gain to accept a match.
  279. cGain := 4
  280. // Some like it higher (CSV), some like it lower (JSON)
  281. const baseCost = 3
  282. // Base is 4 bytes at with an additional cost.
  283. // Matches must be better than this.
  284. for i := prevHead; tries > 0; tries-- {
  285. if wEnd == win[i+length] {
  286. n := matchLen(win[i:i+minMatchLook], wPos)
  287. if n > length {
  288. // Calculate gain. Estimate
  289. newGain := d.h.bitLengthRaw(wPos[:n]) - int(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int(lengthExtraBits[lengthCodes[(n-3)&255]])
  290. //fmt.Println("gain:", newGain, "prev:", cGain, "raw:", d.h.bitLengthRaw(wPos[:n]), "this-len:", n, "prev-len:", length)
  291. if newGain > cGain {
  292. length = n
  293. offset = pos - i
  294. cGain = newGain
  295. ok = true
  296. if n >= nice {
  297. // The match is good enough that we don't try to find a better one.
  298. break
  299. }
  300. wEnd = win[pos+n]
  301. }
  302. }
  303. }
  304. if i <= minIndex {
  305. // hashPrev[i & windowMask] has already been overwritten, so stop now.
  306. break
  307. }
  308. i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset
  309. if i < minIndex {
  310. break
  311. }
  312. }
  313. return
  314. }
  315. func (d *compressor) writeStoredBlock(buf []byte) error {
  316. if d.w.writeStoredHeader(len(buf), false); d.w.err != nil {
  317. return d.w.err
  318. }
  319. d.w.writeBytes(buf)
  320. return d.w.err
  321. }
  322. // hash4 returns a hash representation of the first 4 bytes
  323. // of the supplied slice.
  324. // The caller must ensure that len(b) >= 4.
  325. func hash4(b []byte) uint32 {
  326. return hash4u(le.Load32(b, 0), hashBits)
  327. }
  328. // hash4 returns the hash of u to fit in a hash table with h bits.
  329. // Preferably h should be a constant and should always be <32.
  330. func hash4u(u uint32, h uint8) uint32 {
  331. return (u * prime4bytes) >> (32 - h)
  332. }
  333. // bulkHash4 will compute hashes using the same
  334. // algorithm as hash4
  335. func bulkHash4(b []byte, dst []uint32) {
  336. if len(b) < 4 {
  337. return
  338. }
  339. hb := le.Load32(b, 0)
  340. dst[0] = hash4u(hb, hashBits)
  341. end := len(b) - 4 + 1
  342. for i := 1; i < end; i++ {
  343. hb = (hb >> 8) | uint32(b[i+3])<<24
  344. dst[i] = hash4u(hb, hashBits)
  345. }
  346. }
  347. func (d *compressor) initDeflate() {
  348. d.window = make([]byte, 2*windowSize)
  349. d.byteAvailable = false
  350. d.err = nil
  351. if d.state == nil {
  352. return
  353. }
  354. s := d.state
  355. s.index = 0
  356. s.hashOffset = 1
  357. s.length = minMatchLength - 1
  358. s.offset = 0
  359. s.chainHead = -1
  360. }
  361. // deflateLazy is the same as deflate, but with d.fastSkipHashing == skipNever,
  362. // meaning it always has lazy matching on.
  363. func (d *compressor) deflateLazy() {
  364. s := d.state
  365. // Sanity enables additional runtime tests.
  366. // It's intended to be used during development
  367. // to supplement the currently ad-hoc unit tests.
  368. const sanity = debugDeflate
  369. if d.windowEnd-s.index < minMatchLength+maxMatchLength && !d.sync {
  370. return
  371. }
  372. if d.windowEnd != s.index && d.chain > 100 {
  373. // Get literal huffman coder.
  374. if d.h == nil {
  375. d.h = newHuffmanEncoder(maxFlateBlockTokens)
  376. }
  377. var tmp [256]uint16
  378. toIndex := d.window[s.index:d.windowEnd]
  379. toIndex = toIndex[:min(len(toIndex), maxFlateBlockTokens)]
  380. for _, v := range toIndex {
  381. tmp[v]++
  382. }
  383. d.h.generate(tmp[:], 15)
  384. }
  385. s.maxInsertIndex = d.windowEnd - (minMatchLength - 1)
  386. for {
  387. if sanity && s.index > d.windowEnd {
  388. panic("index > windowEnd")
  389. }
  390. lookahead := d.windowEnd - s.index
  391. if lookahead < minMatchLength+maxMatchLength {
  392. if !d.sync {
  393. return
  394. }
  395. if sanity && s.index > d.windowEnd {
  396. panic("index > windowEnd")
  397. }
  398. if lookahead == 0 {
  399. // Flush current output block if any.
  400. if d.byteAvailable {
  401. // There is still one pending token that needs to be flushed
  402. d.tokens.AddLiteral(d.window[s.index-1])
  403. d.byteAvailable = false
  404. }
  405. if d.tokens.n > 0 {
  406. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  407. return
  408. }
  409. d.tokens.Reset()
  410. }
  411. return
  412. }
  413. }
  414. if s.index < s.maxInsertIndex {
  415. // Update the hash
  416. hash := hash4(d.window[s.index:])
  417. ch := s.hashHead[hash]
  418. s.chainHead = int(ch)
  419. s.hashPrev[s.index&windowMask] = ch
  420. s.hashHead[hash] = uint32(s.index + s.hashOffset)
  421. }
  422. prevLength := s.length
  423. prevOffset := s.offset
  424. s.length = minMatchLength - 1
  425. s.offset = 0
  426. minIndex := max(s.index-windowSize, 0)
  427. if s.chainHead-s.hashOffset >= minIndex && lookahead > prevLength && prevLength < d.lazy {
  428. if newLength, newOffset, ok := d.findMatch(s.index, s.chainHead-s.hashOffset, lookahead); ok {
  429. s.length = newLength
  430. s.offset = newOffset
  431. }
  432. }
  433. if prevLength >= minMatchLength && s.length <= prevLength {
  434. // No better match, but check for better match at end...
  435. //
  436. // Skip forward a number of bytes.
  437. // Offset of 2 seems to yield best results. 3 is sometimes better.
  438. const checkOff = 2
  439. // Check all, except full length
  440. if prevLength < maxMatchLength-checkOff {
  441. prevIndex := s.index - 1
  442. if prevIndex+prevLength < s.maxInsertIndex {
  443. end := min(lookahead, maxMatchLength+checkOff)
  444. end += prevIndex
  445. // Hash at match end.
  446. h := hash4(d.window[prevIndex+prevLength:])
  447. ch2 := int(s.hashHead[h]) - s.hashOffset - prevLength
  448. if prevIndex-ch2 != prevOffset && ch2 > minIndex+checkOff {
  449. length := matchLen(d.window[prevIndex+checkOff:end], d.window[ch2+checkOff:])
  450. // It seems like a pure length metric is best.
  451. if length > prevLength {
  452. prevLength = length
  453. prevOffset = prevIndex - ch2
  454. // Extend back...
  455. for i := checkOff - 1; i >= 0; i-- {
  456. if prevLength >= maxMatchLength || d.window[prevIndex+i] != d.window[ch2+i] {
  457. // Emit tokens we "owe"
  458. for j := 0; j <= i; j++ {
  459. d.tokens.AddLiteral(d.window[prevIndex+j])
  460. if d.tokens.n == maxFlateBlockTokens {
  461. // The block includes the current character
  462. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  463. return
  464. }
  465. d.tokens.Reset()
  466. }
  467. s.index++
  468. if s.index < s.maxInsertIndex {
  469. h := hash4(d.window[s.index:])
  470. ch := s.hashHead[h]
  471. s.chainHead = int(ch)
  472. s.hashPrev[s.index&windowMask] = ch
  473. s.hashHead[h] = uint32(s.index + s.hashOffset)
  474. }
  475. }
  476. break
  477. } else {
  478. prevLength++
  479. }
  480. }
  481. } else if false {
  482. // Check one further ahead.
  483. // Only rarely better, disabled for now.
  484. prevIndex++
  485. h := hash4(d.window[prevIndex+prevLength:])
  486. ch2 := int(s.hashHead[h]) - s.hashOffset - prevLength
  487. if prevIndex-ch2 != prevOffset && ch2 > minIndex+checkOff {
  488. length := matchLen(d.window[prevIndex+checkOff:end], d.window[ch2+checkOff:])
  489. // It seems like a pure length metric is best.
  490. if length > prevLength+checkOff {
  491. prevLength = length
  492. prevOffset = prevIndex - ch2
  493. prevIndex--
  494. // Extend back...
  495. for i := checkOff; i >= 0; i-- {
  496. if prevLength >= maxMatchLength || d.window[prevIndex+i] != d.window[ch2+i-1] {
  497. // Emit tokens we "owe"
  498. for j := 0; j <= i; j++ {
  499. d.tokens.AddLiteral(d.window[prevIndex+j])
  500. if d.tokens.n == maxFlateBlockTokens {
  501. // The block includes the current character
  502. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  503. return
  504. }
  505. d.tokens.Reset()
  506. }
  507. s.index++
  508. if s.index < s.maxInsertIndex {
  509. h := hash4(d.window[s.index:])
  510. ch := s.hashHead[h]
  511. s.chainHead = int(ch)
  512. s.hashPrev[s.index&windowMask] = ch
  513. s.hashHead[h] = uint32(s.index + s.hashOffset)
  514. }
  515. }
  516. break
  517. } else {
  518. prevLength++
  519. }
  520. }
  521. }
  522. }
  523. }
  524. }
  525. }
  526. }
  527. // There was a match at the previous step, and the current match is
  528. // not better. Output the previous match.
  529. d.tokens.AddMatch(uint32(prevLength-3), uint32(prevOffset-minOffsetSize))
  530. // Insert in the hash table all strings up to the end of the match.
  531. // index and index-1 are already inserted. If there is not enough
  532. // lookahead, the last two strings are not inserted into the hash
  533. // table.
  534. newIndex := s.index + prevLength - 1
  535. // Calculate missing hashes
  536. end := min(newIndex, s.maxInsertIndex)
  537. end += minMatchLength - 1
  538. startindex := min(s.index+1, s.maxInsertIndex)
  539. tocheck := d.window[startindex:end]
  540. dstSize := len(tocheck) - minMatchLength + 1
  541. if dstSize > 0 {
  542. dst := s.hashMatch[:dstSize]
  543. bulkHash4(tocheck, dst)
  544. var newH uint32
  545. for i, val := range dst {
  546. di := i + startindex
  547. newH = val & hashMask
  548. // Get previous value with the same hash.
  549. // Our chain should point to the previous value.
  550. s.hashPrev[di&windowMask] = s.hashHead[newH]
  551. // Set the head of the hash chain to us.
  552. s.hashHead[newH] = uint32(di + s.hashOffset)
  553. }
  554. }
  555. s.index = newIndex
  556. d.byteAvailable = false
  557. s.length = minMatchLength - 1
  558. if d.tokens.n == maxFlateBlockTokens {
  559. // The block includes the current character
  560. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  561. return
  562. }
  563. d.tokens.Reset()
  564. }
  565. s.ii = 0
  566. } else {
  567. // Reset, if we got a match this run.
  568. if s.length >= minMatchLength {
  569. s.ii = 0
  570. }
  571. // We have a byte waiting. Emit it.
  572. if d.byteAvailable {
  573. s.ii++
  574. d.tokens.AddLiteral(d.window[s.index-1])
  575. if d.tokens.n == maxFlateBlockTokens {
  576. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  577. return
  578. }
  579. d.tokens.Reset()
  580. }
  581. s.index++
  582. // If we have a long run of no matches, skip additional bytes
  583. // Resets when s.ii overflows after 64KB.
  584. if n := int(s.ii) - d.chain; n > 0 {
  585. n = 1 + int(n>>6)
  586. for j := 0; j < n; j++ {
  587. if s.index >= d.windowEnd-1 {
  588. break
  589. }
  590. d.tokens.AddLiteral(d.window[s.index-1])
  591. if d.tokens.n == maxFlateBlockTokens {
  592. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  593. return
  594. }
  595. d.tokens.Reset()
  596. }
  597. // Index...
  598. if s.index < s.maxInsertIndex {
  599. h := hash4(d.window[s.index:])
  600. ch := s.hashHead[h]
  601. s.chainHead = int(ch)
  602. s.hashPrev[s.index&windowMask] = ch
  603. s.hashHead[h] = uint32(s.index + s.hashOffset)
  604. }
  605. s.index++
  606. }
  607. // Flush last byte
  608. d.tokens.AddLiteral(d.window[s.index-1])
  609. d.byteAvailable = false
  610. // s.length = minMatchLength - 1 // not needed, since s.ii is reset above, so it should never be > minMatchLength
  611. if d.tokens.n == maxFlateBlockTokens {
  612. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  613. return
  614. }
  615. d.tokens.Reset()
  616. }
  617. }
  618. } else {
  619. s.index++
  620. d.byteAvailable = true
  621. }
  622. }
  623. }
  624. }
  625. func (d *compressor) store() {
  626. if d.windowEnd > 0 && (d.windowEnd == maxStoreBlockSize || d.sync) {
  627. d.err = d.writeStoredBlock(d.window[:d.windowEnd])
  628. d.windowEnd = 0
  629. }
  630. }
  631. // fillWindow will fill the buffer with data for huffman-only compression.
  632. // The number of bytes copied is returned.
  633. func (d *compressor) fillBlock(b []byte) int {
  634. n := copy(d.window[d.windowEnd:], b)
  635. d.windowEnd += n
  636. return n
  637. }
  638. // storeHuff will compress and store the currently added data,
  639. // if enough has been accumulated or we at the end of the stream.
  640. // Any error that occurred will be in d.err
  641. func (d *compressor) storeHuff() {
  642. if d.windowEnd < len(d.window) && !d.sync || d.windowEnd == 0 {
  643. return
  644. }
  645. d.w.writeBlockHuff(false, d.window[:d.windowEnd], d.sync)
  646. d.err = d.w.err
  647. d.windowEnd = 0
  648. }
  649. // storeFast will compress and store the currently added data,
  650. // if enough has been accumulated or we at the end of the stream.
  651. // Any error that occurred will be in d.err
  652. func (d *compressor) storeFast() {
  653. // We only compress if we have maxStoreBlockSize.
  654. if d.windowEnd < len(d.window) {
  655. if !d.sync {
  656. return
  657. }
  658. // Handle extremely small sizes.
  659. if d.windowEnd < 128 {
  660. if d.windowEnd == 0 {
  661. return
  662. }
  663. if d.windowEnd <= 32 {
  664. d.err = d.writeStoredBlock(d.window[:d.windowEnd])
  665. } else {
  666. d.w.writeBlockHuff(false, d.window[:d.windowEnd], true)
  667. d.err = d.w.err
  668. }
  669. d.tokens.Reset()
  670. d.windowEnd = 0
  671. d.fast.Reset()
  672. return
  673. }
  674. }
  675. d.fast.Encode(&d.tokens, d.window[:d.windowEnd])
  676. // If we made zero matches, store the block as is.
  677. if d.tokens.n == 0 {
  678. d.err = d.writeStoredBlock(d.window[:d.windowEnd])
  679. // If we removed less than 1/16th, huffman compress the block.
  680. } else if int(d.tokens.n) > d.windowEnd-(d.windowEnd>>4) {
  681. d.w.writeBlockHuff(false, d.window[:d.windowEnd], d.sync)
  682. d.err = d.w.err
  683. } else {
  684. d.w.writeBlockDynamic(&d.tokens, false, d.window[:d.windowEnd], d.sync)
  685. d.err = d.w.err
  686. }
  687. d.tokens.Reset()
  688. d.windowEnd = 0
  689. }
  690. // write will add input byte to the stream.
  691. // Unless an error occurs all bytes will be consumed.
  692. func (d *compressor) write(b []byte) (n int, err error) {
  693. if d.err != nil {
  694. return 0, d.err
  695. }
  696. n = len(b)
  697. for len(b) > 0 {
  698. if d.windowEnd == len(d.window) || d.sync {
  699. d.step(d)
  700. }
  701. b = b[d.fill(d, b):]
  702. if d.err != nil {
  703. return 0, d.err
  704. }
  705. }
  706. return n, d.err
  707. }
  708. func (d *compressor) syncFlush() error {
  709. d.sync = true
  710. if d.err != nil {
  711. return d.err
  712. }
  713. d.step(d)
  714. if d.err == nil {
  715. d.w.writeStoredHeader(0, false)
  716. d.w.flush()
  717. d.err = d.w.err
  718. }
  719. d.sync = false
  720. return d.err
  721. }
  722. func (d *compressor) init(w io.Writer, level int) (err error) {
  723. d.w = newHuffmanBitWriter(w)
  724. switch {
  725. case level == NoCompression:
  726. d.window = make([]byte, maxStoreBlockSize)
  727. d.fill = (*compressor).fillBlock
  728. d.step = (*compressor).store
  729. case level == ConstantCompression:
  730. d.w.logNewTablePenalty = 10
  731. d.window = make([]byte, 32<<10)
  732. d.fill = (*compressor).fillBlock
  733. d.step = (*compressor).storeHuff
  734. case level == DefaultCompression:
  735. level = 5
  736. fallthrough
  737. case level >= 1 && level <= 6:
  738. d.w.logNewTablePenalty = 7
  739. d.fast = newFastEnc(level)
  740. d.window = make([]byte, maxStoreBlockSize)
  741. d.fill = (*compressor).fillBlock
  742. d.step = (*compressor).storeFast
  743. case 7 <= level && level <= 9:
  744. d.w.logNewTablePenalty = 8
  745. d.state = &advancedState{}
  746. d.compressionLevel = levels[level]
  747. d.initDeflate()
  748. d.fill = (*compressor).fillDeflate
  749. d.step = (*compressor).deflateLazy
  750. case -level >= MinCustomWindowSize && -level <= MaxCustomWindowSize:
  751. d.w.logNewTablePenalty = 7
  752. d.fast = &fastEncL5Window{maxOffset: int32(-level), cur: maxStoreBlockSize}
  753. d.window = make([]byte, maxStoreBlockSize)
  754. d.fill = (*compressor).fillBlock
  755. d.step = (*compressor).storeFast
  756. default:
  757. return fmt.Errorf("flate: invalid compression level %d: want value in range [-2, 9]", level)
  758. }
  759. d.level = level
  760. return nil
  761. }
  762. // reset the state of the compressor.
  763. func (d *compressor) reset(w io.Writer) {
  764. d.w.reset(w)
  765. d.sync = false
  766. d.err = nil
  767. // We only need to reset a few things for Snappy.
  768. if d.fast != nil {
  769. d.fast.Reset()
  770. d.windowEnd = 0
  771. d.tokens.Reset()
  772. return
  773. }
  774. switch d.compressionLevel.chain {
  775. case 0:
  776. // level was NoCompression or ConstantCompression.
  777. d.windowEnd = 0
  778. default:
  779. s := d.state
  780. s.chainHead = -1
  781. for i := range s.hashHead {
  782. s.hashHead[i] = 0
  783. }
  784. for i := range s.hashPrev {
  785. s.hashPrev[i] = 0
  786. }
  787. s.hashOffset = 1
  788. s.index, d.windowEnd = 0, 0
  789. d.blockStart, d.byteAvailable = 0, false
  790. d.tokens.Reset()
  791. s.length = minMatchLength - 1
  792. s.offset = 0
  793. s.ii = 0
  794. s.maxInsertIndex = 0
  795. }
  796. }
  797. func (d *compressor) close() error {
  798. if d.err != nil {
  799. return d.err
  800. }
  801. d.sync = true
  802. d.step(d)
  803. if d.err != nil {
  804. return d.err
  805. }
  806. if d.w.writeStoredHeader(0, true); d.w.err != nil {
  807. return d.w.err
  808. }
  809. d.w.flush()
  810. d.w.reset(nil)
  811. return d.w.err
  812. }
  813. // NewWriter returns a new Writer compressing data at the given level.
  814. // Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression);
  815. // higher levels typically run slower but compress more.
  816. // Level 0 (NoCompression) does not attempt any compression; it only adds the
  817. // necessary DEFLATE framing.
  818. // Level -1 (DefaultCompression) uses the default compression level.
  819. // Level -2 (ConstantCompression) will use Huffman compression only, giving
  820. // a very fast compression for all types of input, but sacrificing considerable
  821. // compression efficiency.
  822. //
  823. // If level is in the range [-2, 9] then the error returned will be nil.
  824. // Otherwise the error returned will be non-nil.
  825. func NewWriter(w io.Writer, level int) (*Writer, error) {
  826. var dw Writer
  827. if err := dw.d.init(w, level); err != nil {
  828. return nil, err
  829. }
  830. return &dw, nil
  831. }
  832. // NewWriterDict is like NewWriter but initializes the new
  833. // Writer with a preset dictionary. The returned Writer behaves
  834. // as if the dictionary had been written to it without producing
  835. // any compressed output. The compressed data written to w
  836. // can only be decompressed by a Reader initialized with the
  837. // same dictionary.
  838. func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) {
  839. zw, err := NewWriter(w, level)
  840. if err != nil {
  841. return nil, err
  842. }
  843. zw.d.fillWindow(dict)
  844. zw.dict = append(zw.dict, dict...) // duplicate dictionary for Reset method.
  845. return zw, err
  846. }
  847. // MinCustomWindowSize is the minimum window size that can be sent to NewWriterWindow.
  848. const MinCustomWindowSize = 32
  849. // MaxCustomWindowSize is the maximum custom window that can be sent to NewWriterWindow.
  850. const MaxCustomWindowSize = windowSize
  851. // NewWriterWindow returns a new Writer compressing data with a custom window size.
  852. // windowSize must be from MinCustomWindowSize to MaxCustomWindowSize.
  853. func NewWriterWindow(w io.Writer, windowSize int) (*Writer, error) {
  854. if windowSize < MinCustomWindowSize {
  855. return nil, errors.New("flate: requested window size less than MinWindowSize")
  856. }
  857. if windowSize > MaxCustomWindowSize {
  858. return nil, errors.New("flate: requested window size bigger than MaxCustomWindowSize")
  859. }
  860. var dw Writer
  861. if err := dw.d.init(w, -windowSize); err != nil {
  862. return nil, err
  863. }
  864. return &dw, nil
  865. }
  866. // A Writer takes data written to it and writes the compressed
  867. // form of that data to an underlying writer (see NewWriter).
  868. type Writer struct {
  869. d compressor
  870. dict []byte
  871. }
  872. // Write writes data to w, which will eventually write the
  873. // compressed form of data to its underlying writer.
  874. func (w *Writer) Write(data []byte) (n int, err error) {
  875. return w.d.write(data)
  876. }
  877. // Flush flushes any pending data to the underlying writer.
  878. // It is useful mainly in compressed network protocols, to ensure that
  879. // a remote reader has enough data to reconstruct a packet.
  880. // Flush does not return until the data has been written.
  881. // Calling Flush when there is no pending data still causes the Writer
  882. // to emit a sync marker of at least 4 bytes.
  883. // If the underlying writer returns an error, Flush returns that error.
  884. //
  885. // In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
  886. func (w *Writer) Flush() error {
  887. // For more about flushing:
  888. // http://www.bolet.org/~pornin/deflate-flush.html
  889. return w.d.syncFlush()
  890. }
  891. // Close flushes and closes the writer.
  892. func (w *Writer) Close() error {
  893. return w.d.close()
  894. }
  895. // Reset discards the writer's state and makes it equivalent to
  896. // the result of NewWriter or NewWriterDict called with dst
  897. // and w's level and dictionary.
  898. func (w *Writer) Reset(dst io.Writer) {
  899. if len(w.dict) > 0 {
  900. // w was created with NewWriterDict
  901. w.d.reset(dst)
  902. if dst != nil {
  903. w.d.fillWindow(w.dict)
  904. }
  905. } else {
  906. // w was created with NewWriter
  907. w.d.reset(dst)
  908. }
  909. }
  910. // ResetDict discards the writer's state and makes it equivalent to
  911. // the result of NewWriter or NewWriterDict called with dst
  912. // and w's level, but sets a specific dictionary.
  913. func (w *Writer) ResetDict(dst io.Writer, dict []byte) {
  914. w.dict = dict
  915. w.d.reset(dst)
  916. w.d.fillWindow(w.dict)
  917. }