deflate.go 27 KB

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