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