github.com/aloncn/graphics-go@v0.0.1/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  	// As an optimization, we can initialize the min bits to read at a time
   469  	// for the HLIT tree to the length of the EOB marker since we know that
   470  	// every block must terminate with one. This preserves the property that
   471  	// we never read any extra bytes after the end of the DEFLATE stream.
   472  	if f.h1.min < f.bits[endBlockMarker] {
   473  		f.h1.min = f.bits[endBlockMarker]
   474  	}
   475  
   476  	return nil
   477  }
   478  
   479  // Decode a single Huffman block from f.
   480  // hl and hd are the Huffman states for the lit/length values
   481  // and the distance values, respectively.  If hd == nil, using the
   482  // fixed distance encoding associated with fixed Huffman blocks.
   483  func (f *decompressor) huffmanBlock() {
   484  	for {
   485  		v, err := f.huffSym(f.hl)
   486  		if err != nil {
   487  			f.err = err
   488  			return
   489  		}
   490  		var n uint // number of bits extra
   491  		var length int
   492  		switch {
   493  		case v < 256:
   494  			f.hist[f.hp] = byte(v)
   495  			f.hp++
   496  			if f.hp == len(f.hist) {
   497  				// After the flush, continue this loop.
   498  				f.flush((*decompressor).huffmanBlock)
   499  				return
   500  			}
   501  			continue
   502  		case v == 256:
   503  			// Done with huffman block; read next block.
   504  			f.step = (*decompressor).nextBlock
   505  			return
   506  		// otherwise, reference to older data
   507  		case v < 265:
   508  			length = v - (257 - 3)
   509  			n = 0
   510  		case v < 269:
   511  			length = v*2 - (265*2 - 11)
   512  			n = 1
   513  		case v < 273:
   514  			length = v*4 - (269*4 - 19)
   515  			n = 2
   516  		case v < 277:
   517  			length = v*8 - (273*8 - 35)
   518  			n = 3
   519  		case v < 281:
   520  			length = v*16 - (277*16 - 67)
   521  			n = 4
   522  		case v < 285:
   523  			length = v*32 - (281*32 - 131)
   524  			n = 5
   525  		case v < maxNumLit:
   526  			length = 258
   527  			n = 0
   528  		default:
   529  			f.err = CorruptInputError(f.roffset)
   530  			return
   531  		}
   532  		if n > 0 {
   533  			for f.nb < n {
   534  				if err = f.moreBits(); err != nil {
   535  					f.err = err
   536  					return
   537  				}
   538  			}
   539  			length += int(f.b & uint32(1<<n-1))
   540  			f.b >>= n
   541  			f.nb -= n
   542  		}
   543  
   544  		var dist int
   545  		if f.hd == nil {
   546  			for f.nb < 5 {
   547  				if err = f.moreBits(); err != nil {
   548  					f.err = err
   549  					return
   550  				}
   551  			}
   552  			dist = int(reverseByte[(f.b&0x1F)<<3])
   553  			f.b >>= 5
   554  			f.nb -= 5
   555  		} else {
   556  			if dist, err = f.huffSym(f.hd); err != nil {
   557  				f.err = err
   558  				return
   559  			}
   560  		}
   561  
   562  		switch {
   563  		case dist < 4:
   564  			dist++
   565  		case dist < maxNumDist:
   566  			nb := uint(dist-2) >> 1
   567  			// have 1 bit in bottom of dist, need nb more.
   568  			extra := (dist & 1) << nb
   569  			for f.nb < nb {
   570  				if err = f.moreBits(); err != nil {
   571  					f.err = err
   572  					return
   573  				}
   574  			}
   575  			extra |= int(f.b & uint32(1<<nb-1))
   576  			f.b >>= nb
   577  			f.nb -= nb
   578  			dist = 1<<(nb+1) + 1 + extra
   579  		default:
   580  			f.err = CorruptInputError(f.roffset)
   581  			return
   582  		}
   583  
   584  		// Copy history[-dist:-dist+length] into output.
   585  		if dist > len(f.hist) {
   586  			f.err = InternalError("bad history distance")
   587  			return
   588  		}
   589  
   590  		// No check on length; encoding can be prescient.
   591  		if !f.hfull && dist > f.hp {
   592  			f.err = CorruptInputError(f.roffset)
   593  			return
   594  		}
   595  
   596  		f.copyLen, f.copyDist = length, dist
   597  		if f.copyHist() {
   598  			return
   599  		}
   600  	}
   601  }
   602  
   603  // copyHist copies f.copyLen bytes from f.hist (f.copyDist bytes ago) to itself.
   604  // It reports whether the f.hist buffer is full.
   605  func (f *decompressor) copyHist() bool {
   606  	p := f.hp - f.copyDist
   607  	if p < 0 {
   608  		p += len(f.hist)
   609  	}
   610  	for f.copyLen > 0 {
   611  		n := f.copyLen
   612  		if x := len(f.hist) - f.hp; n > x {
   613  			n = x
   614  		}
   615  		if x := len(f.hist) - p; n > x {
   616  			n = x
   617  		}
   618  		forwardCopy(f.hist[:], f.hp, p, n)
   619  		p += n
   620  		f.hp += n
   621  		f.copyLen -= n
   622  		if f.hp == len(f.hist) {
   623  			// After flush continue copying out of history.
   624  			f.flush((*decompressor).copyHuff)
   625  			return true
   626  		}
   627  		if p == len(f.hist) {
   628  			p = 0
   629  		}
   630  	}
   631  	return false
   632  }
   633  
   634  func (f *decompressor) copyHuff() {
   635  	if f.copyHist() {
   636  		return
   637  	}
   638  	f.huffmanBlock()
   639  }
   640  
   641  // Copy a single uncompressed data block from input to output.
   642  func (f *decompressor) dataBlock() {
   643  	// Uncompressed.
   644  	// Discard current half-byte.
   645  	f.nb = 0
   646  	f.b = 0
   647  
   648  	// Length then ones-complement of length.
   649  	nr, err := io.ReadFull(f.r, f.buf[0:4])
   650  	f.roffset += int64(nr)
   651  	if err != nil {
   652  		if err == io.EOF {
   653  			err = io.ErrUnexpectedEOF
   654  		}
   655  		f.err = err
   656  		return
   657  	}
   658  	n := int(f.buf[0]) | int(f.buf[1])<<8
   659  	nn := int(f.buf[2]) | int(f.buf[3])<<8
   660  	if uint16(nn) != uint16(^n) {
   661  		f.err = CorruptInputError(f.roffset)
   662  		return
   663  	}
   664  
   665  	if n == 0 {
   666  		// 0-length block means sync
   667  		f.flush((*decompressor).nextBlock)
   668  		return
   669  	}
   670  
   671  	f.copyLen = n
   672  	f.copyData()
   673  }
   674  
   675  // copyData copies f.copyLen bytes from the underlying reader into f.hist.
   676  // It pauses for reads when f.hist is full.
   677  func (f *decompressor) copyData() {
   678  	n := f.copyLen
   679  	for n > 0 {
   680  		m := len(f.hist) - f.hp
   681  		if m > n {
   682  			m = n
   683  		}
   684  		m, err := io.ReadFull(f.r, f.hist[f.hp:f.hp+m])
   685  		f.roffset += int64(m)
   686  		if err != nil {
   687  			if err == io.EOF {
   688  				err = io.ErrUnexpectedEOF
   689  			}
   690  			f.err = err
   691  			return
   692  		}
   693  		n -= m
   694  		f.hp += m
   695  		if f.hp == len(f.hist) {
   696  			f.copyLen = n
   697  			f.flush((*decompressor).copyData)
   698  			return
   699  		}
   700  	}
   701  	f.step = (*decompressor).nextBlock
   702  }
   703  
   704  func (f *decompressor) setDict(dict []byte) {
   705  	if len(dict) > len(f.hist) {
   706  		// Will only remember the tail.
   707  		dict = dict[len(dict)-len(f.hist):]
   708  	}
   709  
   710  	f.hp = copy(f.hist[:], dict)
   711  	if f.hp == len(f.hist) {
   712  		f.hp = 0
   713  		f.hfull = true
   714  	}
   715  	f.hw = f.hp
   716  }
   717  
   718  func (f *decompressor) moreBits() error {
   719  	c, err := f.r.ReadByte()
   720  	if err != nil {
   721  		if err == io.EOF {
   722  			err = io.ErrUnexpectedEOF
   723  		}
   724  		return err
   725  	}
   726  	f.roffset++
   727  	f.b |= uint32(c) << f.nb
   728  	f.nb += 8
   729  	return nil
   730  }
   731  
   732  // Read the next Huffman-encoded symbol from f according to h.
   733  func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) {
   734  	// Since a huffmanDecoder can be empty or be composed of a degenerate tree
   735  	// with single element, huffSym must error on these two edge cases. In both
   736  	// cases, the chunks slice will be 0 for the invalid sequence, leading it
   737  	// satisfy the n == 0 check below.
   738  	n := uint(h.min)
   739  	for {
   740  		for f.nb < n {
   741  			if err := f.moreBits(); err != nil {
   742  				return 0, err
   743  			}
   744  		}
   745  		chunk := h.chunks[f.b&(huffmanNumChunks-1)]
   746  		n = uint(chunk & huffmanCountMask)
   747  		if n > huffmanChunkBits {
   748  			chunk = h.links[chunk>>huffmanValueShift][(f.b>>huffmanChunkBits)&h.linkMask]
   749  			n = uint(chunk & huffmanCountMask)
   750  		}
   751  		if n <= f.nb {
   752  			if n == 0 {
   753  				f.err = CorruptInputError(f.roffset)
   754  				return 0, f.err
   755  			}
   756  			f.b >>= n
   757  			f.nb -= n
   758  			return int(chunk >> huffmanValueShift), nil
   759  		}
   760  	}
   761  }
   762  
   763  // Flush any buffered output to the underlying writer.
   764  func (f *decompressor) flush(step func(*decompressor)) {
   765  	f.toRead = f.hist[f.hw:f.hp]
   766  	f.woffset += int64(f.hp - f.hw)
   767  	f.hw = f.hp
   768  	if f.hp == len(f.hist) {
   769  		f.hp = 0
   770  		f.hw = 0
   771  		f.hfull = true
   772  	}
   773  	f.step = step
   774  }
   775  
   776  func makeReader(r io.Reader) Reader {
   777  	if rr, ok := r.(Reader); ok {
   778  		return rr
   779  	}
   780  	return bufio.NewReader(r)
   781  }
   782  
   783  func fixedHuffmanDecoderInit() {
   784  	fixedOnce.Do(func() {
   785  		// These come from the RFC section 3.2.6.
   786  		var bits [288]int
   787  		for i := 0; i < 144; i++ {
   788  			bits[i] = 8
   789  		}
   790  		for i := 144; i < 256; i++ {
   791  			bits[i] = 9
   792  		}
   793  		for i := 256; i < 280; i++ {
   794  			bits[i] = 7
   795  		}
   796  		for i := 280; i < 288; i++ {
   797  			bits[i] = 8
   798  		}
   799  		fixedHuffmanDecoder.init(bits[:])
   800  	})
   801  }
   802  
   803  func (f *decompressor) Reset(r io.Reader, dict []byte) error {
   804  	*f = decompressor{
   805  		r:        makeReader(r),
   806  		bits:     f.bits,
   807  		codebits: f.codebits,
   808  		hist:     f.hist,
   809  		step:     (*decompressor).nextBlock,
   810  	}
   811  	if dict != nil {
   812  		f.setDict(dict)
   813  	}
   814  	return nil
   815  }
   816  
   817  // NewReader returns a new ReadCloser that can be used
   818  // to read the uncompressed version of r.
   819  // If r does not also implement io.ByteReader,
   820  // the decompressor may read more data than necessary from r.
   821  // It is the caller's responsibility to call Close on the ReadCloser
   822  // when finished reading.
   823  //
   824  // The ReadCloser returned by NewReader also implements Resetter.
   825  func NewReader(r io.Reader) io.ReadCloser {
   826  	fixedHuffmanDecoderInit()
   827  
   828  	var f decompressor
   829  	f.r = makeReader(r)
   830  	f.hist = new([maxHist]byte)
   831  	f.bits = new([maxNumLit + maxNumDist]int)
   832  	f.codebits = new([numCodes]int)
   833  	f.step = (*decompressor).nextBlock
   834  	return &f
   835  }
   836  
   837  // NewReaderDict is like NewReader but initializes the reader
   838  // with a preset dictionary.  The returned Reader behaves as if
   839  // the uncompressed data stream started with the given dictionary,
   840  // which has already been read.  NewReaderDict is typically used
   841  // to read data compressed by NewWriterDict.
   842  //
   843  // The ReadCloser returned by NewReader also implements Resetter.
   844  func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser {
   845  	fixedHuffmanDecoderInit()
   846  
   847  	var f decompressor
   848  	f.r = makeReader(r)
   849  	f.hist = new([maxHist]byte)
   850  	f.bits = new([maxNumLit + maxNumDist]int)
   851  	f.codebits = new([numCodes]int)
   852  	f.step = (*decompressor).nextBlock
   853  	f.setDict(dict)
   854  	return &f
   855  }