deflate.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. "errors"
  9. "fmt"
  10. "io"
  11. "math"
  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 := 0; j < loops; j++ {
  213. startindex := j * 256
  214. end := startindex + 256 + minMatchLength - 1
  215. if end > n {
  216. end = n
  217. }
  218. tocheck := d.window[startindex:end]
  219. dstSize := len(tocheck) - minMatchLength + 1
  220. if dstSize <= 0 {
  221. continue
  222. }
  223. dst := s.hashMatch[:dstSize]
  224. bulkHash4(tocheck, dst)
  225. var newH uint32
  226. for i, val := range dst {
  227. di := i + startindex
  228. newH = val & hashMask
  229. // Get previous value with the same hash.
  230. // Our chain should point to the previous value.
  231. s.hashPrev[di&windowMask] = s.hashHead[newH]
  232. // Set the head of the hash chain to us.
  233. s.hashHead[newH] = uint32(di + s.hashOffset)
  234. }
  235. }
  236. // Update window information.
  237. d.windowEnd += n
  238. s.index = n
  239. }
  240. // Try to find a match starting at index whose length is greater than prevSize.
  241. // We only look at chainCount possibilities before giving up.
  242. // pos = s.index, prevHead = s.chainHead-s.hashOffset, prevLength=minMatchLength-1, lookahead
  243. func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, offset int, ok bool) {
  244. minMatchLook := maxMatchLength
  245. if lookahead < minMatchLook {
  246. minMatchLook = lookahead
  247. }
  248. win := d.window[0 : pos+minMatchLook]
  249. // We quit when we get a match that's at least nice long
  250. nice := len(win) - pos
  251. if d.nice < nice {
  252. nice = d.nice
  253. }
  254. // If we've got a match that's good enough, only look in 1/4 the chain.
  255. tries := d.chain
  256. length = minMatchLength - 1
  257. wEnd := win[pos+length]
  258. wPos := win[pos:]
  259. minIndex := pos - windowSize
  260. if minIndex < 0 {
  261. minIndex = 0
  262. }
  263. offset = 0
  264. if d.chain < 100 {
  265. for i := prevHead; tries > 0; tries-- {
  266. if wEnd == win[i+length] {
  267. n := matchLen(win[i:i+minMatchLook], wPos)
  268. if n > length {
  269. length = n
  270. offset = pos - i
  271. ok = true
  272. if n >= nice {
  273. // The match is good enough that we don't try to find a better one.
  274. break
  275. }
  276. wEnd = win[pos+n]
  277. }
  278. }
  279. if i <= minIndex {
  280. // hashPrev[i & windowMask] has already been overwritten, so stop now.
  281. break
  282. }
  283. i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset
  284. if i < minIndex {
  285. break
  286. }
  287. }
  288. return
  289. }
  290. // Minimum gain to accept a match.
  291. cGain := 4
  292. // Some like it higher (CSV), some like it lower (JSON)
  293. const baseCost = 3
  294. // Base is 4 bytes at with an additional cost.
  295. // Matches must be better than this.
  296. for i := prevHead; tries > 0; tries-- {
  297. if wEnd == win[i+length] {
  298. n := matchLen(win[i:i+minMatchLook], wPos)
  299. if n > length {
  300. // Calculate gain. Estimate
  301. newGain := d.h.bitLengthRaw(wPos[:n]) - int(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int(lengthExtraBits[lengthCodes[(n-3)&255]])
  302. //fmt.Println("gain:", newGain, "prev:", cGain, "raw:", d.h.bitLengthRaw(wPos[:n]), "this-len:", n, "prev-len:", length)
  303. if newGain > cGain {
  304. length = n
  305. offset = pos - i
  306. cGain = newGain
  307. ok = true
  308. if n >= nice {
  309. // The match is good enough that we don't try to find a better one.
  310. break
  311. }
  312. wEnd = win[pos+n]
  313. }
  314. }
  315. }
  316. if i <= minIndex {
  317. // hashPrev[i & windowMask] has already been overwritten, so stop now.
  318. break
  319. }
  320. i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset
  321. if i < minIndex {
  322. break
  323. }
  324. }
  325. return
  326. }
  327. func (d *compressor) writeStoredBlock(buf []byte) error {
  328. if d.w.writeStoredHeader(len(buf), false); d.w.err != nil {
  329. return d.w.err
  330. }
  331. d.w.writeBytes(buf)
  332. return d.w.err
  333. }
  334. // hash4 returns a hash representation of the first 4 bytes
  335. // of the supplied slice.
  336. // The caller must ensure that len(b) >= 4.
  337. func hash4(b []byte) uint32 {
  338. return hash4u(binary.LittleEndian.Uint32(b), hashBits)
  339. }
  340. // hash4 returns the hash of u to fit in a hash table with h bits.
  341. // Preferably h should be a constant and should always be <32.
  342. func hash4u(u uint32, h uint8) uint32 {
  343. return (u * prime4bytes) >> (32 - h)
  344. }
  345. // bulkHash4 will compute hashes using the same
  346. // algorithm as hash4
  347. func bulkHash4(b []byte, dst []uint32) {
  348. if len(b) < 4 {
  349. return
  350. }
  351. hb := binary.LittleEndian.Uint32(b)
  352. dst[0] = hash4u(hb, hashBits)
  353. end := len(b) - 4 + 1
  354. for i := 1; i < end; i++ {
  355. hb = (hb >> 8) | uint32(b[i+3])<<24
  356. dst[i] = hash4u(hb, hashBits)
  357. }
  358. }
  359. func (d *compressor) initDeflate() {
  360. d.window = make([]byte, 2*windowSize)
  361. d.byteAvailable = false
  362. d.err = nil
  363. if d.state == nil {
  364. return
  365. }
  366. s := d.state
  367. s.index = 0
  368. s.hashOffset = 1
  369. s.length = minMatchLength - 1
  370. s.offset = 0
  371. s.chainHead = -1
  372. }
  373. // deflateLazy is the same as deflate, but with d.fastSkipHashing == skipNever,
  374. // meaning it always has lazy matching on.
  375. func (d *compressor) deflateLazy() {
  376. s := d.state
  377. // Sanity enables additional runtime tests.
  378. // It's intended to be used during development
  379. // to supplement the currently ad-hoc unit tests.
  380. const sanity = debugDeflate
  381. if d.windowEnd-s.index < minMatchLength+maxMatchLength && !d.sync {
  382. return
  383. }
  384. if d.windowEnd != s.index && d.chain > 100 {
  385. // Get literal huffman coder.
  386. if d.h == nil {
  387. d.h = newHuffmanEncoder(maxFlateBlockTokens)
  388. }
  389. var tmp [256]uint16
  390. for _, v := range d.window[s.index:d.windowEnd] {
  391. tmp[v]++
  392. }
  393. d.h.generate(tmp[:], 15)
  394. }
  395. s.maxInsertIndex = d.windowEnd - (minMatchLength - 1)
  396. for {
  397. if sanity && s.index > d.windowEnd {
  398. panic("index > windowEnd")
  399. }
  400. lookahead := d.windowEnd - s.index
  401. if lookahead < minMatchLength+maxMatchLength {
  402. if !d.sync {
  403. return
  404. }
  405. if sanity && s.index > d.windowEnd {
  406. panic("index > windowEnd")
  407. }
  408. if lookahead == 0 {
  409. // Flush current output block if any.
  410. if d.byteAvailable {
  411. // There is still one pending token that needs to be flushed
  412. d.tokens.AddLiteral(d.window[s.index-1])
  413. d.byteAvailable = false
  414. }
  415. if d.tokens.n > 0 {
  416. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  417. return
  418. }
  419. d.tokens.Reset()
  420. }
  421. return
  422. }
  423. }
  424. if s.index < s.maxInsertIndex {
  425. // Update the hash
  426. hash := hash4(d.window[s.index:])
  427. ch := s.hashHead[hash]
  428. s.chainHead = int(ch)
  429. s.hashPrev[s.index&windowMask] = ch
  430. s.hashHead[hash] = uint32(s.index + s.hashOffset)
  431. }
  432. prevLength := s.length
  433. prevOffset := s.offset
  434. s.length = minMatchLength - 1
  435. s.offset = 0
  436. minIndex := s.index - windowSize
  437. if minIndex < 0 {
  438. minIndex = 0
  439. }
  440. if s.chainHead-s.hashOffset >= minIndex && lookahead > prevLength && prevLength < d.lazy {
  441. if newLength, newOffset, ok := d.findMatch(s.index, s.chainHead-s.hashOffset, lookahead); ok {
  442. s.length = newLength
  443. s.offset = newOffset
  444. }
  445. }
  446. if prevLength >= minMatchLength && s.length <= prevLength {
  447. // No better match, but check for better match at end...
  448. //
  449. // Skip forward a number of bytes.
  450. // Offset of 2 seems to yield best results. 3 is sometimes better.
  451. const checkOff = 2
  452. // Check all, except full length
  453. if prevLength < maxMatchLength-checkOff {
  454. prevIndex := s.index - 1
  455. if prevIndex+prevLength < s.maxInsertIndex {
  456. end := lookahead
  457. if lookahead > maxMatchLength+checkOff {
  458. end = maxMatchLength + checkOff
  459. }
  460. end += prevIndex
  461. // Hash at match end.
  462. h := hash4(d.window[prevIndex+prevLength:])
  463. ch2 := int(s.hashHead[h]) - s.hashOffset - prevLength
  464. if prevIndex-ch2 != prevOffset && ch2 > minIndex+checkOff {
  465. length := matchLen(d.window[prevIndex+checkOff:end], d.window[ch2+checkOff:])
  466. // It seems like a pure length metric is best.
  467. if length > prevLength {
  468. prevLength = length
  469. prevOffset = prevIndex - ch2
  470. // Extend back...
  471. for i := checkOff - 1; i >= 0; i-- {
  472. if prevLength >= maxMatchLength || d.window[prevIndex+i] != d.window[ch2+i] {
  473. // Emit tokens we "owe"
  474. for j := 0; j <= i; j++ {
  475. d.tokens.AddLiteral(d.window[prevIndex+j])
  476. if d.tokens.n == maxFlateBlockTokens {
  477. // The block includes the current character
  478. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  479. return
  480. }
  481. d.tokens.Reset()
  482. }
  483. s.index++
  484. if s.index < s.maxInsertIndex {
  485. h := hash4(d.window[s.index:])
  486. ch := s.hashHead[h]
  487. s.chainHead = int(ch)
  488. s.hashPrev[s.index&windowMask] = ch
  489. s.hashHead[h] = uint32(s.index + s.hashOffset)
  490. }
  491. }
  492. break
  493. } else {
  494. prevLength++
  495. }
  496. }
  497. } else if false {
  498. // Check one further ahead.
  499. // Only rarely better, disabled for now.
  500. prevIndex++
  501. h := hash4(d.window[prevIndex+prevLength:])
  502. ch2 := int(s.hashHead[h]) - s.hashOffset - prevLength
  503. if prevIndex-ch2 != prevOffset && ch2 > minIndex+checkOff {
  504. length := matchLen(d.window[prevIndex+checkOff:end], d.window[ch2+checkOff:])
  505. // It seems like a pure length metric is best.
  506. if length > prevLength+checkOff {
  507. prevLength = length
  508. prevOffset = prevIndex - ch2
  509. prevIndex--
  510. // Extend back...
  511. for i := checkOff; i >= 0; i-- {
  512. if prevLength >= maxMatchLength || d.window[prevIndex+i] != d.window[ch2+i-1] {
  513. // Emit tokens we "owe"
  514. for j := 0; j <= i; j++ {
  515. d.tokens.AddLiteral(d.window[prevIndex+j])
  516. if d.tokens.n == maxFlateBlockTokens {
  517. // The block includes the current character
  518. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  519. return
  520. }
  521. d.tokens.Reset()
  522. }
  523. s.index++
  524. if s.index < s.maxInsertIndex {
  525. h := hash4(d.window[s.index:])
  526. ch := s.hashHead[h]
  527. s.chainHead = int(ch)
  528. s.hashPrev[s.index&windowMask] = ch
  529. s.hashHead[h] = uint32(s.index + s.hashOffset)
  530. }
  531. }
  532. break
  533. } else {
  534. prevLength++
  535. }
  536. }
  537. }
  538. }
  539. }
  540. }
  541. }
  542. }
  543. // There was a match at the previous step, and the current match is
  544. // not better. Output the previous match.
  545. d.tokens.AddMatch(uint32(prevLength-3), uint32(prevOffset-minOffsetSize))
  546. // Insert in the hash table all strings up to the end of the match.
  547. // index and index-1 are already inserted. If there is not enough
  548. // lookahead, the last two strings are not inserted into the hash
  549. // table.
  550. newIndex := s.index + prevLength - 1
  551. // Calculate missing hashes
  552. end := newIndex
  553. if end > s.maxInsertIndex {
  554. end = s.maxInsertIndex
  555. }
  556. end += minMatchLength - 1
  557. startindex := s.index + 1
  558. if startindex > s.maxInsertIndex {
  559. startindex = s.maxInsertIndex
  560. }
  561. tocheck := d.window[startindex:end]
  562. dstSize := len(tocheck) - minMatchLength + 1
  563. if dstSize > 0 {
  564. dst := s.hashMatch[:dstSize]
  565. bulkHash4(tocheck, dst)
  566. var newH uint32
  567. for i, val := range dst {
  568. di := i + startindex
  569. newH = val & hashMask
  570. // Get previous value with the same hash.
  571. // Our chain should point to the previous value.
  572. s.hashPrev[di&windowMask] = s.hashHead[newH]
  573. // Set the head of the hash chain to us.
  574. s.hashHead[newH] = uint32(di + s.hashOffset)
  575. }
  576. }
  577. s.index = newIndex
  578. d.byteAvailable = false
  579. s.length = minMatchLength - 1
  580. if d.tokens.n == maxFlateBlockTokens {
  581. // The block includes the current character
  582. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  583. return
  584. }
  585. d.tokens.Reset()
  586. }
  587. s.ii = 0
  588. } else {
  589. // Reset, if we got a match this run.
  590. if s.length >= minMatchLength {
  591. s.ii = 0
  592. }
  593. // We have a byte waiting. Emit it.
  594. if d.byteAvailable {
  595. s.ii++
  596. d.tokens.AddLiteral(d.window[s.index-1])
  597. if d.tokens.n == maxFlateBlockTokens {
  598. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  599. return
  600. }
  601. d.tokens.Reset()
  602. }
  603. s.index++
  604. // If we have a long run of no matches, skip additional bytes
  605. // Resets when s.ii overflows after 64KB.
  606. if n := int(s.ii) - d.chain; n > 0 {
  607. n = 1 + int(n>>6)
  608. for j := 0; j < n; j++ {
  609. if s.index >= d.windowEnd-1 {
  610. break
  611. }
  612. d.tokens.AddLiteral(d.window[s.index-1])
  613. if d.tokens.n == maxFlateBlockTokens {
  614. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  615. return
  616. }
  617. d.tokens.Reset()
  618. }
  619. // Index...
  620. if s.index < s.maxInsertIndex {
  621. h := hash4(d.window[s.index:])
  622. ch := s.hashHead[h]
  623. s.chainHead = int(ch)
  624. s.hashPrev[s.index&windowMask] = ch
  625. s.hashHead[h] = uint32(s.index + s.hashOffset)
  626. }
  627. s.index++
  628. }
  629. // Flush last byte
  630. d.tokens.AddLiteral(d.window[s.index-1])
  631. d.byteAvailable = false
  632. // s.length = minMatchLength - 1 // not needed, since s.ii is reset above, so it should never be > minMatchLength
  633. if d.tokens.n == maxFlateBlockTokens {
  634. if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil {
  635. return
  636. }
  637. d.tokens.Reset()
  638. }
  639. }
  640. } else {
  641. s.index++
  642. d.byteAvailable = true
  643. }
  644. }
  645. }
  646. }
  647. func (d *compressor) store() {
  648. if d.windowEnd > 0 && (d.windowEnd == maxStoreBlockSize || d.sync) {
  649. d.err = d.writeStoredBlock(d.window[:d.windowEnd])
  650. d.windowEnd = 0
  651. }
  652. }
  653. // fillWindow will fill the buffer with data for huffman-only compression.
  654. // The number of bytes copied is returned.
  655. func (d *compressor) fillBlock(b []byte) int {
  656. n := copy(d.window[d.windowEnd:], b)
  657. d.windowEnd += n
  658. return n
  659. }
  660. // storeHuff will compress and store the currently added data,
  661. // if enough has been accumulated or we at the end of the stream.
  662. // Any error that occurred will be in d.err
  663. func (d *compressor) storeHuff() {
  664. if d.windowEnd < len(d.window) && !d.sync || d.windowEnd == 0 {
  665. return
  666. }
  667. d.w.writeBlockHuff(false, d.window[:d.windowEnd], d.sync)
  668. d.err = d.w.err
  669. d.windowEnd = 0
  670. }
  671. // storeFast will compress and store the currently added data,
  672. // if enough has been accumulated or we at the end of the stream.
  673. // Any error that occurred will be in d.err
  674. func (d *compressor) storeFast() {
  675. // We only compress if we have maxStoreBlockSize.
  676. if d.windowEnd < len(d.window) {
  677. if !d.sync {
  678. return
  679. }
  680. // Handle extremely small sizes.
  681. if d.windowEnd < 128 {
  682. if d.windowEnd == 0 {
  683. return
  684. }
  685. if d.windowEnd <= 32 {
  686. d.err = d.writeStoredBlock(d.window[:d.windowEnd])
  687. } else {
  688. d.w.writeBlockHuff(false, d.window[:d.windowEnd], true)
  689. d.err = d.w.err
  690. }
  691. d.tokens.Reset()
  692. d.windowEnd = 0
  693. d.fast.Reset()
  694. return
  695. }
  696. }
  697. d.fast.Encode(&d.tokens, d.window[:d.windowEnd])
  698. // If we made zero matches, store the block as is.
  699. if d.tokens.n == 0 {
  700. d.err = d.writeStoredBlock(d.window[:d.windowEnd])
  701. // If we removed less than 1/16th, huffman compress the block.
  702. } else if int(d.tokens.n) > d.windowEnd-(d.windowEnd>>4) {
  703. d.w.writeBlockHuff(false, d.window[:d.windowEnd], d.sync)
  704. d.err = d.w.err
  705. } else {
  706. d.w.writeBlockDynamic(&d.tokens, false, d.window[:d.windowEnd], d.sync)
  707. d.err = d.w.err
  708. }
  709. d.tokens.Reset()
  710. d.windowEnd = 0
  711. }
  712. // write will add input byte to the stream.
  713. // Unless an error occurs all bytes will be consumed.
  714. func (d *compressor) write(b []byte) (n int, err error) {
  715. if d.err != nil {
  716. return 0, d.err
  717. }
  718. n = len(b)
  719. for len(b) > 0 {
  720. if d.windowEnd == len(d.window) || d.sync {
  721. d.step(d)
  722. }
  723. b = b[d.fill(d, b):]
  724. if d.err != nil {
  725. return 0, d.err
  726. }
  727. }
  728. return n, d.err
  729. }
  730. func (d *compressor) syncFlush() error {
  731. d.sync = true
  732. if d.err != nil {
  733. return d.err
  734. }
  735. d.step(d)
  736. if d.err == nil {
  737. d.w.writeStoredHeader(0, false)
  738. d.w.flush()
  739. d.err = d.w.err
  740. }
  741. d.sync = false
  742. return d.err
  743. }
  744. func (d *compressor) init(w io.Writer, level int) (err error) {
  745. d.w = newHuffmanBitWriter(w)
  746. switch {
  747. case level == NoCompression:
  748. d.window = make([]byte, maxStoreBlockSize)
  749. d.fill = (*compressor).fillBlock
  750. d.step = (*compressor).store
  751. case level == ConstantCompression:
  752. d.w.logNewTablePenalty = 10
  753. d.window = make([]byte, 32<<10)
  754. d.fill = (*compressor).fillBlock
  755. d.step = (*compressor).storeHuff
  756. case level == DefaultCompression:
  757. level = 5
  758. fallthrough
  759. case level >= 1 && level <= 6:
  760. d.w.logNewTablePenalty = 7
  761. d.fast = newFastEnc(level)
  762. d.window = make([]byte, maxStoreBlockSize)
  763. d.fill = (*compressor).fillBlock
  764. d.step = (*compressor).storeFast
  765. case 7 <= level && level <= 9:
  766. d.w.logNewTablePenalty = 8
  767. d.state = &advancedState{}
  768. d.compressionLevel = levels[level]
  769. d.initDeflate()
  770. d.fill = (*compressor).fillDeflate
  771. d.step = (*compressor).deflateLazy
  772. case -level >= MinCustomWindowSize && -level <= MaxCustomWindowSize:
  773. d.w.logNewTablePenalty = 7
  774. d.fast = &fastEncL5Window{maxOffset: int32(-level), cur: maxStoreBlockSize}
  775. d.window = make([]byte, maxStoreBlockSize)
  776. d.fill = (*compressor).fillBlock
  777. d.step = (*compressor).storeFast
  778. default:
  779. return fmt.Errorf("flate: invalid compression level %d: want value in range [-2, 9]", level)
  780. }
  781. d.level = level
  782. return nil
  783. }
  784. // reset the state of the compressor.
  785. func (d *compressor) reset(w io.Writer) {
  786. d.w.reset(w)
  787. d.sync = false
  788. d.err = nil
  789. // We only need to reset a few things for Snappy.
  790. if d.fast != nil {
  791. d.fast.Reset()
  792. d.windowEnd = 0
  793. d.tokens.Reset()
  794. return
  795. }
  796. switch d.compressionLevel.chain {
  797. case 0:
  798. // level was NoCompression or ConstantCompresssion.
  799. d.windowEnd = 0
  800. default:
  801. s := d.state
  802. s.chainHead = -1
  803. for i := range s.hashHead {
  804. s.hashHead[i] = 0
  805. }
  806. for i := range s.hashPrev {
  807. s.hashPrev[i] = 0
  808. }
  809. s.hashOffset = 1
  810. s.index, d.windowEnd = 0, 0
  811. d.blockStart, d.byteAvailable = 0, false
  812. d.tokens.Reset()
  813. s.length = minMatchLength - 1
  814. s.offset = 0
  815. s.ii = 0
  816. s.maxInsertIndex = 0
  817. }
  818. }
  819. func (d *compressor) close() error {
  820. if d.err != nil {
  821. return d.err
  822. }
  823. d.sync = true
  824. d.step(d)
  825. if d.err != nil {
  826. return d.err
  827. }
  828. if d.w.writeStoredHeader(0, true); d.w.err != nil {
  829. return d.w.err
  830. }
  831. d.w.flush()
  832. d.w.reset(nil)
  833. return d.w.err
  834. }
  835. // NewWriter returns a new Writer compressing data at the given level.
  836. // Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression);
  837. // higher levels typically run slower but compress more.
  838. // Level 0 (NoCompression) does not attempt any compression; it only adds the
  839. // necessary DEFLATE framing.
  840. // Level -1 (DefaultCompression) uses the default compression level.
  841. // Level -2 (ConstantCompression) will use Huffman compression only, giving
  842. // a very fast compression for all types of input, but sacrificing considerable
  843. // compression efficiency.
  844. //
  845. // If level is in the range [-2, 9] then the error returned will be nil.
  846. // Otherwise the error returned will be non-nil.
  847. func NewWriter(w io.Writer, level int) (*Writer, error) {
  848. var dw Writer
  849. if err := dw.d.init(w, level); err != nil {
  850. return nil, err
  851. }
  852. return &dw, nil
  853. }
  854. // NewWriterDict is like NewWriter but initializes the new
  855. // Writer with a preset dictionary. The returned Writer behaves
  856. // as if the dictionary had been written to it without producing
  857. // any compressed output. The compressed data written to w
  858. // can only be decompressed by a Reader initialized with the
  859. // same dictionary.
  860. func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) {
  861. zw, err := NewWriter(w, level)
  862. if err != nil {
  863. return nil, err
  864. }
  865. zw.d.fillWindow(dict)
  866. zw.dict = append(zw.dict, dict...) // duplicate dictionary for Reset method.
  867. return zw, err
  868. }
  869. // MinCustomWindowSize is the minimum window size that can be sent to NewWriterWindow.
  870. const MinCustomWindowSize = 32
  871. // MaxCustomWindowSize is the maximum custom window that can be sent to NewWriterWindow.
  872. const MaxCustomWindowSize = windowSize
  873. // NewWriterWindow returns a new Writer compressing data with a custom window size.
  874. // windowSize must be from MinCustomWindowSize to MaxCustomWindowSize.
  875. func NewWriterWindow(w io.Writer, windowSize int) (*Writer, error) {
  876. if windowSize < MinCustomWindowSize {
  877. return nil, errors.New("flate: requested window size less than MinWindowSize")
  878. }
  879. if windowSize > MaxCustomWindowSize {
  880. return nil, errors.New("flate: requested window size bigger than MaxCustomWindowSize")
  881. }
  882. var dw Writer
  883. if err := dw.d.init(w, -windowSize); err != nil {
  884. return nil, err
  885. }
  886. return &dw, nil
  887. }
  888. // A Writer takes data written to it and writes the compressed
  889. // form of that data to an underlying writer (see NewWriter).
  890. type Writer struct {
  891. d compressor
  892. dict []byte
  893. }
  894. // Write writes data to w, which will eventually write the
  895. // compressed form of data to its underlying writer.
  896. func (w *Writer) Write(data []byte) (n int, err error) {
  897. return w.d.write(data)
  898. }
  899. // Flush flushes any pending data to the underlying writer.
  900. // It is useful mainly in compressed network protocols, to ensure that
  901. // a remote reader has enough data to reconstruct a packet.
  902. // Flush does not return until the data has been written.
  903. // Calling Flush when there is no pending data still causes the Writer
  904. // to emit a sync marker of at least 4 bytes.
  905. // If the underlying writer returns an error, Flush returns that error.
  906. //
  907. // In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
  908. func (w *Writer) Flush() error {
  909. // For more about flushing:
  910. // http://www.bolet.org/~pornin/deflate-flush.html
  911. return w.d.syncFlush()
  912. }
  913. // Close flushes and closes the writer.
  914. func (w *Writer) Close() error {
  915. return w.d.close()
  916. }
  917. // Reset discards the writer's state and makes it equivalent to
  918. // the result of NewWriter or NewWriterDict called with dst
  919. // and w's level and dictionary.
  920. func (w *Writer) Reset(dst io.Writer) {
  921. if len(w.dict) > 0 {
  922. // w was created with NewWriterDict
  923. w.d.reset(dst)
  924. if dst != nil {
  925. w.d.fillWindow(w.dict)
  926. }
  927. } else {
  928. // w was created with NewWriter
  929. w.d.reset(dst)
  930. }
  931. }
  932. // ResetDict discards the writer's state and makes it equivalent to
  933. // the result of NewWriter or NewWriterDict called with dst
  934. // and w's level, but sets a specific dictionary.
  935. func (w *Writer) ResetDict(dst io.Writer, dict []byte) {
  936. w.dict = dict
  937. w.d.reset(dst)
  938. w.d.fillWindow(w.dict)
  939. }