github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/compress/flate/deflate.go (about)

     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.
     4  
     5  package flate
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  	"math"
    11  )
    12  
    13  const (
    14  	NoCompression      = 0
    15  	BestSpeed          = 1
    16  	BestCompression    = 9
    17  	DefaultCompression = -1
    18  
    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.
    24  	//
    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.
    28  	HuffmanOnly = -2
    29  )
    30  
    31  const (
    32  	logWindowSize = 15
    33  	windowSize    = 1 << logWindowSize
    34  	windowMask    = windowSize - 1
    35  
    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
    47  
    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
    56  
    57  	skipNever = math.MaxInt32
    58  )
    59  
    60  type compressionLevel struct {
    61  	level, good, lazy, nice, chain, fastSkipHashing int
    62  }
    63  
    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.
    68  	{2, 4, 0, 16, 8, 5},
    69  	{3, 4, 0, 32, 32, 6},
    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},
    78  }
    79  
    80  type compressor struct {
    81  	compressionLevel
    82  
    83  	w          *huffmanBitWriter
    84  	bulkHasher func([]byte, []uint32)
    85  
    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
    91  
    92  	// Input hash chains
    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.
    97  	chainHead  int
    98  	hashHead   [hashSize]uint32
    99  	hashPrev   [windowSize]uint32
   100  	hashOffset int
   101  
   102  	// input window: unprocessed data is window[index:windowEnd]
   103  	index         int
   104  	window        []byte
   105  	windowEnd     int
   106  	blockStart    int  // window index where current tokens start
   107  	byteAvailable bool // if true, still need to process window[index-1].
   108  
   109  	// queued output tokens
   110  	tokens []token
   111  
   112  	// deflate state
   113  	length         int
   114  	offset         int
   115  	hash           uint32
   116  	maxInsertIndex int
   117  	err            error
   118  
   119  	// hashMatch must be able to contain hashes for the maximum match length.
   120  	hashMatch [maxMatchLength - 1]uint32
   121  }
   122  
   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
   131  		} else {
   132  			d.blockStart = math.MaxInt32
   133  		}
   134  		d.hashOffset += windowSize
   135  		if d.hashOffset > maxHashOffset {
   136  			delta := d.hashOffset - 1
   137  			d.hashOffset -= delta
   138  			d.chainHead -= delta
   139  			for i, v := range d.hashPrev {
   140  				if int(v) > delta {
   141  					d.hashPrev[i] = uint32(int(v) - delta)
   142  				} else {
   143  					d.hashPrev[i] = 0
   144  				}
   145  			}
   146  			for i, v := range d.hashHead {
   147  				if int(v) > delta {
   148  					d.hashHead[i] = uint32(int(v) - delta)
   149  				} else {
   150  					d.hashHead[i] = 0
   151  				}
   152  			}
   153  		}
   154  	}
   155  	n := copy(d.window[d.windowEnd:], b)
   156  	d.windowEnd += n
   157  	return n
   158  }
   159  
   160  func (d *compressor) writeBlock(tokens []token, index int) error {
   161  	if index > 0 {
   162  		var window []byte
   163  		if d.blockStart <= index {
   164  			window = d.window[d.blockStart:index]
   165  		}
   166  		d.blockStart = index
   167  		d.w.writeBlock(tokens, false, window)
   168  		return d.w.err
   169  	}
   170  	return nil
   171  }
   172  
   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 {
   180  		return
   181  	}
   182  	if d.index != 0 || d.windowEnd != 0 {
   183  		panic("internal error: fillWindow called with stale data")
   184  	}
   185  
   186  	// If we are given too much, cut it.
   187  	if len(b) > windowSize {
   188  		b = b[len(b)-windowSize:]
   189  	}
   190  	// Add all to window.
   191  	n := copy(d.window, b)
   192  
   193  	// Calculate 256 hashes at the time (more L1 cache hits)
   194  	loops := (n + 256 - minMatchLength) / 256
   195  	for j := 0; j < loops; j++ {
   196  		index := j * 256
   197  		end := index + 256 + minMatchLength - 1
   198  		if end > n {
   199  			end = n
   200  		}
   201  		toCheck := d.window[index:end]
   202  		dstSize := len(toCheck) - minMatchLength + 1
   203  
   204  		if dstSize <= 0 {
   205  			continue
   206  		}
   207  
   208  		dst := d.hashMatch[:dstSize]
   209  		d.bulkHasher(toCheck, dst)
   210  		var newH uint32
   211  		for i, val := range dst {
   212  			di := i + index
   213  			newH = val
   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)
   220  		}
   221  		d.hash = newH
   222  	}
   223  	// Update window information.
   224  	d.windowEnd = n
   225  	d.index = n
   226  }
   227  
   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
   234  	}
   235  
   236  	win := d.window[0 : pos+minMatchLook]
   237  
   238  	// We quit when we get a match that's at least nice long
   239  	nice := len(win) - pos
   240  	if d.nice < nice {
   241  		nice = d.nice
   242  	}
   243  
   244  	// If we've got a match that's good enough, only look in 1/4 the chain.
   245  	tries := d.chain
   246  	length = prevLength
   247  	if length >= d.good {
   248  		tries >>= 2
   249  	}
   250  
   251  	wEnd := win[pos+length]
   252  	wPos := win[pos:]
   253  	minIndex := pos - windowSize
   254  
   255  	for i := prevHead; tries > 0; tries-- {
   256  		if wEnd == win[i+length] {
   257  			n := matchLen(win[i:], wPos, minMatchLook)
   258  
   259  			if n > length && (n > minMatchLength || pos-i <= 4096) {
   260  				length = n
   261  				offset = pos - i
   262  				ok = true
   263  				if n >= nice {
   264  					// The match is good enough that we don't try to find a better one.
   265  					break
   266  				}
   267  				wEnd = win[pos+n]
   268  			}
   269  		}
   270  		if i == minIndex {
   271  			// hashPrev[i & windowMask] has already been overwritten, so stop now.
   272  			break
   273  		}
   274  		i = int(d.hashPrev[i&windowMask]) - d.hashOffset
   275  		if i < minIndex || i < 0 {
   276  			break
   277  		}
   278  	}
   279  	return
   280  }
   281  
   282  func (d *compressor) writeStoredBlock(buf []byte) error {
   283  	if d.w.writeStoredHeader(len(buf), false); d.w.err != nil {
   284  		return d.w.err
   285  	}
   286  	d.w.writeBytes(buf)
   287  	return d.w.err
   288  }
   289  
   290  const hashmul = 0x1e35a7bd
   291  
   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)
   297  }
   298  
   299  // bulkHash4 will compute hashes using the same
   300  // algorithm as hash4
   301  func bulkHash4(b []byte, dst []uint32) {
   302  	if len(b) < minMatchLength {
   303  		return
   304  	}
   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)
   311  	}
   312  }
   313  
   314  // matchLen returns the number of matching bytes in a and b
   315  // up to length 'max'. Both slices must be at least 'max'
   316  // bytes in size.
   317  func matchLen(a, b []byte, max int) int {
   318  	a = a[:max]
   319  	b = b[:len(a)]
   320  	for i, av := range a {
   321  		if b[i] != av {
   322  			return i
   323  		}
   324  	}
   325  	return max
   326  }
   327  
   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 {
   334  		if !d.sync {
   335  			return
   336  		}
   337  
   338  		// Handle small sizes.
   339  		if d.windowEnd < 128 {
   340  			switch {
   341  			case d.windowEnd == 0:
   342  				return
   343  			case d.windowEnd <= 16:
   344  				d.err = d.writeStoredBlock(d.window[:d.windowEnd])
   345  			default:
   346  				d.w.writeBlockHuff(false, d.window[:d.windowEnd])
   347  				d.err = d.w.err
   348  			}
   349  			d.windowEnd = 0
   350  			d.bestSpeed.reset()
   351  			return
   352  		}
   353  
   354  	}
   355  	// Encode the block.
   356  	d.tokens = d.bestSpeed.encode(d.tokens[:0], d.window[:d.windowEnd])
   357  
   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])
   361  	} else {
   362  		d.w.writeBlockDynamic(d.tokens, false, d.window[:d.windowEnd])
   363  	}
   364  	d.err = d.w.err
   365  	d.windowEnd = 0
   366  }
   367  
   368  func (d *compressor) initDeflate() {
   369  	d.window = make([]byte, 2*windowSize)
   370  	d.hashOffset = 1
   371  	d.tokens = make([]token, 0, maxFlateBlockTokens+1)
   372  	d.length = minMatchLength - 1
   373  	d.offset = 0
   374  	d.byteAvailable = false
   375  	d.index = 0
   376  	d.hash = 0
   377  	d.chainHead = -1
   378  	d.bulkHasher = bulkHash4
   379  }
   380  
   381  func (d *compressor) deflate() {
   382  	if d.windowEnd-d.index < minMatchLength+maxMatchLength && !d.sync {
   383  		return
   384  	}
   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  
   391  Loop:
   392  	for {
   393  		if d.index > d.windowEnd {
   394  			panic("index > windowEnd")
   395  		}
   396  		lookahead := d.windowEnd - d.index
   397  		if lookahead < minMatchLength+maxMatchLength {
   398  			if !d.sync {
   399  				break Loop
   400  			}
   401  			if d.index > d.windowEnd {
   402  				panic("index > windowEnd")
   403  			}
   404  			if lookahead == 0 {
   405  				// Flush current output block if any.
   406  				if d.byteAvailable {
   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
   410  				}
   411  				if len(d.tokens) > 0 {
   412  					if d.err = d.writeBlock(d.tokens, d.index); d.err != nil {
   413  						return
   414  					}
   415  					d.tokens = d.tokens[:0]
   416  				}
   417  				break Loop
   418  			}
   419  		}
   420  		if d.index < d.maxInsertIndex {
   421  			// Update the hash
   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)
   427  		}
   428  		prevLength := d.length
   429  		prevOffset := d.offset
   430  		d.length = minMatchLength - 1
   431  		d.offset = 0
   432  		minIndex := d.index - windowSize
   433  		if minIndex < 0 {
   434  			minIndex = 0
   435  		}
   436  
   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 {
   441  				d.length = newLength
   442  				d.offset = newOffset
   443  			}
   444  		}
   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)))
   451  			} else {
   452  				d.tokens = append(d.tokens, matchToken(uint32(prevLength-baseMatchLength), uint32(prevOffset-baseMatchOffset)))
   453  			}
   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
   457  			// table.
   458  			if d.length <= d.fastSkipHashing {
   459  				var newIndex int
   460  				if d.fastSkipHashing != skipNever {
   461  					newIndex = d.index + d.length
   462  				} else {
   463  					newIndex = d.index + prevLength - 1
   464  				}
   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)
   474  					}
   475  				}
   476  				if d.fastSkipHashing == skipNever {
   477  					d.byteAvailable = false
   478  					d.length = minMatchLength - 1
   479  				}
   480  			} else {
   481  				// For matches this long, we don't bother inserting each individual
   482  				// item into the table.
   483  				d.index += d.length
   484  				if d.index < d.maxInsertIndex {
   485  					d.hash = hash4(d.window[d.index : d.index+minMatchLength])
   486  				}
   487  			}
   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 {
   491  					return
   492  				}
   493  				d.tokens = d.tokens[:0]
   494  			}
   495  		} else {
   496  			if d.fastSkipHashing != skipNever || d.byteAvailable {
   497  				i := d.index - 1
   498  				if d.fastSkipHashing != skipNever {
   499  					i = d.index
   500  				}
   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 {
   504  						return
   505  					}
   506  					d.tokens = d.tokens[:0]
   507  				}
   508  			}
   509  			d.index++
   510  			if d.fastSkipHashing == skipNever {
   511  				d.byteAvailable = true
   512  			}
   513  		}
   514  	}
   515  }
   516  
   517  func (d *compressor) fillStore(b []byte) int {
   518  	n := copy(d.window[d.windowEnd:], b)
   519  	d.windowEnd += n
   520  	return n
   521  }
   522  
   523  func (d *compressor) store() {
   524  	if d.windowEnd > 0 && (d.windowEnd == maxStoreBlockSize || d.sync) {
   525  		d.err = d.writeStoredBlock(d.window[:d.windowEnd])
   526  		d.windowEnd = 0
   527  	}
   528  }
   529  
   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 {
   535  		return
   536  	}
   537  	d.w.writeBlockHuff(false, d.window[:d.windowEnd])
   538  	d.err = d.w.err
   539  	d.windowEnd = 0
   540  }
   541  
   542  func (d *compressor) write(b []byte) (n int, err error) {
   543  	if d.err != nil {
   544  		return 0, d.err
   545  	}
   546  	n = len(b)
   547  	for len(b) > 0 {
   548  		d.step(d)
   549  		b = b[d.fill(d, b):]
   550  		if d.err != nil {
   551  			return 0, d.err
   552  		}
   553  	}
   554  	return n, nil
   555  }
   556  
   557  func (d *compressor) syncFlush() error {
   558  	if d.err != nil {
   559  		return d.err
   560  	}
   561  	d.sync = true
   562  	d.step(d)
   563  	if d.err == nil {
   564  		d.w.writeStoredHeader(0, false)
   565  		d.w.flush()
   566  		d.err = d.w.err
   567  	}
   568  	d.sync = false
   569  	return d.err
   570  }
   571  
   572  func (d *compressor) init(w io.Writer, level int) (err error) {
   573  	d.w = newHuffmanBitWriter(w)
   574  
   575  	switch {
   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:
   592  		level = 6
   593  		fallthrough
   594  	case 2 <= level && level <= 9:
   595  		d.compressionLevel = levels[level]
   596  		d.initDeflate()
   597  		d.fill = (*compressor).fillDeflate
   598  		d.step = (*compressor).deflate
   599  	default:
   600  		return fmt.Errorf("flate: invalid compression level %d: want value in range [-2, 9]", level)
   601  	}
   602  	return nil
   603  }
   604  
   605  func (d *compressor) reset(w io.Writer) {
   606  	d.w.reset(w)
   607  	d.sync = false
   608  	d.err = nil
   609  	switch d.compressionLevel.level {
   610  	case NoCompression:
   611  		d.windowEnd = 0
   612  	case BestSpeed:
   613  		d.windowEnd = 0
   614  		d.tokens = d.tokens[:0]
   615  		d.bestSpeed.reset()
   616  	default:
   617  		d.chainHead = -1
   618  		for i := range d.hashHead {
   619  			d.hashHead[i] = 0
   620  		}
   621  		for i := range d.hashPrev {
   622  			d.hashPrev[i] = 0
   623  		}
   624  		d.hashOffset = 1
   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
   629  		d.offset = 0
   630  		d.hash = 0
   631  		d.maxInsertIndex = 0
   632  	}
   633  }
   634  
   635  func (d *compressor) close() error {
   636  	if d.err != nil {
   637  		return d.err
   638  	}
   639  	d.sync = true
   640  	d.step(d)
   641  	if d.err != nil {
   642  		return d.err
   643  	}
   644  	if d.w.writeStoredHeader(0, true); d.w.err != nil {
   645  		return d.w.err
   646  	}
   647  	d.w.flush()
   648  	return d.w.err
   649  }
   650  
   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.
   660  //
   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) {
   664  	var dw Writer
   665  	if err := dw.d.init(w, level); err != nil {
   666  		return nil, err
   667  	}
   668  	return &dw, nil
   669  }
   670  
   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
   676  // same dictionary.
   677  func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) {
   678  	dw := &dictWriter{w}
   679  	zw, err := NewWriter(dw, level)
   680  	if err != nil {
   681  		return nil, err
   682  	}
   683  	zw.d.fillWindow(dict)
   684  	zw.dict = append(zw.dict, dict...) // duplicate dictionary for Reset method.
   685  	return zw, err
   686  }
   687  
   688  type dictWriter struct {
   689  	w io.Writer
   690  }
   691  
   692  func (w *dictWriter) Write(b []byte) (n int, err error) {
   693  	return w.w.Write(b)
   694  }
   695  
   696  // A Writer takes data written to it and writes the compressed
   697  // form of that data to an underlying writer (see NewWriter).
   698  type Writer struct {
   699  	d    compressor
   700  	dict []byte
   701  }
   702  
   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)
   707  }
   708  
   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.
   716  //
   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()
   722  }
   723  
   724  // Close flushes and closes the writer.
   725  func (w *Writer) Close() error {
   726  	return w.d.close()
   727  }
   728  
   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
   735  		dw.w = dst
   736  		w.d.reset(dw)
   737  		w.d.fillWindow(w.dict)
   738  	} else {
   739  		// w was created with NewWriter
   740  		w.d.reset(dst)
   741  	}
   742  }