deflate.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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. "fmt"
  8. "io"
  9. "math"
  10. )
  11. const (
  12. NoCompression = 0
  13. BestSpeed = 1
  14. BestCompression = 9
  15. DefaultCompression = -1
  16. // HuffmanOnly disables Lempel-Ziv match searching and only performs Huffman
  17. // entropy encoding. This mode is useful in compressing data that has
  18. // already been compressed with an LZ style algorithm (e.g. Snappy or LZ4)
  19. // that lacks an entropy encoder. Compression gains are achieved when
  20. // certain bytes in the input stream occur more frequently than others.
  21. //
  22. // Note that HuffmanOnly produces a compressed output that is
  23. // RFC 1951 compliant. That is, any valid DEFLATE decompressor will
  24. // continue to be able to decompress this output.
  25. HuffmanOnly = -2
  26. ConstantCompression = HuffmanOnly // compatibility alias.
  27. logWindowSize = 15
  28. windowSize = 1 << logWindowSize
  29. windowMask = windowSize - 1
  30. logMaxOffsetSize = 15 // Standard DEFLATE
  31. minMatchLength = 4 // The smallest match that the compressor looks for
  32. maxMatchLength = 258 // The longest match for the compressor
  33. minOffsetSize = 1 // The shortest offset that makes any sense
  34. // The maximum number of tokens we put into a single flat block, just too
  35. // stop things from getting too large.
  36. maxFlateBlockTokens = 1 << 14
  37. maxStoreBlockSize = 65535
  38. hashBits = 17 // After 17 performance degrades
  39. hashSize = 1 << hashBits
  40. hashMask = (1 << hashBits) - 1
  41. hashShift = (hashBits + minMatchLength - 1) / minMatchLength
  42. maxHashOffset = 1 << 24
  43. skipNever = math.MaxInt32
  44. )
  45. var useSSE42 bool
  46. type compressionLevel struct {
  47. good, lazy, nice, chain, fastSkipHashing, level int
  48. }
  49. // Compression levels have been rebalanced from zlib deflate defaults
  50. // to give a bigger spread in speed and compression.
  51. // See https://blog.klauspost.com/rebalancing-deflate-compression-levels/
  52. var levels = []compressionLevel{
  53. {}, // 0
  54. // Level 1-4 uses specialized algorithm - values not used
  55. {0, 0, 0, 0, 0, 1},
  56. {0, 0, 0, 0, 0, 2},
  57. {0, 0, 0, 0, 0, 3},
  58. {0, 0, 0, 0, 0, 4},
  59. // For levels 5-6 we don't bother trying with lazy matches.
  60. // Lazy matching is at least 30% slower, with 1.5% increase.
  61. {6, 0, 12, 8, 12, 5},
  62. {8, 0, 24, 16, 16, 6},
  63. // Levels 7-9 use increasingly more lazy matching
  64. // and increasingly stringent conditions for "good enough".
  65. {8, 8, 24, 16, skipNever, 7},
  66. {10, 16, 24, 64, skipNever, 8},
  67. {32, 258, 258, 4096, skipNever, 9},
  68. }
  69. type compressor struct {
  70. compressionLevel
  71. w *huffmanBitWriter
  72. bulkHasher func([]byte, []uint32)
  73. // compression algorithm
  74. fill func(*compressor, []byte) int // copy data to window
  75. step func(*compressor) // process window
  76. sync bool // requesting flush
  77. // Input hash chains
  78. // hashHead[hashValue] contains the largest inputIndex with the specified hash value
  79. // If hashHead[hashValue] is within the current window, then
  80. // hashPrev[hashHead[hashValue] & windowMask] contains the previous index
  81. // with the same hash value.
  82. chainHead int
  83. hashHead [hashSize]uint32
  84. hashPrev [windowSize]uint32
  85. hashOffset int
  86. // input window: unprocessed data is window[index:windowEnd]
  87. index int
  88. window []byte
  89. windowEnd int
  90. blockStart int // window index where current tokens start
  91. byteAvailable bool // if true, still need to process window[index-1].
  92. // queued output tokens
  93. tokens tokens
  94. // deflate state
  95. length int
  96. offset int
  97. hash uint32
  98. maxInsertIndex int
  99. err error
  100. ii uint16 // position of last match, intended to overflow to reset.
  101. snap snappyEnc
  102. hashMatch [maxMatchLength + minMatchLength]uint32
  103. }
  104. func (d *compressor) fillDeflate(b []byte) int {
  105. if d.index >= 2*windowSize-(minMatchLength+maxMatchLength) {
  106. // shift the window by windowSize
  107. copy(d.window[:], d.window[windowSize:2*windowSize])
  108. d.index -= windowSize
  109. d.windowEnd -= windowSize
  110. if d.blockStart >= windowSize {
  111. d.blockStart -= windowSize
  112. } else {
  113. d.blockStart = math.MaxInt32
  114. }
  115. d.hashOffset += windowSize
  116. if d.hashOffset > maxHashOffset {
  117. delta := d.hashOffset - 1
  118. d.hashOffset -= delta
  119. d.chainHead -= delta
  120. // Iterate over slices instead of arrays to avoid copying
  121. // the entire table onto the stack (Issue #18625).
  122. for i, v := range d.hashPrev[:] {
  123. if int(v) > delta {
  124. d.hashPrev[i] = uint32(int(v) - delta)
  125. } else {
  126. d.hashPrev[i] = 0
  127. }
  128. }
  129. for i, v := range d.hashHead[:] {
  130. if int(v) > delta {
  131. d.hashHead[i] = uint32(int(v) - delta)
  132. } else {
  133. d.hashHead[i] = 0
  134. }
  135. }
  136. }
  137. }
  138. n := copy(d.window[d.windowEnd:], b)
  139. d.windowEnd += n
  140. return n
  141. }
  142. func (d *compressor) writeBlock(tok tokens, index int, eof bool) error {
  143. if index > 0 || eof {
  144. var window []byte
  145. if d.blockStart <= index {
  146. window = d.window[d.blockStart:index]
  147. }
  148. d.blockStart = index
  149. d.w.writeBlock(tok.tokens[:tok.n], eof, window)
  150. return d.w.err
  151. }
  152. return nil
  153. }
  154. // writeBlockSkip writes the current block and uses the number of tokens
  155. // to determine if the block should be stored on no matches, or
  156. // only huffman encoded.
  157. func (d *compressor) writeBlockSkip(tok tokens, index int, eof bool) error {
  158. if index > 0 || eof {
  159. if d.blockStart <= index {
  160. window := d.window[d.blockStart:index]
  161. // If we removed less than a 64th of all literals
  162. // we huffman compress the block.
  163. if int(tok.n) > len(window)-int(tok.n>>6) {
  164. d.w.writeBlockHuff(eof, window)
  165. } else {
  166. // Write a dynamic huffman block.
  167. d.w.writeBlockDynamic(tok.tokens[:tok.n], eof, window)
  168. }
  169. } else {
  170. d.w.writeBlock(tok.tokens[:tok.n], eof, nil)
  171. }
  172. d.blockStart = index
  173. return d.w.err
  174. }
  175. return nil
  176. }
  177. // fillWindow will fill the current window with the supplied
  178. // dictionary and calculate all hashes.
  179. // This is much faster than doing a full encode.
  180. // Should only be used after a start/reset.
  181. func (d *compressor) fillWindow(b []byte) {
  182. // Do not fill window if we are in store-only mode,
  183. // use constant or Snappy compression.
  184. switch d.compressionLevel.level {
  185. case 0, 1, 2:
  186. return
  187. }
  188. // If we are given too much, cut it.
  189. if len(b) > windowSize {
  190. b = b[len(b)-windowSize:]
  191. }
  192. // Add all to window.
  193. n := copy(d.window[d.windowEnd:], b)
  194. // Calculate 256 hashes at the time (more L1 cache hits)
  195. loops := (n + 256 - minMatchLength) / 256
  196. for j := 0; j < loops; j++ {
  197. startindex := j * 256
  198. end := startindex + 256 + minMatchLength - 1
  199. if end > n {
  200. end = n
  201. }
  202. tocheck := d.window[startindex:end]
  203. dstSize := len(tocheck) - minMatchLength + 1
  204. if dstSize <= 0 {
  205. continue
  206. }
  207. dst := d.hashMatch[:dstSize]
  208. d.bulkHasher(tocheck, dst)
  209. var newH uint32
  210. for i, val := range dst {
  211. di := i + startindex
  212. newH = val & hashMask
  213. // Get previous value with the same hash.
  214. // Our chain should point to the previous value.
  215. d.hashPrev[di&windowMask] = d.hashHead[newH]
  216. // Set the head of the hash chain to us.
  217. d.hashHead[newH] = uint32(di + d.hashOffset)
  218. }
  219. d.hash = newH
  220. }
  221. // Update window information.
  222. d.windowEnd += n
  223. d.index = n
  224. }
  225. // Try to find a match starting at index whose length is greater than prevSize.
  226. // We only look at chainCount possibilities before giving up.
  227. // pos = d.index, prevHead = d.chainHead-d.hashOffset, prevLength=minMatchLength-1, lookahead
  228. func (d *compressor) findMatch(pos int, prevHead int, prevLength int, lookahead int) (length, offset int, ok bool) {
  229. minMatchLook := maxMatchLength
  230. if lookahead < minMatchLook {
  231. minMatchLook = lookahead
  232. }
  233. win := d.window[0 : pos+minMatchLook]
  234. // We quit when we get a match that's at least nice long
  235. nice := len(win) - pos
  236. if d.nice < nice {
  237. nice = d.nice
  238. }
  239. // If we've got a match that's good enough, only look in 1/4 the chain.
  240. tries := d.chain
  241. length = prevLength
  242. if length >= d.good {
  243. tries >>= 2
  244. }
  245. wEnd := win[pos+length]
  246. wPos := win[pos:]
  247. minIndex := pos - windowSize
  248. for i := prevHead; tries > 0; tries-- {
  249. if wEnd == win[i+length] {
  250. n := matchLen(win[i:], wPos, minMatchLook)
  251. if n > length && (n > minMatchLength || pos-i <= 4096) {
  252. length = n
  253. offset = pos - i
  254. ok = true
  255. if n >= nice {
  256. // The match is good enough that we don't try to find a better one.
  257. break
  258. }
  259. wEnd = win[pos+n]
  260. }
  261. }
  262. if i == minIndex {
  263. // hashPrev[i & windowMask] has already been overwritten, so stop now.
  264. break
  265. }
  266. i = int(d.hashPrev[i&windowMask]) - d.hashOffset
  267. if i < minIndex || i < 0 {
  268. break
  269. }
  270. }
  271. return
  272. }
  273. // Try to find a match starting at index whose length is greater than prevSize.
  274. // We only look at chainCount possibilities before giving up.
  275. // pos = d.index, prevHead = d.chainHead-d.hashOffset, prevLength=minMatchLength-1, lookahead
  276. func (d *compressor) findMatchSSE(pos int, prevHead int, prevLength int, lookahead int) (length, offset int, ok bool) {
  277. minMatchLook := maxMatchLength
  278. if lookahead < minMatchLook {
  279. minMatchLook = lookahead
  280. }
  281. win := d.window[0 : pos+minMatchLook]
  282. // We quit when we get a match that's at least nice long
  283. nice := len(win) - pos
  284. if d.nice < nice {
  285. nice = d.nice
  286. }
  287. // If we've got a match that's good enough, only look in 1/4 the chain.
  288. tries := d.chain
  289. length = prevLength
  290. if length >= d.good {
  291. tries >>= 2
  292. }
  293. wEnd := win[pos+length]
  294. wPos := win[pos:]
  295. minIndex := pos - windowSize
  296. for i := prevHead; tries > 0; tries-- {
  297. if wEnd == win[i+length] {
  298. n := matchLenSSE4(win[i:], wPos, minMatchLook)
  299. if n > length && (n > minMatchLength || pos-i <= 4096) {
  300. length = n
  301. offset = pos - i
  302. ok = true
  303. if n >= nice {
  304. // The match is good enough that we don't try to find a better one.
  305. break
  306. }
  307. wEnd = win[pos+n]
  308. }
  309. }
  310. if i == minIndex {
  311. // hashPrev[i & windowMask] has already been overwritten, so stop now.
  312. break
  313. }
  314. i = int(d.hashPrev[i&windowMask]) - d.hashOffset
  315. if i < minIndex || i < 0 {
  316. break
  317. }
  318. }
  319. return
  320. }
  321. func (d *compressor) writeStoredBlock(buf []byte) error {
  322. if d.w.writeStoredHeader(len(buf), false); d.w.err != nil {
  323. return d.w.err
  324. }
  325. d.w.writeBytes(buf)
  326. return d.w.err
  327. }
  328. const hashmul = 0x1e35a7bd
  329. // hash4 returns a hash representation of the first 4 bytes
  330. // of the supplied slice.
  331. // The caller must ensure that len(b) >= 4.
  332. func hash4(b []byte) uint32 {
  333. return ((uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24) * hashmul) >> (32 - hashBits)
  334. }
  335. // bulkHash4 will compute hashes using the same
  336. // algorithm as hash4
  337. func bulkHash4(b []byte, dst []uint32) {
  338. if len(b) < minMatchLength {
  339. return
  340. }
  341. hb := uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
  342. dst[0] = (hb * hashmul) >> (32 - hashBits)
  343. end := len(b) - minMatchLength + 1
  344. for i := 1; i < end; i++ {
  345. hb = (hb << 8) | uint32(b[i+3])
  346. dst[i] = (hb * hashmul) >> (32 - hashBits)
  347. }
  348. }
  349. // matchLen returns the number of matching bytes in a and b
  350. // up to length 'max'. Both slices must be at least 'max'
  351. // bytes in size.
  352. func matchLen(a, b []byte, max int) int {
  353. a = a[:max]
  354. b = b[:len(a)]
  355. for i, av := range a {
  356. if b[i] != av {
  357. return i
  358. }
  359. }
  360. return max
  361. }
  362. func (d *compressor) initDeflate() {
  363. d.window = make([]byte, 2*windowSize)
  364. d.hashOffset = 1
  365. d.length = minMatchLength - 1
  366. d.offset = 0
  367. d.byteAvailable = false
  368. d.index = 0
  369. d.hash = 0
  370. d.chainHead = -1
  371. d.bulkHasher = bulkHash4
  372. if useSSE42 {
  373. d.bulkHasher = crc32sseAll
  374. }
  375. }
  376. // Assumes that d.fastSkipHashing != skipNever,
  377. // otherwise use deflateLazy
  378. func (d *compressor) deflate() {
  379. // Sanity enables additional runtime tests.
  380. // It's intended to be used during development
  381. // to supplement the currently ad-hoc unit tests.
  382. const sanity = false
  383. if d.windowEnd-d.index < minMatchLength+maxMatchLength && !d.sync {
  384. return
  385. }
  386. d.maxInsertIndex = d.windowEnd - (minMatchLength - 1)
  387. if d.index < d.maxInsertIndex {
  388. d.hash = hash4(d.window[d.index : d.index+minMatchLength])
  389. }
  390. for {
  391. if sanity && d.index > d.windowEnd {
  392. panic("index > windowEnd")
  393. }
  394. lookahead := d.windowEnd - d.index
  395. if lookahead < minMatchLength+maxMatchLength {
  396. if !d.sync {
  397. return
  398. }
  399. if sanity && d.index > d.windowEnd {
  400. panic("index > windowEnd")
  401. }
  402. if lookahead == 0 {
  403. if d.tokens.n > 0 {
  404. if d.err = d.writeBlockSkip(d.tokens, d.index, false); d.err != nil {
  405. return
  406. }
  407. d.tokens.n = 0
  408. }
  409. return
  410. }
  411. }
  412. if d.index < d.maxInsertIndex {
  413. // Update the hash
  414. d.hash = hash4(d.window[d.index : d.index+minMatchLength])
  415. ch := d.hashHead[d.hash&hashMask]
  416. d.chainHead = int(ch)
  417. d.hashPrev[d.index&windowMask] = ch
  418. d.hashHead[d.hash&hashMask] = uint32(d.index + d.hashOffset)
  419. }
  420. d.length = minMatchLength - 1
  421. d.offset = 0
  422. minIndex := d.index - windowSize
  423. if minIndex < 0 {
  424. minIndex = 0
  425. }
  426. if d.chainHead-d.hashOffset >= minIndex && lookahead > minMatchLength-1 {
  427. if newLength, newOffset, ok := d.findMatch(d.index, d.chainHead-d.hashOffset, minMatchLength-1, lookahead); ok {
  428. d.length = newLength
  429. d.offset = newOffset
  430. }
  431. }
  432. if d.length >= minMatchLength {
  433. d.ii = 0
  434. // There was a match at the previous step, and the current match is
  435. // not better. Output the previous match.
  436. // "d.length-3" should NOT be "d.length-minMatchLength", since the format always assume 3
  437. d.tokens.tokens[d.tokens.n] = matchToken(uint32(d.length-3), uint32(d.offset-minOffsetSize))
  438. d.tokens.n++
  439. // Insert in the hash table all strings up to the end of the match.
  440. // index and index-1 are already inserted. If there is not enough
  441. // lookahead, the last two strings are not inserted into the hash
  442. // table.
  443. if d.length <= d.fastSkipHashing {
  444. var newIndex int
  445. newIndex = d.index + d.length
  446. // Calculate missing hashes
  447. end := newIndex
  448. if end > d.maxInsertIndex {
  449. end = d.maxInsertIndex
  450. }
  451. end += minMatchLength - 1
  452. startindex := d.index + 1
  453. if startindex > d.maxInsertIndex {
  454. startindex = d.maxInsertIndex
  455. }
  456. tocheck := d.window[startindex:end]
  457. dstSize := len(tocheck) - minMatchLength + 1
  458. if dstSize > 0 {
  459. dst := d.hashMatch[:dstSize]
  460. bulkHash4(tocheck, dst)
  461. var newH uint32
  462. for i, val := range dst {
  463. di := i + startindex
  464. newH = val & hashMask
  465. // Get previous value with the same hash.
  466. // Our chain should point to the previous value.
  467. d.hashPrev[di&windowMask] = d.hashHead[newH]
  468. // Set the head of the hash chain to us.
  469. d.hashHead[newH] = uint32(di + d.hashOffset)
  470. }
  471. d.hash = newH
  472. }
  473. d.index = newIndex
  474. } else {
  475. // For matches this long, we don't bother inserting each individual
  476. // item into the table.
  477. d.index += d.length
  478. if d.index < d.maxInsertIndex {
  479. d.hash = hash4(d.window[d.index : d.index+minMatchLength])
  480. }
  481. }
  482. if d.tokens.n == maxFlateBlockTokens {
  483. // The block includes the current character
  484. if d.err = d.writeBlockSkip(d.tokens, d.index, false); d.err != nil {
  485. return
  486. }
  487. d.tokens.n = 0
  488. }
  489. } else {
  490. d.ii++
  491. end := d.index + int(d.ii>>uint(d.fastSkipHashing)) + 1
  492. if end > d.windowEnd {
  493. end = d.windowEnd
  494. }
  495. for i := d.index; i < end; i++ {
  496. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[i]))
  497. d.tokens.n++
  498. if d.tokens.n == maxFlateBlockTokens {
  499. if d.err = d.writeBlockSkip(d.tokens, i+1, false); d.err != nil {
  500. return
  501. }
  502. d.tokens.n = 0
  503. }
  504. }
  505. d.index = end
  506. }
  507. }
  508. }
  509. // deflateLazy is the same as deflate, but with d.fastSkipHashing == skipNever,
  510. // meaning it always has lazy matching on.
  511. func (d *compressor) deflateLazy() {
  512. // Sanity enables additional runtime tests.
  513. // It's intended to be used during development
  514. // to supplement the currently ad-hoc unit tests.
  515. const sanity = false
  516. if d.windowEnd-d.index < minMatchLength+maxMatchLength && !d.sync {
  517. return
  518. }
  519. d.maxInsertIndex = d.windowEnd - (minMatchLength - 1)
  520. if d.index < d.maxInsertIndex {
  521. d.hash = hash4(d.window[d.index : d.index+minMatchLength])
  522. }
  523. for {
  524. if sanity && d.index > d.windowEnd {
  525. panic("index > windowEnd")
  526. }
  527. lookahead := d.windowEnd - d.index
  528. if lookahead < minMatchLength+maxMatchLength {
  529. if !d.sync {
  530. return
  531. }
  532. if sanity && d.index > d.windowEnd {
  533. panic("index > windowEnd")
  534. }
  535. if lookahead == 0 {
  536. // Flush current output block if any.
  537. if d.byteAvailable {
  538. // There is still one pending token that needs to be flushed
  539. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[d.index-1]))
  540. d.tokens.n++
  541. d.byteAvailable = false
  542. }
  543. if d.tokens.n > 0 {
  544. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  545. return
  546. }
  547. d.tokens.n = 0
  548. }
  549. return
  550. }
  551. }
  552. if d.index < d.maxInsertIndex {
  553. // Update the hash
  554. d.hash = hash4(d.window[d.index : d.index+minMatchLength])
  555. ch := d.hashHead[d.hash&hashMask]
  556. d.chainHead = int(ch)
  557. d.hashPrev[d.index&windowMask] = ch
  558. d.hashHead[d.hash&hashMask] = uint32(d.index + d.hashOffset)
  559. }
  560. prevLength := d.length
  561. prevOffset := d.offset
  562. d.length = minMatchLength - 1
  563. d.offset = 0
  564. minIndex := d.index - windowSize
  565. if minIndex < 0 {
  566. minIndex = 0
  567. }
  568. if d.chainHead-d.hashOffset >= minIndex && lookahead > prevLength && prevLength < d.lazy {
  569. if newLength, newOffset, ok := d.findMatch(d.index, d.chainHead-d.hashOffset, minMatchLength-1, lookahead); ok {
  570. d.length = newLength
  571. d.offset = newOffset
  572. }
  573. }
  574. if prevLength >= minMatchLength && d.length <= prevLength {
  575. // There was a match at the previous step, and the current match is
  576. // not better. Output the previous match.
  577. d.tokens.tokens[d.tokens.n] = matchToken(uint32(prevLength-3), uint32(prevOffset-minOffsetSize))
  578. d.tokens.n++
  579. // Insert in the hash table all strings up to the end of the match.
  580. // index and index-1 are already inserted. If there is not enough
  581. // lookahead, the last two strings are not inserted into the hash
  582. // table.
  583. var newIndex int
  584. newIndex = d.index + prevLength - 1
  585. // Calculate missing hashes
  586. end := newIndex
  587. if end > d.maxInsertIndex {
  588. end = d.maxInsertIndex
  589. }
  590. end += minMatchLength - 1
  591. startindex := d.index + 1
  592. if startindex > d.maxInsertIndex {
  593. startindex = d.maxInsertIndex
  594. }
  595. tocheck := d.window[startindex:end]
  596. dstSize := len(tocheck) - minMatchLength + 1
  597. if dstSize > 0 {
  598. dst := d.hashMatch[:dstSize]
  599. bulkHash4(tocheck, dst)
  600. var newH uint32
  601. for i, val := range dst {
  602. di := i + startindex
  603. newH = val & hashMask
  604. // Get previous value with the same hash.
  605. // Our chain should point to the previous value.
  606. d.hashPrev[di&windowMask] = d.hashHead[newH]
  607. // Set the head of the hash chain to us.
  608. d.hashHead[newH] = uint32(di + d.hashOffset)
  609. }
  610. d.hash = newH
  611. }
  612. d.index = newIndex
  613. d.byteAvailable = false
  614. d.length = minMatchLength - 1
  615. if d.tokens.n == maxFlateBlockTokens {
  616. // The block includes the current character
  617. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  618. return
  619. }
  620. d.tokens.n = 0
  621. }
  622. } else {
  623. // Reset, if we got a match this run.
  624. if d.length >= minMatchLength {
  625. d.ii = 0
  626. }
  627. // We have a byte waiting. Emit it.
  628. if d.byteAvailable {
  629. d.ii++
  630. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[d.index-1]))
  631. d.tokens.n++
  632. if d.tokens.n == maxFlateBlockTokens {
  633. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  634. return
  635. }
  636. d.tokens.n = 0
  637. }
  638. d.index++
  639. // If we have a long run of no matches, skip additional bytes
  640. // Resets when d.ii overflows after 64KB.
  641. if d.ii > 31 {
  642. n := int(d.ii >> 5)
  643. for j := 0; j < n; j++ {
  644. if d.index >= d.windowEnd-1 {
  645. break
  646. }
  647. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[d.index-1]))
  648. d.tokens.n++
  649. if d.tokens.n == maxFlateBlockTokens {
  650. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  651. return
  652. }
  653. d.tokens.n = 0
  654. }
  655. d.index++
  656. }
  657. // Flush last byte
  658. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[d.index-1]))
  659. d.tokens.n++
  660. d.byteAvailable = false
  661. // d.length = minMatchLength - 1 // not needed, since d.ii is reset above, so it should never be > minMatchLength
  662. if d.tokens.n == maxFlateBlockTokens {
  663. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  664. return
  665. }
  666. d.tokens.n = 0
  667. }
  668. }
  669. } else {
  670. d.index++
  671. d.byteAvailable = true
  672. }
  673. }
  674. }
  675. }
  676. // Assumes that d.fastSkipHashing != skipNever,
  677. // otherwise use deflateLazySSE
  678. func (d *compressor) deflateSSE() {
  679. // Sanity enables additional runtime tests.
  680. // It's intended to be used during development
  681. // to supplement the currently ad-hoc unit tests.
  682. const sanity = false
  683. if d.windowEnd-d.index < minMatchLength+maxMatchLength && !d.sync {
  684. return
  685. }
  686. d.maxInsertIndex = d.windowEnd - (minMatchLength - 1)
  687. if d.index < d.maxInsertIndex {
  688. d.hash = crc32sse(d.window[d.index:d.index+minMatchLength]) & hashMask
  689. }
  690. for {
  691. if sanity && d.index > d.windowEnd {
  692. panic("index > windowEnd")
  693. }
  694. lookahead := d.windowEnd - d.index
  695. if lookahead < minMatchLength+maxMatchLength {
  696. if !d.sync {
  697. return
  698. }
  699. if sanity && d.index > d.windowEnd {
  700. panic("index > windowEnd")
  701. }
  702. if lookahead == 0 {
  703. if d.tokens.n > 0 {
  704. if d.err = d.writeBlockSkip(d.tokens, d.index, false); d.err != nil {
  705. return
  706. }
  707. d.tokens.n = 0
  708. }
  709. return
  710. }
  711. }
  712. if d.index < d.maxInsertIndex {
  713. // Update the hash
  714. d.hash = crc32sse(d.window[d.index:d.index+minMatchLength]) & hashMask
  715. ch := d.hashHead[d.hash]
  716. d.chainHead = int(ch)
  717. d.hashPrev[d.index&windowMask] = ch
  718. d.hashHead[d.hash] = uint32(d.index + d.hashOffset)
  719. }
  720. d.length = minMatchLength - 1
  721. d.offset = 0
  722. minIndex := d.index - windowSize
  723. if minIndex < 0 {
  724. minIndex = 0
  725. }
  726. if d.chainHead-d.hashOffset >= minIndex && lookahead > minMatchLength-1 {
  727. if newLength, newOffset, ok := d.findMatchSSE(d.index, d.chainHead-d.hashOffset, minMatchLength-1, lookahead); ok {
  728. d.length = newLength
  729. d.offset = newOffset
  730. }
  731. }
  732. if d.length >= minMatchLength {
  733. d.ii = 0
  734. // There was a match at the previous step, and the current match is
  735. // not better. Output the previous match.
  736. // "d.length-3" should NOT be "d.length-minMatchLength", since the format always assume 3
  737. d.tokens.tokens[d.tokens.n] = matchToken(uint32(d.length-3), uint32(d.offset-minOffsetSize))
  738. d.tokens.n++
  739. // Insert in the hash table all strings up to the end of the match.
  740. // index and index-1 are already inserted. If there is not enough
  741. // lookahead, the last two strings are not inserted into the hash
  742. // table.
  743. if d.length <= d.fastSkipHashing {
  744. var newIndex int
  745. newIndex = d.index + d.length
  746. // Calculate missing hashes
  747. end := newIndex
  748. if end > d.maxInsertIndex {
  749. end = d.maxInsertIndex
  750. }
  751. end += minMatchLength - 1
  752. startindex := d.index + 1
  753. if startindex > d.maxInsertIndex {
  754. startindex = d.maxInsertIndex
  755. }
  756. tocheck := d.window[startindex:end]
  757. dstSize := len(tocheck) - minMatchLength + 1
  758. if dstSize > 0 {
  759. dst := d.hashMatch[:dstSize]
  760. crc32sseAll(tocheck, dst)
  761. var newH uint32
  762. for i, val := range dst {
  763. di := i + startindex
  764. newH = val & hashMask
  765. // Get previous value with the same hash.
  766. // Our chain should point to the previous value.
  767. d.hashPrev[di&windowMask] = d.hashHead[newH]
  768. // Set the head of the hash chain to us.
  769. d.hashHead[newH] = uint32(di + d.hashOffset)
  770. }
  771. d.hash = newH
  772. }
  773. d.index = newIndex
  774. } else {
  775. // For matches this long, we don't bother inserting each individual
  776. // item into the table.
  777. d.index += d.length
  778. if d.index < d.maxInsertIndex {
  779. d.hash = crc32sse(d.window[d.index:d.index+minMatchLength]) & hashMask
  780. }
  781. }
  782. if d.tokens.n == maxFlateBlockTokens {
  783. // The block includes the current character
  784. if d.err = d.writeBlockSkip(d.tokens, d.index, false); d.err != nil {
  785. return
  786. }
  787. d.tokens.n = 0
  788. }
  789. } else {
  790. d.ii++
  791. end := d.index + int(d.ii>>5) + 1
  792. if end > d.windowEnd {
  793. end = d.windowEnd
  794. }
  795. for i := d.index; i < end; i++ {
  796. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[i]))
  797. d.tokens.n++
  798. if d.tokens.n == maxFlateBlockTokens {
  799. if d.err = d.writeBlockSkip(d.tokens, i+1, false); d.err != nil {
  800. return
  801. }
  802. d.tokens.n = 0
  803. }
  804. }
  805. d.index = end
  806. }
  807. }
  808. }
  809. // deflateLazy is the same as deflate, but with d.fastSkipHashing == skipNever,
  810. // meaning it always has lazy matching on.
  811. func (d *compressor) deflateLazySSE() {
  812. // Sanity enables additional runtime tests.
  813. // It's intended to be used during development
  814. // to supplement the currently ad-hoc unit tests.
  815. const sanity = false
  816. if d.windowEnd-d.index < minMatchLength+maxMatchLength && !d.sync {
  817. return
  818. }
  819. d.maxInsertIndex = d.windowEnd - (minMatchLength - 1)
  820. if d.index < d.maxInsertIndex {
  821. d.hash = crc32sse(d.window[d.index:d.index+minMatchLength]) & hashMask
  822. }
  823. for {
  824. if sanity && d.index > d.windowEnd {
  825. panic("index > windowEnd")
  826. }
  827. lookahead := d.windowEnd - d.index
  828. if lookahead < minMatchLength+maxMatchLength {
  829. if !d.sync {
  830. return
  831. }
  832. if sanity && d.index > d.windowEnd {
  833. panic("index > windowEnd")
  834. }
  835. if lookahead == 0 {
  836. // Flush current output block if any.
  837. if d.byteAvailable {
  838. // There is still one pending token that needs to be flushed
  839. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[d.index-1]))
  840. d.tokens.n++
  841. d.byteAvailable = false
  842. }
  843. if d.tokens.n > 0 {
  844. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  845. return
  846. }
  847. d.tokens.n = 0
  848. }
  849. return
  850. }
  851. }
  852. if d.index < d.maxInsertIndex {
  853. // Update the hash
  854. d.hash = crc32sse(d.window[d.index:d.index+minMatchLength]) & hashMask
  855. ch := d.hashHead[d.hash]
  856. d.chainHead = int(ch)
  857. d.hashPrev[d.index&windowMask] = ch
  858. d.hashHead[d.hash] = uint32(d.index + d.hashOffset)
  859. }
  860. prevLength := d.length
  861. prevOffset := d.offset
  862. d.length = minMatchLength - 1
  863. d.offset = 0
  864. minIndex := d.index - windowSize
  865. if minIndex < 0 {
  866. minIndex = 0
  867. }
  868. if d.chainHead-d.hashOffset >= minIndex && lookahead > prevLength && prevLength < d.lazy {
  869. if newLength, newOffset, ok := d.findMatchSSE(d.index, d.chainHead-d.hashOffset, minMatchLength-1, lookahead); ok {
  870. d.length = newLength
  871. d.offset = newOffset
  872. }
  873. }
  874. if prevLength >= minMatchLength && d.length <= prevLength {
  875. // There was a match at the previous step, and the current match is
  876. // not better. Output the previous match.
  877. d.tokens.tokens[d.tokens.n] = matchToken(uint32(prevLength-3), uint32(prevOffset-minOffsetSize))
  878. d.tokens.n++
  879. // Insert in the hash table all strings up to the end of the match.
  880. // index and index-1 are already inserted. If there is not enough
  881. // lookahead, the last two strings are not inserted into the hash
  882. // table.
  883. var newIndex int
  884. newIndex = d.index + prevLength - 1
  885. // Calculate missing hashes
  886. end := newIndex
  887. if end > d.maxInsertIndex {
  888. end = d.maxInsertIndex
  889. }
  890. end += minMatchLength - 1
  891. startindex := d.index + 1
  892. if startindex > d.maxInsertIndex {
  893. startindex = d.maxInsertIndex
  894. }
  895. tocheck := d.window[startindex:end]
  896. dstSize := len(tocheck) - minMatchLength + 1
  897. if dstSize > 0 {
  898. dst := d.hashMatch[:dstSize]
  899. crc32sseAll(tocheck, dst)
  900. var newH uint32
  901. for i, val := range dst {
  902. di := i + startindex
  903. newH = val & hashMask
  904. // Get previous value with the same hash.
  905. // Our chain should point to the previous value.
  906. d.hashPrev[di&windowMask] = d.hashHead[newH]
  907. // Set the head of the hash chain to us.
  908. d.hashHead[newH] = uint32(di + d.hashOffset)
  909. }
  910. d.hash = newH
  911. }
  912. d.index = newIndex
  913. d.byteAvailable = false
  914. d.length = minMatchLength - 1
  915. if d.tokens.n == maxFlateBlockTokens {
  916. // The block includes the current character
  917. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  918. return
  919. }
  920. d.tokens.n = 0
  921. }
  922. } else {
  923. // Reset, if we got a match this run.
  924. if d.length >= minMatchLength {
  925. d.ii = 0
  926. }
  927. // We have a byte waiting. Emit it.
  928. if d.byteAvailable {
  929. d.ii++
  930. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[d.index-1]))
  931. d.tokens.n++
  932. if d.tokens.n == maxFlateBlockTokens {
  933. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  934. return
  935. }
  936. d.tokens.n = 0
  937. }
  938. d.index++
  939. // If we have a long run of no matches, skip additional bytes
  940. // Resets when d.ii overflows after 64KB.
  941. if d.ii > 31 {
  942. n := int(d.ii >> 6)
  943. for j := 0; j < n; j++ {
  944. if d.index >= d.windowEnd-1 {
  945. break
  946. }
  947. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[d.index-1]))
  948. d.tokens.n++
  949. if d.tokens.n == maxFlateBlockTokens {
  950. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  951. return
  952. }
  953. d.tokens.n = 0
  954. }
  955. d.index++
  956. }
  957. // Flush last byte
  958. d.tokens.tokens[d.tokens.n] = literalToken(uint32(d.window[d.index-1]))
  959. d.tokens.n++
  960. d.byteAvailable = false
  961. // d.length = minMatchLength - 1 // not needed, since d.ii is reset above, so it should never be > minMatchLength
  962. if d.tokens.n == maxFlateBlockTokens {
  963. if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil {
  964. return
  965. }
  966. d.tokens.n = 0
  967. }
  968. }
  969. } else {
  970. d.index++
  971. d.byteAvailable = true
  972. }
  973. }
  974. }
  975. }
  976. func (d *compressor) store() {
  977. if d.windowEnd > 0 && (d.windowEnd == maxStoreBlockSize || d.sync) {
  978. d.err = d.writeStoredBlock(d.window[:d.windowEnd])
  979. d.windowEnd = 0
  980. }
  981. }
  982. // fillWindow will fill the buffer with data for huffman-only compression.
  983. // The number of bytes copied is returned.
  984. func (d *compressor) fillBlock(b []byte) int {
  985. n := copy(d.window[d.windowEnd:], b)
  986. d.windowEnd += n
  987. return n
  988. }
  989. // storeHuff will compress and store the currently added data,
  990. // if enough has been accumulated or we at the end of the stream.
  991. // Any error that occurred will be in d.err
  992. func (d *compressor) storeHuff() {
  993. if d.windowEnd < len(d.window) && !d.sync || d.windowEnd == 0 {
  994. return
  995. }
  996. d.w.writeBlockHuff(false, d.window[:d.windowEnd])
  997. d.err = d.w.err
  998. d.windowEnd = 0
  999. }
  1000. // storeHuff will compress and store the currently added data,
  1001. // if enough has been accumulated or we at the end of the stream.
  1002. // Any error that occurred will be in d.err
  1003. func (d *compressor) storeSnappy() {
  1004. // We only compress if we have maxStoreBlockSize.
  1005. if d.windowEnd < maxStoreBlockSize {
  1006. if !d.sync {
  1007. return
  1008. }
  1009. // Handle extremely small sizes.
  1010. if d.windowEnd < 128 {
  1011. if d.windowEnd == 0 {
  1012. return
  1013. }
  1014. if d.windowEnd <= 32 {
  1015. d.err = d.writeStoredBlock(d.window[:d.windowEnd])
  1016. d.tokens.n = 0
  1017. d.windowEnd = 0
  1018. } else {
  1019. d.w.writeBlockHuff(false, d.window[:d.windowEnd])
  1020. d.err = d.w.err
  1021. }
  1022. d.tokens.n = 0
  1023. d.windowEnd = 0
  1024. d.snap.Reset()
  1025. return
  1026. }
  1027. }
  1028. d.snap.Encode(&d.tokens, d.window[:d.windowEnd])
  1029. // If we made zero matches, store the block as is.
  1030. if int(d.tokens.n) == d.windowEnd {
  1031. d.err = d.writeStoredBlock(d.window[:d.windowEnd])
  1032. // If we removed less than 1/16th, huffman compress the block.
  1033. } else if int(d.tokens.n) > d.windowEnd-(d.windowEnd>>4) {
  1034. d.w.writeBlockHuff(false, d.window[:d.windowEnd])
  1035. d.err = d.w.err
  1036. } else {
  1037. d.w.writeBlockDynamic(d.tokens.tokens[:d.tokens.n], false, d.window[:d.windowEnd])
  1038. d.err = d.w.err
  1039. }
  1040. d.tokens.n = 0
  1041. d.windowEnd = 0
  1042. }
  1043. // write will add input byte to the stream.
  1044. // Unless an error occurs all bytes will be consumed.
  1045. func (d *compressor) write(b []byte) (n int, err error) {
  1046. if d.err != nil {
  1047. return 0, d.err
  1048. }
  1049. n = len(b)
  1050. for len(b) > 0 {
  1051. d.step(d)
  1052. b = b[d.fill(d, b):]
  1053. if d.err != nil {
  1054. return 0, d.err
  1055. }
  1056. }
  1057. return n, d.err
  1058. }
  1059. func (d *compressor) syncFlush() error {
  1060. d.sync = true
  1061. if d.err != nil {
  1062. return d.err
  1063. }
  1064. d.step(d)
  1065. if d.err == nil {
  1066. d.w.writeStoredHeader(0, false)
  1067. d.w.flush()
  1068. d.err = d.w.err
  1069. }
  1070. d.sync = false
  1071. return d.err
  1072. }
  1073. func (d *compressor) init(w io.Writer, level int) (err error) {
  1074. d.w = newHuffmanBitWriter(w)
  1075. switch {
  1076. case level == NoCompression:
  1077. d.window = make([]byte, maxStoreBlockSize)
  1078. d.fill = (*compressor).fillBlock
  1079. d.step = (*compressor).store
  1080. case level == ConstantCompression:
  1081. d.window = make([]byte, maxStoreBlockSize)
  1082. d.fill = (*compressor).fillBlock
  1083. d.step = (*compressor).storeHuff
  1084. case level >= 1 && level <= 4:
  1085. d.snap = newSnappy(level)
  1086. d.window = make([]byte, maxStoreBlockSize)
  1087. d.fill = (*compressor).fillBlock
  1088. d.step = (*compressor).storeSnappy
  1089. case level == DefaultCompression:
  1090. level = 5
  1091. fallthrough
  1092. case 5 <= level && level <= 9:
  1093. d.compressionLevel = levels[level]
  1094. d.initDeflate()
  1095. d.fill = (*compressor).fillDeflate
  1096. if d.fastSkipHashing == skipNever {
  1097. if useSSE42 {
  1098. d.step = (*compressor).deflateLazySSE
  1099. } else {
  1100. d.step = (*compressor).deflateLazy
  1101. }
  1102. } else {
  1103. if useSSE42 {
  1104. d.step = (*compressor).deflateSSE
  1105. } else {
  1106. d.step = (*compressor).deflate
  1107. }
  1108. }
  1109. default:
  1110. return fmt.Errorf("flate: invalid compression level %d: want value in range [-2, 9]", level)
  1111. }
  1112. return nil
  1113. }
  1114. // reset the state of the compressor.
  1115. func (d *compressor) reset(w io.Writer) {
  1116. d.w.reset(w)
  1117. d.sync = false
  1118. d.err = nil
  1119. // We only need to reset a few things for Snappy.
  1120. if d.snap != nil {
  1121. d.snap.Reset()
  1122. d.windowEnd = 0
  1123. d.tokens.n = 0
  1124. return
  1125. }
  1126. switch d.compressionLevel.chain {
  1127. case 0:
  1128. // level was NoCompression or ConstantCompresssion.
  1129. d.windowEnd = 0
  1130. default:
  1131. d.chainHead = -1
  1132. for i := range d.hashHead {
  1133. d.hashHead[i] = 0
  1134. }
  1135. for i := range d.hashPrev {
  1136. d.hashPrev[i] = 0
  1137. }
  1138. d.hashOffset = 1
  1139. d.index, d.windowEnd = 0, 0
  1140. d.blockStart, d.byteAvailable = 0, false
  1141. d.tokens.n = 0
  1142. d.length = minMatchLength - 1
  1143. d.offset = 0
  1144. d.hash = 0
  1145. d.ii = 0
  1146. d.maxInsertIndex = 0
  1147. }
  1148. }
  1149. func (d *compressor) close() error {
  1150. if d.err != nil {
  1151. return d.err
  1152. }
  1153. d.sync = true
  1154. d.step(d)
  1155. if d.err != nil {
  1156. return d.err
  1157. }
  1158. if d.w.writeStoredHeader(0, true); d.w.err != nil {
  1159. return d.w.err
  1160. }
  1161. d.w.flush()
  1162. return d.w.err
  1163. }
  1164. // NewWriter returns a new Writer compressing data at the given level.
  1165. // Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression);
  1166. // higher levels typically run slower but compress more.
  1167. // Level 0 (NoCompression) does not attempt any compression; it only adds the
  1168. // necessary DEFLATE framing.
  1169. // Level -1 (DefaultCompression) uses the default compression level.
  1170. // Level -2 (ConstantCompression) will use Huffman compression only, giving
  1171. // a very fast compression for all types of input, but sacrificing considerable
  1172. // compression efficiency.
  1173. //
  1174. // If level is in the range [-2, 9] then the error returned will be nil.
  1175. // Otherwise the error returned will be non-nil.
  1176. func NewWriter(w io.Writer, level int) (*Writer, error) {
  1177. var dw Writer
  1178. if err := dw.d.init(w, level); err != nil {
  1179. return nil, err
  1180. }
  1181. return &dw, nil
  1182. }
  1183. // NewWriterDict is like NewWriter but initializes the new
  1184. // Writer with a preset dictionary. The returned Writer behaves
  1185. // as if the dictionary had been written to it without producing
  1186. // any compressed output. The compressed data written to w
  1187. // can only be decompressed by a Reader initialized with the
  1188. // same dictionary.
  1189. func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) {
  1190. dw := &dictWriter{w}
  1191. zw, err := NewWriter(dw, level)
  1192. if err != nil {
  1193. return nil, err
  1194. }
  1195. zw.d.fillWindow(dict)
  1196. zw.dict = append(zw.dict, dict...) // duplicate dictionary for Reset method.
  1197. return zw, err
  1198. }
  1199. type dictWriter struct {
  1200. w io.Writer
  1201. }
  1202. func (w *dictWriter) Write(b []byte) (n int, err error) {
  1203. return w.w.Write(b)
  1204. }
  1205. // A Writer takes data written to it and writes the compressed
  1206. // form of that data to an underlying writer (see NewWriter).
  1207. type Writer struct {
  1208. d compressor
  1209. dict []byte
  1210. }
  1211. // Write writes data to w, which will eventually write the
  1212. // compressed form of data to its underlying writer.
  1213. func (w *Writer) Write(data []byte) (n int, err error) {
  1214. return w.d.write(data)
  1215. }
  1216. // Flush flushes any pending data to the underlying writer.
  1217. // It is useful mainly in compressed network protocols, to ensure that
  1218. // a remote reader has enough data to reconstruct a packet.
  1219. // Flush does not return until the data has been written.
  1220. // Calling Flush when there is no pending data still causes the Writer
  1221. // to emit a sync marker of at least 4 bytes.
  1222. // If the underlying writer returns an error, Flush returns that error.
  1223. //
  1224. // In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
  1225. func (w *Writer) Flush() error {
  1226. // For more about flushing:
  1227. // http://www.bolet.org/~pornin/deflate-flush.html
  1228. return w.d.syncFlush()
  1229. }
  1230. // Close flushes and closes the writer.
  1231. func (w *Writer) Close() error {
  1232. return w.d.close()
  1233. }
  1234. // Reset discards the writer's state and makes it equivalent to
  1235. // the result of NewWriter or NewWriterDict called with dst
  1236. // and w's level and dictionary.
  1237. func (w *Writer) Reset(dst io.Writer) {
  1238. if dw, ok := w.d.w.writer.(*dictWriter); ok {
  1239. // w was created with NewWriterDict
  1240. dw.w = dst
  1241. w.d.reset(dw)
  1242. w.d.fillWindow(w.dict)
  1243. } else {
  1244. // w was created with NewWriter
  1245. w.d.reset(dst)
  1246. }
  1247. }
  1248. // ResetDict discards the writer's state and makes it equivalent to
  1249. // the result of NewWriter or NewWriterDict called with dst
  1250. // and w's level, but sets a specific dictionary.
  1251. func (w *Writer) ResetDict(dst io.Writer, dict []byte) {
  1252. w.dict = dict
  1253. w.d.reset(dst)
  1254. w.d.fillWindow(w.dict)
  1255. }