github.com/d4l3k/go@v0.0.0-20151015000803-65fc379daeda/src/compress/flate/inflate.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 implements the DEFLATE compressed data format, described in
     6  // RFC 1951.  The gzip and zlib packages implement access to DEFLATE-based file
     7  // formats.
     8  package flate
     9  
    10  import (
    11  	"bufio"
    12  	"io"
    13  	"strconv"
    14  	"sync"
    15  )
    16  
    17  const (
    18  	maxCodeLen = 16    // max length of Huffman code
    19  	maxHist    = 32768 // max history required
    20  	// The next three numbers come from the RFC section 3.2.7, with the
    21  	// additional proviso in section 3.2.5 which implies that distance codes
    22  	// 30 and 31 should never occur in compressed data.
    23  	maxNumLit  = 286
    24  	maxNumDist = 30
    25  	numCodes   = 19 // number of codes in Huffman meta-code
    26  )
    27  
    28  // Initialize the fixedHuffmanDecoder only once upon first use.
    29  var fixedOnce sync.Once
    30  var fixedHuffmanDecoder huffmanDecoder
    31  
    32  // A CorruptInputError reports the presence of corrupt input at a given offset.
    33  type CorruptInputError int64
    34  
    35  func (e CorruptInputError) Error() string {
    36  	return "flate: corrupt input before offset " + strconv.FormatInt(int64(e), 10)
    37  }
    38  
    39  // An InternalError reports an error in the flate code itself.
    40  type InternalError string
    41  
    42  func (e InternalError) Error() string { return "flate: internal error: " + string(e) }
    43  
    44  // A ReadError reports an error encountered while reading input.
    45  //
    46  // Deprecated: No longer returned.
    47  type ReadError struct {
    48  	Offset int64 // byte offset where error occurred
    49  	Err    error // error returned by underlying Read
    50  }
    51  
    52  func (e *ReadError) Error() string {
    53  	return "flate: read error at offset " + strconv.FormatInt(e.Offset, 10) + ": " + e.Err.Error()
    54  }
    55  
    56  // A WriteError reports an error encountered while writing output.
    57  //
    58  // Deprecated: No longer returned.
    59  type WriteError struct {
    60  	Offset int64 // byte offset where error occurred
    61  	Err    error // error returned by underlying Write
    62  }
    63  
    64  func (e *WriteError) Error() string {
    65  	return "flate: write error at offset " + strconv.FormatInt(e.Offset, 10) + ": " + e.Err.Error()
    66  }
    67  
    68  // Resetter resets a ReadCloser returned by NewReader or NewReaderDict to
    69  // to switch to a new underlying Reader. This permits reusing a ReadCloser
    70  // instead of allocating a new one.
    71  type Resetter interface {
    72  	// Reset discards any buffered data and resets the Resetter as if it was
    73  	// newly initialized with the given reader.
    74  	Reset(r io.Reader, dict []byte) error
    75  }
    76  
    77  // The data structure for decoding Huffman tables is based on that of
    78  // zlib. There is a lookup table of a fixed bit width (huffmanChunkBits),
    79  // For codes smaller than the table width, there are multiple entries
    80  // (each combination of trailing bits has the same value). For codes
    81  // larger than the table width, the table contains a link to an overflow
    82  // table. The width of each entry in the link table is the maximum code
    83  // size minus the chunk width.
    84  //
    85  // Note that you can do a lookup in the table even without all bits
    86  // filled. Since the extra bits are zero, and the DEFLATE Huffman codes
    87  // have the property that shorter codes come before longer ones, the
    88  // bit length estimate in the result is a lower bound on the actual
    89  // number of bits.
    90  //
    91  // See the following:
    92  //	http://www.gzip.org/algorithm.txt
    93  
    94  // chunk & 15 is number of bits
    95  // chunk >> 4 is value, including table link
    96  
    97  const (
    98  	huffmanChunkBits  = 9
    99  	huffmanNumChunks  = 1 << huffmanChunkBits
   100  	huffmanCountMask  = 15
   101  	huffmanValueShift = 4
   102  )
   103  
   104  type huffmanDecoder struct {
   105  	min      int                      // the minimum code length
   106  	chunks   [huffmanNumChunks]uint32 // chunks as described above
   107  	links    [][]uint32               // overflow links
   108  	linkMask uint32                   // mask the width of the link table
   109  }
   110  
   111  // Initialize Huffman decoding tables from array of code lengths.
   112  // Following this function, h is guaranteed to be initialized into a complete
   113  // tree (i.e., neither over-subscribed nor under-subscribed). The exception is a
   114  // degenerate case where the tree has only a single symbol with length 1. Empty
   115  // trees are permitted.
   116  func (h *huffmanDecoder) init(bits []int) bool {
   117  	// Sanity enables additional runtime tests during Huffman
   118  	// table construction.  It's intended to be used during
   119  	// development to supplement the currently ad-hoc unit tests.
   120  	const sanity = false
   121  
   122  	if h.min != 0 {
   123  		*h = huffmanDecoder{}
   124  	}
   125  
   126  	// Count number of codes of each length,
   127  	// compute min and max length.
   128  	var count [maxCodeLen]int
   129  	var min, max int
   130  	for _, n := range bits {
   131  		if n == 0 {
   132  			continue
   133  		}
   134  		if min == 0 || n < min {
   135  			min = n
   136  		}
   137  		if n > max {
   138  			max = n
   139  		}
   140  		count[n]++
   141  	}
   142  
   143  	// Empty tree. The decompressor.huffSym function will fail later if the tree
   144  	// is used. Technically, an empty tree is only valid for the HDIST tree and
   145  	// not the HCLEN and HLIT tree. However, a stream with an empty HCLEN tree
   146  	// is guaranteed to fail since it will attempt to use the tree to decode the
   147  	// codes for the HLIT and HDIST trees. Similarly, an empty HLIT tree is
   148  	// guaranteed to fail later since the compressed data section must be
   149  	// composed of at least one symbol (the end-of-block marker).
   150  	if max == 0 {
   151  		return true
   152  	}
   153  
   154  	code := 0
   155  	var nextcode [maxCodeLen]int
   156  	for i := min; i <= max; i++ {
   157  		code <<= 1
   158  		nextcode[i] = code
   159  		code += count[i]
   160  	}
   161  
   162  	// Check that the coding is complete (i.e., that we've
   163  	// assigned all 2-to-the-max possible bit sequences).
   164  	// Exception: To be compatible with zlib, we also need to
   165  	// accept degenerate single-code codings.  See also
   166  	// TestDegenerateHuffmanCoding.
   167  	if code != 1<<uint(max) && !(code == 1 && max == 1) {
   168  		return false
   169  	}
   170  
   171  	h.min = min
   172  	if max > huffmanChunkBits {
   173  		numLinks := 1 << (uint(max) - huffmanChunkBits)
   174  		h.linkMask = uint32(numLinks - 1)
   175  
   176  		// create link tables
   177  		link := nextcode[huffmanChunkBits+1] >> 1
   178  		h.links = make([][]uint32, huffmanNumChunks-link)
   179  		for j := uint(link); j < huffmanNumChunks; j++ {
   180  			reverse := int(reverseByte[j>>8]) | int(reverseByte[j&0xff])<<8
   181  			reverse >>= uint(16 - huffmanChunkBits)
   182  			off := j - uint(link)
   183  			if sanity && h.chunks[reverse] != 0 {
   184  				panic("impossible: overwriting existing chunk")
   185  			}
   186  			h.chunks[reverse] = uint32(off<<huffmanValueShift | (huffmanChunkBits + 1))
   187  			h.links[off] = make([]uint32, numLinks)
   188  		}
   189  	}
   190  
   191  	for i, n := range bits {
   192  		if n == 0 {
   193  			continue
   194  		}
   195  		code := nextcode[n]
   196  		nextcode[n]++
   197  		chunk := uint32(i<<huffmanValueShift | n)
   198  		reverse := int(reverseByte[code>>8]) | int(reverseByte[code&0xff])<<8
   199  		reverse >>= uint(16 - n)
   200  		if n <= huffmanChunkBits {
   201  			for off := reverse; off < len(h.chunks); off += 1 << uint(n) {
   202  				// We should never need to overwrite
   203  				// an existing chunk.  Also, 0 is
   204  				// never a valid chunk, because the
   205  				// lower 4 "count" bits should be
   206  				// between 1 and 15.
   207  				if sanity && h.chunks[off] != 0 {
   208  					panic("impossible: overwriting existing chunk")
   209  				}
   210  				h.chunks[off] = chunk
   211  			}
   212  		} else {
   213  			j := reverse & (huffmanNumChunks - 1)
   214  			if sanity && h.chunks[j]&huffmanCountMask != huffmanChunkBits+1 {
   215  				// Longer codes should have been
   216  				// associated with a link table above.
   217  				panic("impossible: not an indirect chunk")
   218  			}
   219  			value := h.chunks[j] >> huffmanValueShift
   220  			linktab := h.links[value]
   221  			reverse >>= huffmanChunkBits
   222  			for off := reverse; off < len(linktab); off += 1 << uint(n-huffmanChunkBits) {
   223  				if sanity && linktab[off] != 0 {
   224  					panic("impossible: overwriting existing chunk")
   225  				}
   226  				linktab[off] = chunk
   227  			}
   228  		}
   229  	}
   230  
   231  	if sanity {
   232  		// Above we've sanity checked that we never overwrote
   233  		// an existing entry.  Here we additionally check that
   234  		// we filled the tables completely.
   235  		for i, chunk := range h.chunks {
   236  			if chunk == 0 {
   237  				// As an exception, in the degenerate
   238  				// single-code case, we allow odd
   239  				// chunks to be missing.
   240  				if code == 1 && i%2 == 1 {
   241  					continue
   242  				}
   243  				panic("impossible: missing chunk")
   244  			}
   245  		}
   246  		for _, linktab := range h.links {
   247  			for _, chunk := range linktab {
   248  				if chunk == 0 {
   249  					panic("impossible: missing chunk")
   250  				}
   251  			}
   252  		}
   253  	}
   254  
   255  	return true
   256  }
   257  
   258  // The actual read interface needed by NewReader.
   259  // If the passed in io.Reader does not also have ReadByte,
   260  // the NewReader will introduce its own buffering.
   261  type Reader interface {
   262  	io.Reader
   263  	io.ByteReader
   264  }
   265  
   266  // Decompress state.
   267  type decompressor struct {
   268  	// Input source.
   269  	r       Reader
   270  	roffset int64
   271  	woffset int64
   272  
   273  	// Input bits, in top of b.
   274  	b  uint32
   275  	nb uint
   276  
   277  	// Huffman decoders for literal/length, distance.
   278  	h1, h2 huffmanDecoder
   279  
   280  	// Length arrays used to define Huffman codes.
   281  	bits     *[maxNumLit + maxNumDist]int
   282  	codebits *[numCodes]int
   283  
   284  	// Output history, buffer.
   285  	hist  *[maxHist]byte
   286  	hp    int  // current output position in buffer
   287  	hw    int  // have written hist[0:hw] already
   288  	hfull bool // buffer has filled at least once
   289  
   290  	// Temporary buffer (avoids repeated allocation).
   291  	buf [4]byte
   292  
   293  	// Next step in the decompression,
   294  	// and decompression state.
   295  	step     func(*decompressor)
   296  	final    bool
   297  	err      error
   298  	toRead   []byte
   299  	hl, hd   *huffmanDecoder
   300  	copyLen  int
   301  	copyDist int
   302  }
   303  
   304  func (f *decompressor) nextBlock() {
   305  	if f.final {
   306  		if f.hw != f.hp {
   307  			f.flush((*decompressor).nextBlock)
   308  			return
   309  		}
   310  		f.err = io.EOF
   311  		return
   312  	}
   313  	for f.nb < 1+2 {
   314  		if f.err = f.moreBits(); f.err != nil {
   315  			return
   316  		}
   317  	}
   318  	f.final = f.b&1 == 1
   319  	f.b >>= 1
   320  	typ := f.b & 3
   321  	f.b >>= 2
   322  	f.nb -= 1 + 2
   323  	switch typ {
   324  	case 0:
   325  		f.dataBlock()
   326  	case 1:
   327  		// compressed, fixed Huffman tables
   328  		f.hl = &fixedHuffmanDecoder
   329  		f.hd = nil
   330  		f.huffmanBlock()
   331  	case 2:
   332  		// compressed, dynamic Huffman tables
   333  		if f.err = f.readHuffman(); f.err != nil {
   334  			break
   335  		}
   336  		f.hl = &f.h1
   337  		f.hd = &f.h2
   338  		f.huffmanBlock()
   339  	default:
   340  		// 3 is reserved.
   341  		f.err = CorruptInputError(f.roffset)
   342  	}
   343  }
   344  
   345  func (f *decompressor) Read(b []byte) (int, error) {
   346  	for {
   347  		if len(f.toRead) > 0 {
   348  			n := copy(b, f.toRead)
   349  			f.toRead = f.toRead[n:]
   350  			return n, nil
   351  		}
   352  		if f.err != nil {
   353  			return 0, f.err
   354  		}
   355  		f.step(f)
   356  	}
   357  }
   358  
   359  func (f *decompressor) Close() error {
   360  	if f.err == io.EOF {
   361  		return nil
   362  	}
   363  	return f.err
   364  }
   365  
   366  // RFC 1951 section 3.2.7.
   367  // Compression with dynamic Huffman codes
   368  
   369  var codeOrder = [...]int{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
   370  
   371  func (f *decompressor) readHuffman() error {
   372  	// HLIT[5], HDIST[5], HCLEN[4].
   373  	for f.nb < 5+5+4 {
   374  		if err := f.moreBits(); err != nil {
   375  			return err
   376  		}
   377  	}
   378  	nlit := int(f.b&0x1F) + 257
   379  	if nlit > maxNumLit {
   380  		return CorruptInputError(f.roffset)
   381  	}
   382  	f.b >>= 5
   383  	ndist := int(f.b&0x1F) + 1
   384  	if ndist > maxNumDist {
   385  		return CorruptInputError(f.roffset)
   386  	}
   387  	f.b >>= 5
   388  	nclen := int(f.b&0xF) + 4
   389  	// numCodes is 19, so nclen is always valid.
   390  	f.b >>= 4
   391  	f.nb -= 5 + 5 + 4
   392  
   393  	// (HCLEN+4)*3 bits: code lengths in the magic codeOrder order.
   394  	for i := 0; i < nclen; i++ {
   395  		for f.nb < 3 {
   396  			if err := f.moreBits(); err != nil {
   397  				return err
   398  			}
   399  		}
   400  		f.codebits[codeOrder[i]] = int(f.b & 0x7)
   401  		f.b >>= 3
   402  		f.nb -= 3
   403  	}
   404  	for i := nclen; i < len(codeOrder); i++ {
   405  		f.codebits[codeOrder[i]] = 0
   406  	}
   407  	if !f.h1.init(f.codebits[0:]) {
   408  		return CorruptInputError(f.roffset)
   409  	}
   410  
   411  	// HLIT + 257 code lengths, HDIST + 1 code lengths,
   412  	// using the code length Huffman code.
   413  	for i, n := 0, nlit+ndist; i < n; {
   414  		x, err := f.huffSym(&f.h1)
   415  		if err != nil {
   416  			return err
   417  		}
   418  		if x < 16 {
   419  			// Actual length.
   420  			f.bits[i] = x
   421  			i++
   422  			continue
   423  		}
   424  		// Repeat previous length or zero.
   425  		var rep int
   426  		var nb uint
   427  		var b int
   428  		switch x {
   429  		default:
   430  			return InternalError("unexpected length code")
   431  		case 16:
   432  			rep = 3
   433  			nb = 2
   434  			if i == 0 {
   435  				return CorruptInputError(f.roffset)
   436  			}
   437  			b = f.bits[i-1]
   438  		case 17:
   439  			rep = 3
   440  			nb = 3
   441  			b = 0
   442  		case 18:
   443  			rep = 11
   444  			nb = 7
   445  			b = 0
   446  		}
   447  		for f.nb < nb {
   448  			if err := f.moreBits(); err != nil {
   449  				return err
   450  			}
   451  		}
   452  		rep += int(f.b & uint32(1<<nb-1))
   453  		f.b >>= nb
   454  		f.nb -= nb
   455  		if i+rep > n {
   456  			return CorruptInputError(f.roffset)
   457  		}
   458  		for j := 0; j < rep; j++ {
   459  			f.bits[i] = b
   460  			i++
   461  		}
   462  	}
   463  
   464  	if !f.h1.init(f.bits[0:nlit]) || !f.h2.init(f.bits[nlit:nlit+ndist]) {
   465  		return CorruptInputError(f.roffset)
   466  	}
   467  
   468  	return nil
   469  }
   470  
   471  // Decode a single Huffman block from f.
   472  // hl and hd are the Huffman states for the lit/length values
   473  // and the distance values, respectively.  If hd == nil, using the
   474  // fixed distance encoding associated with fixed Huffman blocks.
   475  func (f *decompressor) huffmanBlock() {
   476  	for {
   477  		v, err := f.huffSym(f.hl)
   478  		if err != nil {
   479  			f.err = err
   480  			return
   481  		}
   482  		var n uint // number of bits extra
   483  		var length int
   484  		switch {
   485  		case v < 256:
   486  			f.hist[f.hp] = byte(v)
   487  			f.hp++
   488  			if f.hp == len(f.hist) {
   489  				// After the flush, continue this loop.
   490  				f.flush((*decompressor).huffmanBlock)
   491  				return
   492  			}
   493  			continue
   494  		case v == 256:
   495  			// Done with huffman block; read next block.
   496  			f.step = (*decompressor).nextBlock
   497  			return
   498  		// otherwise, reference to older data
   499  		case v < 265:
   500  			length = v - (257 - 3)
   501  			n = 0
   502  		case v < 269:
   503  			length = v*2 - (265*2 - 11)
   504  			n = 1
   505  		case v < 273:
   506  			length = v*4 - (269*4 - 19)
   507  			n = 2
   508  		case v < 277:
   509  			length = v*8 - (273*8 - 35)
   510  			n = 3
   511  		case v < 281:
   512  			length = v*16 - (277*16 - 67)
   513  			n = 4
   514  		case v < 285:
   515  			length = v*32 - (281*32 - 131)
   516  			n = 5
   517  		case v < maxNumLit:
   518  			length = 258
   519  			n = 0
   520  		default:
   521  			f.err = CorruptInputError(f.roffset)
   522  			return
   523  		}
   524  		if n > 0 {
   525  			for f.nb < n {
   526  				if err = f.moreBits(); err != nil {
   527  					f.err = err
   528  					return
   529  				}
   530  			}
   531  			length += int(f.b & uint32(1<<n-1))
   532  			f.b >>= n
   533  			f.nb -= n
   534  		}
   535  
   536  		var dist int
   537  		if f.hd == nil {
   538  			for f.nb < 5 {
   539  				if err = f.moreBits(); err != nil {
   540  					f.err = err
   541  					return
   542  				}
   543  			}
   544  			dist = int(reverseByte[(f.b&0x1F)<<3])
   545  			f.b >>= 5
   546  			f.nb -= 5
   547  		} else {
   548  			if dist, err = f.huffSym(f.hd); err != nil {
   549  				f.err = err
   550  				return
   551  			}
   552  		}
   553  
   554  		switch {
   555  		case dist < 4:
   556  			dist++
   557  		case dist < maxNumDist:
   558  			nb := uint(dist-2) >> 1
   559  			// have 1 bit in bottom of dist, need nb more.
   560  			extra := (dist & 1) << nb
   561  			for f.nb < nb {
   562  				if err = f.moreBits(); err != nil {
   563  					f.err = err
   564  					return
   565  				}
   566  			}
   567  			extra |= int(f.b & uint32(1<<nb-1))
   568  			f.b >>= nb
   569  			f.nb -= nb
   570  			dist = 1<<(nb+1) + 1 + extra
   571  		default:
   572  			f.err = CorruptInputError(f.roffset)
   573  			return
   574  		}
   575  
   576  		// Copy history[-dist:-dist+length] into output.
   577  		if dist > len(f.hist) {
   578  			f.err = InternalError("bad history distance")
   579  			return
   580  		}
   581  
   582  		// No check on length; encoding can be prescient.
   583  		if !f.hfull && dist > f.hp {
   584  			f.err = CorruptInputError(f.roffset)
   585  			return
   586  		}
   587  
   588  		f.copyLen, f.copyDist = length, dist
   589  		if f.copyHist() {
   590  			return
   591  		}
   592  	}
   593  }
   594  
   595  // copyHist copies f.copyLen bytes from f.hist (f.copyDist bytes ago) to itself.
   596  // It reports whether the f.hist buffer is full.
   597  func (f *decompressor) copyHist() bool {
   598  	p := f.hp - f.copyDist
   599  	if p < 0 {
   600  		p += len(f.hist)
   601  	}
   602  	for f.copyLen > 0 {
   603  		n := f.copyLen
   604  		if x := len(f.hist) - f.hp; n > x {
   605  			n = x
   606  		}
   607  		if x := len(f.hist) - p; n > x {
   608  			n = x
   609  		}
   610  		forwardCopy(f.hist[:], f.hp, p, n)
   611  		p += n
   612  		f.hp += n
   613  		f.copyLen -= n
   614  		if f.hp == len(f.hist) {
   615  			// After flush continue copying out of history.
   616  			f.flush((*decompressor).copyHuff)
   617  			return true
   618  		}
   619  		if p == len(f.hist) {
   620  			p = 0
   621  		}
   622  	}
   623  	return false
   624  }
   625  
   626  func (f *decompressor) copyHuff() {
   627  	if f.copyHist() {
   628  		return
   629  	}
   630  	f.huffmanBlock()
   631  }
   632  
   633  // Copy a single uncompressed data block from input to output.
   634  func (f *decompressor) dataBlock() {
   635  	// Uncompressed.
   636  	// Discard current half-byte.
   637  	f.nb = 0
   638  	f.b = 0
   639  
   640  	// Length then ones-complement of length.
   641  	nr, err := io.ReadFull(f.r, f.buf[0:4])
   642  	f.roffset += int64(nr)
   643  	if err != nil {
   644  		if err == io.EOF {
   645  			err = io.ErrUnexpectedEOF
   646  		}
   647  		f.err = err
   648  		return
   649  	}
   650  	n := int(f.buf[0]) | int(f.buf[1])<<8
   651  	nn := int(f.buf[2]) | int(f.buf[3])<<8
   652  	if uint16(nn) != uint16(^n) {
   653  		f.err = CorruptInputError(f.roffset)
   654  		return
   655  	}
   656  
   657  	if n == 0 {
   658  		// 0-length block means sync
   659  		f.flush((*decompressor).nextBlock)
   660  		return
   661  	}
   662  
   663  	f.copyLen = n
   664  	f.copyData()
   665  }
   666  
   667  // copyData copies f.copyLen bytes from the underlying reader into f.hist.
   668  // It pauses for reads when f.hist is full.
   669  func (f *decompressor) copyData() {
   670  	n := f.copyLen
   671  	for n > 0 {
   672  		m := len(f.hist) - f.hp
   673  		if m > n {
   674  			m = n
   675  		}
   676  		m, err := io.ReadFull(f.r, f.hist[f.hp:f.hp+m])
   677  		f.roffset += int64(m)
   678  		if err != nil {
   679  			if err == io.EOF {
   680  				err = io.ErrUnexpectedEOF
   681  			}
   682  			f.err = err
   683  			return
   684  		}
   685  		n -= m
   686  		f.hp += m
   687  		if f.hp == len(f.hist) {
   688  			f.copyLen = n
   689  			f.flush((*decompressor).copyData)
   690  			return
   691  		}
   692  	}
   693  	f.step = (*decompressor).nextBlock
   694  }
   695  
   696  func (f *decompressor) setDict(dict []byte) {
   697  	if len(dict) > len(f.hist) {
   698  		// Will only remember the tail.
   699  		dict = dict[len(dict)-len(f.hist):]
   700  	}
   701  
   702  	f.hp = copy(f.hist[:], dict)
   703  	if f.hp == len(f.hist) {
   704  		f.hp = 0
   705  		f.hfull = true
   706  	}
   707  	f.hw = f.hp
   708  }
   709  
   710  func (f *decompressor) moreBits() error {
   711  	c, err := f.r.ReadByte()
   712  	if err != nil {
   713  		if err == io.EOF {
   714  			err = io.ErrUnexpectedEOF
   715  		}
   716  		return err
   717  	}
   718  	f.roffset++
   719  	f.b |= uint32(c) << f.nb
   720  	f.nb += 8
   721  	return nil
   722  }
   723  
   724  // Read the next Huffman-encoded symbol from f according to h.
   725  func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) {
   726  	// Since a huffmanDecoder can be empty or be composed of a degenerate tree
   727  	// with single element, huffSym must error on these two edge cases. In both
   728  	// cases, the chunks slice will be 0 for the invalid sequence, leading it
   729  	// satisfy the n == 0 check below.
   730  	n := uint(h.min)
   731  	for {
   732  		for f.nb < n {
   733  			if err := f.moreBits(); err != nil {
   734  				return 0, err
   735  			}
   736  		}
   737  		chunk := h.chunks[f.b&(huffmanNumChunks-1)]
   738  		n = uint(chunk & huffmanCountMask)
   739  		if n > huffmanChunkBits {
   740  			chunk = h.links[chunk>>huffmanValueShift][(f.b>>huffmanChunkBits)&h.linkMask]
   741  			n = uint(chunk & huffmanCountMask)
   742  		}
   743  		if n <= f.nb {
   744  			if n == 0 {
   745  				f.err = CorruptInputError(f.roffset)
   746  				return 0, f.err
   747  			}
   748  			f.b >>= n
   749  			f.nb -= n
   750  			return int(chunk >> huffmanValueShift), nil
   751  		}
   752  	}
   753  }
   754  
   755  // Flush any buffered output to the underlying writer.
   756  func (f *decompressor) flush(step func(*decompressor)) {
   757  	f.toRead = f.hist[f.hw:f.hp]
   758  	f.woffset += int64(f.hp - f.hw)
   759  	f.hw = f.hp
   760  	if f.hp == len(f.hist) {
   761  		f.hp = 0
   762  		f.hw = 0
   763  		f.hfull = true
   764  	}
   765  	f.step = step
   766  }
   767  
   768  func makeReader(r io.Reader) Reader {
   769  	if rr, ok := r.(Reader); ok {
   770  		return rr
   771  	}
   772  	return bufio.NewReader(r)
   773  }
   774  
   775  func fixedHuffmanDecoderInit() {
   776  	fixedOnce.Do(func() {
   777  		// These come from the RFC section 3.2.6.
   778  		var bits [288]int
   779  		for i := 0; i < 144; i++ {
   780  			bits[i] = 8
   781  		}
   782  		for i := 144; i < 256; i++ {
   783  			bits[i] = 9
   784  		}
   785  		for i := 256; i < 280; i++ {
   786  			bits[i] = 7
   787  		}
   788  		for i := 280; i < 288; i++ {
   789  			bits[i] = 8
   790  		}
   791  		fixedHuffmanDecoder.init(bits[:])
   792  	})
   793  }
   794  
   795  func (f *decompressor) Reset(r io.Reader, dict []byte) error {
   796  	*f = decompressor{
   797  		r:        makeReader(r),
   798  		bits:     f.bits,
   799  		codebits: f.codebits,
   800  		hist:     f.hist,
   801  		step:     (*decompressor).nextBlock,
   802  	}
   803  	if dict != nil {
   804  		f.setDict(dict)
   805  	}
   806  	return nil
   807  }
   808  
   809  // NewReader returns a new ReadCloser that can be used
   810  // to read the uncompressed version of r.
   811  // If r does not also implement io.ByteReader,
   812  // the decompressor may read more data than necessary from r.
   813  // It is the caller's responsibility to call Close on the ReadCloser
   814  // when finished reading.
   815  //
   816  // The ReadCloser returned by NewReader also implements Resetter.
   817  func NewReader(r io.Reader) io.ReadCloser {
   818  	fixedHuffmanDecoderInit()
   819  
   820  	var f decompressor
   821  	f.r = makeReader(r)
   822  	f.hist = new([maxHist]byte)
   823  	f.bits = new([maxNumLit + maxNumDist]int)
   824  	f.codebits = new([numCodes]int)
   825  	f.step = (*decompressor).nextBlock
   826  	return &f
   827  }
   828  
   829  // NewReaderDict is like NewReader but initializes the reader
   830  // with a preset dictionary.  The returned Reader behaves as if
   831  // the uncompressed data stream started with the given dictionary,
   832  // which has already been read.  NewReaderDict is typically used
   833  // to read data compressed by NewWriterDict.
   834  //
   835  // The ReadCloser returned by NewReader also implements Resetter.
   836  func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser {
   837  	fixedHuffmanDecoderInit()
   838  
   839  	var f decompressor
   840  	f.r = makeReader(r)
   841  	f.hist = new([maxHist]byte)
   842  	f.bits = new([maxNumLit + maxNumDist]int)
   843  	f.codebits = new([numCodes]int)
   844  	f.step = (*decompressor).nextBlock
   845  	f.setDict(dict)
   846  	return &f
   847  }