1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
17 DefaultCompression = -1
19 // HuffmanOnly disables Lempel-Ziv match searching and only performs Huffman
20 // entropy encoding. This mode is useful in compressing data that has
21 // already been compressed with an LZ style algorithm (e.g. Snappy or LZ4)
22 // that lacks an entropy encoder. Compression gains are achieved when
23 // certain bytes in the input stream occur more frequently than others.
25 // Note that HuffmanOnly produces a compressed output that is
26 // RFC 1951 compliant. That is, any valid DEFLATE decompressor will
27 // continue to be able to decompress this output.
33 windowSize = 1 << logWindowSize
34 windowMask = windowSize - 1
36 // The LZ77 step produces a sequence of literal tokens and <length, offset>
37 // pair tokens. The offset is also known as distance. The underlying wire
38 // format limits the range of lengths and offsets. For example, there are
39 // 256 legitimate lengths: those in the range [3, 258]. This package's
40 // compressor uses a higher minimum match length, enabling optimizations
41 // such as finding matches via 32-bit loads and compares.
42 baseMatchLength = 3 // The smallest match length per the RFC section 3.2.5
43 minMatchLength = 4 // The smallest match length that the compressor actually emits
44 maxMatchLength = 258 // The largest match length
45 baseMatchOffset = 1 // The smallest match offset
46 maxMatchOffset = 1 << 15 // The largest match offset
48 // The maximum number of tokens we put into a single flate block, just to
49 // stop things from getting too large.
50 maxFlateBlockTokens = 1 << 14
51 maxStoreBlockSize = 65535
52 hashBits = 17 // After 17 performance degrades
53 hashSize = 1 << hashBits
54 hashMask = (1 << hashBits) - 1
55 maxHashOffset = 1 << 24
57 skipNever = math.MaxInt32
60 type compressionLevel struct {
61 level, good, lazy, nice, chain, fastSkipHashing int
64 var levels = []compressionLevel{
65 {0, 0, 0, 0, 0, 0}, // NoCompression.
66 {1, 0, 0, 0, 0, 0}, // BestSpeed uses a custom algorithm; see deflatefast.go.
67 // For levels 2-3 we don't bother trying with lazy matches.
70 // Levels 4-9 use increasingly more lazy matching
71 // and increasingly stringent conditions for "good enough".
72 {4, 4, 4, 16, 16, skipNever},
73 {5, 8, 16, 32, 32, skipNever},
74 {6, 8, 16, 128, 128, skipNever},
75 {7, 8, 32, 128, 256, skipNever},
76 {8, 32, 128, 258, 1024, skipNever},
77 {9, 32, 258, 258, 4096, skipNever},
80 type compressor struct {
84 bulkHasher func([]byte, []uint32)
86 // compression algorithm
87 fill func(*compressor, []byte) int // copy data to window
88 step func(*compressor) // process window
89 sync bool // requesting flush
90 bestSpeed *deflateFast // Encoder for BestSpeed
93 // hashHead[hashValue] contains the largest inputIndex with the specified hash value
94 // If hashHead[hashValue] is within the current window, then
95 // hashPrev[hashHead[hashValue] & windowMask] contains the previous index
96 // with the same hash value.
98 hashHead [hashSize]uint32
99 hashPrev [windowSize]uint32
102 // input window: unprocessed data is window[index:windowEnd]
106 blockStart int // window index where current tokens start
107 byteAvailable bool // if true, still need to process window[index-1].
109 // queued output tokens
119 // hashMatch must be able to contain hashes for the maximum match length.
120 hashMatch [maxMatchLength - 1]uint32
123 func (d *compressor) fillDeflate(b []byte) int {
124 if d.index >= 2*windowSize-(minMatchLength+maxMatchLength) {
125 // shift the window by windowSize
126 copy(d.window, d.window[windowSize:2*windowSize])
127 d.index -= windowSize
128 d.windowEnd -= windowSize
129 if d.blockStart >= windowSize {
130 d.blockStart -= windowSize
132 d.blockStart = math.MaxInt32
134 d.hashOffset += windowSize
135 if d.hashOffset > maxHashOffset {
136 delta := d.hashOffset - 1
137 d.hashOffset -= delta
139 for i, v := range d.hashPrev {
141 d.hashPrev[i] = uint32(int(v) - delta)
146 for i, v := range d.hashHead {
148 d.hashHead[i] = uint32(int(v) - delta)
155 n := copy(d.window[d.windowEnd:], b)
160 func (d *compressor) writeBlock(tokens []token, index int) error {
163 if d.blockStart <= index {
164 window = d.window[d.blockStart:index]
167 d.w.writeBlock(tokens, false, window)
173 // fillWindow will fill the current window with the supplied
174 // dictionary and calculate all hashes.
175 // This is much faster than doing a full encode.
176 // Should only be used after a reset.
177 func (d *compressor) fillWindow(b []byte) {
178 // Do not fill window if we are in store-only mode.
179 if d.compressionLevel.level < 2 {
182 if d.index != 0 || d.windowEnd != 0 {
183 panic("internal error: fillWindow called with stale data")
186 // If we are given too much, cut it.
187 if len(b) > windowSize {
188 b = b[len(b)-windowSize:]
190 // Add all to window.
191 n := copy(d.window, b)
193 // Calculate 256 hashes at the time (more L1 cache hits)
194 loops := (n + 256 - minMatchLength) / 256
195 for j := 0; j < loops; j++ {
197 end := index + 256 + minMatchLength - 1
201 toCheck := d.window[index:end]
202 dstSize := len(toCheck) - minMatchLength + 1
208 dst := d.hashMatch[:dstSize]
209 d.bulkHasher(toCheck, dst)
211 for i, val := range dst {
214 hh := &d.hashHead[newH&hashMask]
215 // Get previous value with the same hash.
216 // Our chain should point to the previous value.
217 d.hashPrev[di&windowMask] = *hh
218 // Set the head of the hash chain to us.
219 *hh = uint32(di + d.hashOffset)
223 // Update window information.
228 // Try to find a match starting at index whose length is greater than prevSize.
229 // We only look at chainCount possibilities before giving up.
230 func (d *compressor) findMatch(pos int, prevHead int, prevLength int, lookahead int) (length, offset int, ok bool) {
231 minMatchLook := maxMatchLength
232 if lookahead < minMatchLook {
233 minMatchLook = lookahead
236 win := d.window[0 : pos+minMatchLook]
238 // We quit when we get a match that's at least nice long
239 nice := len(win) - pos
244 // If we've got a match that's good enough, only look in 1/4 the chain.
247 if length >= d.good {
251 wEnd := win[pos+length]
253 minIndex := pos - windowSize
255 for i := prevHead; tries > 0; tries-- {
256 if wEnd == win[i+length] {
257 n := matchLen(win[i:], wPos, minMatchLook)
259 if n > length && (n > minMatchLength || pos-i <= 4096) {
264 // The match is good enough that we don't try to find a better one.
271 // hashPrev[i & windowMask] has already been overwritten, so stop now.
274 i = int(d.hashPrev[i&windowMask]) - d.hashOffset
275 if i < minIndex || i < 0 {
282 func (d *compressor) writeStoredBlock(buf []byte) error {
283 if d.w.writeStoredHeader(len(buf), false); d.w.err != nil {
290 const hashmul = 0x1e35a7bd
292 // hash4 returns a hash representation of the first 4 bytes
293 // of the supplied slice.
294 // The caller must ensure that len(b) >= 4.
295 func hash4(b []byte) uint32 {
296 return ((uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24) * hashmul) >> (32 - hashBits)
299 // bulkHash4 will compute hashes using the same
300 // algorithm as hash4
301 func bulkHash4(b []byte, dst []uint32) {
302 if len(b) < minMatchLength {
305 hb := uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
306 dst[0] = (hb * hashmul) >> (32 - hashBits)
307 end := len(b) - minMatchLength + 1
308 for i := 1; i < end; i++ {
309 hb = (hb << 8) | uint32(b[i+3])
310 dst[i] = (hb * hashmul) >> (32 - hashBits)
314 // matchLen returns the number of matching bytes in a and b
315 // up to length 'max'. Both slices must be at least 'max'
317 func matchLen(a, b []byte, max int) int {
320 for i, av := range a {
328 // encSpeed will compress and store the currently added data,
329 // if enough has been accumulated or we at the end of the stream.
330 // Any error that occurred will be in d.err
331 func (d *compressor) encSpeed() {
332 // We only compress if we have maxStoreBlockSize.
333 if d.windowEnd < maxStoreBlockSize {
338 // Handle small sizes.
339 if d.windowEnd < 128 {
341 case d.windowEnd == 0:
343 case d.windowEnd <= 16:
344 d.err = d.writeStoredBlock(d.window[:d.windowEnd])
346 d.w.writeBlockHuff(false, d.window[:d.windowEnd])
356 d.tokens = d.bestSpeed.encode(d.tokens[:0], d.window[:d.windowEnd])
358 // If we removed less than 1/16th, Huffman compress the block.
359 if len(d.tokens) > d.windowEnd-(d.windowEnd>>4) {
360 d.w.writeBlockHuff(false, d.window[:d.windowEnd])
362 d.w.writeBlockDynamic(d.tokens, false, d.window[:d.windowEnd])
368 func (d *compressor) initDeflate() {
369 d.window = make([]byte, 2*windowSize)
371 d.tokens = make([]token, 0, maxFlateBlockTokens+1)
372 d.length = minMatchLength - 1
374 d.byteAvailable = false
378 d.bulkHasher = bulkHash4
381 func (d *compressor) deflate() {
382 if d.windowEnd-d.index < minMatchLength+maxMatchLength && !d.sync {
386 d.maxInsertIndex = d.windowEnd - (minMatchLength - 1)
387 if d.index < d.maxInsertIndex {
388 d.hash = hash4(d.window[d.index : d.index+minMatchLength])
393 if d.index > d.windowEnd {
394 panic("index > windowEnd")
396 lookahead := d.windowEnd - d.index
397 if lookahead < minMatchLength+maxMatchLength {
401 if d.index > d.windowEnd {
402 panic("index > windowEnd")
405 // Flush current output block if any.
407 // There is still one pending token that needs to be flushed
408 d.tokens = append(d.tokens, literalToken(uint32(d.window[d.index-1])))
409 d.byteAvailable = false
411 if len(d.tokens) > 0 {
412 if d.err = d.writeBlock(d.tokens, d.index); d.err != nil {
415 d.tokens = d.tokens[:0]
420 if d.index < d.maxInsertIndex {
422 d.hash = hash4(d.window[d.index : d.index+minMatchLength])
423 hh := &d.hashHead[d.hash&hashMask]
424 d.chainHead = int(*hh)
425 d.hashPrev[d.index&windowMask] = uint32(d.chainHead)
426 *hh = uint32(d.index + d.hashOffset)
428 prevLength := d.length
429 prevOffset := d.offset
430 d.length = minMatchLength - 1
432 minIndex := d.index - windowSize
437 if d.chainHead-d.hashOffset >= minIndex &&
438 (d.fastSkipHashing != skipNever && lookahead > minMatchLength-1 ||
439 d.fastSkipHashing == skipNever && lookahead > prevLength && prevLength < d.lazy) {
440 if newLength, newOffset, ok := d.findMatch(d.index, d.chainHead-d.hashOffset, minMatchLength-1, lookahead); ok {
445 if d.fastSkipHashing != skipNever && d.length >= minMatchLength ||
446 d.fastSkipHashing == skipNever && prevLength >= minMatchLength && d.length <= prevLength {
447 // There was a match at the previous step, and the current match is
448 // not better. Output the previous match.
449 if d.fastSkipHashing != skipNever {
450 d.tokens = append(d.tokens, matchToken(uint32(d.length-baseMatchLength), uint32(d.offset-baseMatchOffset)))
452 d.tokens = append(d.tokens, matchToken(uint32(prevLength-baseMatchLength), uint32(prevOffset-baseMatchOffset)))
454 // Insert in the hash table all strings up to the end of the match.
455 // index and index-1 are already inserted. If there is not enough
456 // lookahead, the last two strings are not inserted into the hash
458 if d.length <= d.fastSkipHashing {
460 if d.fastSkipHashing != skipNever {
461 newIndex = d.index + d.length
463 newIndex = d.index + prevLength - 1
465 for d.index++; d.index < newIndex; d.index++ {
466 if d.index < d.maxInsertIndex {
467 d.hash = hash4(d.window[d.index : d.index+minMatchLength])
468 // Get previous value with the same hash.
469 // Our chain should point to the previous value.
470 hh := &d.hashHead[d.hash&hashMask]
471 d.hashPrev[d.index&windowMask] = *hh
472 // Set the head of the hash chain to us.
473 *hh = uint32(d.index + d.hashOffset)
476 if d.fastSkipHashing == skipNever {
477 d.byteAvailable = false
478 d.length = minMatchLength - 1
481 // For matches this long, we don't bother inserting each individual
482 // item into the table.
484 if d.index < d.maxInsertIndex {
485 d.hash = hash4(d.window[d.index : d.index+minMatchLength])
488 if len(d.tokens) == maxFlateBlockTokens {
489 // The block includes the current character
490 if d.err = d.writeBlock(d.tokens, d.index); d.err != nil {
493 d.tokens = d.tokens[:0]
496 if d.fastSkipHashing != skipNever || d.byteAvailable {
498 if d.fastSkipHashing != skipNever {
501 d.tokens = append(d.tokens, literalToken(uint32(d.window[i])))
502 if len(d.tokens) == maxFlateBlockTokens {
503 if d.err = d.writeBlock(d.tokens, i+1); d.err != nil {
506 d.tokens = d.tokens[:0]
510 if d.fastSkipHashing == skipNever {
511 d.byteAvailable = true
517 func (d *compressor) fillStore(b []byte) int {
518 n := copy(d.window[d.windowEnd:], b)
523 func (d *compressor) store() {
524 if d.windowEnd > 0 && (d.windowEnd == maxStoreBlockSize || d.sync) {
525 d.err = d.writeStoredBlock(d.window[:d.windowEnd])
530 // storeHuff compresses and stores the currently added data
531 // when the d.window is full or we are at the end of the stream.
532 // Any error that occurred will be in d.err
533 func (d *compressor) storeHuff() {
534 if d.windowEnd < len(d.window) && !d.sync || d.windowEnd == 0 {
537 d.w.writeBlockHuff(false, d.window[:d.windowEnd])
542 func (d *compressor) write(b []byte) (n int, err error) {
557 func (d *compressor) syncFlush() error {
564 d.w.writeStoredHeader(0, false)
572 func (d *compressor) init(w io.Writer, level int) (err error) {
573 d.w = newHuffmanBitWriter(w)
576 case level == NoCompression:
577 d.window = make([]byte, maxStoreBlockSize)
578 d.fill = (*compressor).fillStore
579 d.step = (*compressor).store
580 case level == HuffmanOnly:
581 d.window = make([]byte, maxStoreBlockSize)
582 d.fill = (*compressor).fillStore
583 d.step = (*compressor).storeHuff
584 case level == BestSpeed:
585 d.compressionLevel = levels[level]
586 d.window = make([]byte, maxStoreBlockSize)
587 d.fill = (*compressor).fillStore
588 d.step = (*compressor).encSpeed
589 d.bestSpeed = newDeflateFast()
590 d.tokens = make([]token, maxStoreBlockSize)
591 case level == DefaultCompression:
594 case 2 <= level && level <= 9:
595 d.compressionLevel = levels[level]
597 d.fill = (*compressor).fillDeflate
598 d.step = (*compressor).deflate
600 return fmt.Errorf("flate: invalid compression level %d: want value in range [-2, 9]", level)
605 func (d *compressor) reset(w io.Writer) {
609 switch d.compressionLevel.level {
614 d.tokens = d.tokens[:0]
618 for i := range d.hashHead {
621 for i := range d.hashPrev {
625 d.index, d.windowEnd = 0, 0
626 d.blockStart, d.byteAvailable = 0, false
627 d.tokens = d.tokens[:0]
628 d.length = minMatchLength - 1
635 func (d *compressor) close() error {
644 if d.w.writeStoredHeader(0, true); d.w.err != nil {
651 // NewWriter returns a new Writer compressing data at the given level.
652 // Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression);
653 // higher levels typically run slower but compress more. Level 0
654 // (NoCompression) does not attempt any compression; it only adds the
655 // necessary DEFLATE framing.
656 // Level -1 (DefaultCompression) uses the default compression level.
657 // Level -2 (HuffmanOnly) will use Huffman compression only, giving
658 // a very fast compression for all types of input, but sacrificing considerable
659 // compression efficiency.
661 // If level is in the range [-2, 9] then the error returned will be nil.
662 // Otherwise the error returned will be non-nil.
663 func NewWriter(w io.Writer, level int) (*Writer, error) {
665 if err := dw.d.init(w, level); err != nil {
671 // NewWriterDict is like NewWriter but initializes the new
672 // Writer with a preset dictionary. The returned Writer behaves
673 // as if the dictionary had been written to it without producing
674 // any compressed output. The compressed data written to w
675 // can only be decompressed by a Reader initialized with the
677 func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) {
679 zw, err := NewWriter(dw, level)
683 zw.d.fillWindow(dict)
684 zw.dict = append(zw.dict, dict...) // duplicate dictionary for Reset method.
688 type dictWriter struct {
692 func (w *dictWriter) Write(b []byte) (n int, err error) {
696 // A Writer takes data written to it and writes the compressed
697 // form of that data to an underlying writer (see NewWriter).
703 // Write writes data to w, which will eventually write the
704 // compressed form of data to its underlying writer.
705 func (w *Writer) Write(data []byte) (n int, err error) {
706 return w.d.write(data)
709 // Flush flushes any pending data to the underlying writer.
710 // It is useful mainly in compressed network protocols, to ensure that
711 // a remote reader has enough data to reconstruct a packet.
712 // Flush does not return until the data has been written.
713 // Calling Flush when there is no pending data still causes the Writer
714 // to emit a sync marker of at least 4 bytes.
715 // If the underlying writer returns an error, Flush returns that error.
717 // In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
718 func (w *Writer) Flush() error {
719 // For more about flushing:
720 // http://www.bolet.org/~pornin/deflate-flush.html
721 return w.d.syncFlush()
724 // Close flushes and closes the writer.
725 func (w *Writer) Close() error {
729 // Reset discards the writer's state and makes it equivalent to
730 // the result of NewWriter or NewWriterDict called with dst
731 // and w's level and dictionary.
732 func (w *Writer) Reset(dst io.Writer) {
733 if dw, ok := w.d.w.writer.(*dictWriter); ok {
734 // w was created with NewWriterDict
737 w.d.fillWindow(w.dict)
739 // w was created with NewWriter