| 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 |
"compress/flate" |
| 13 |
"fmt" |
| 14 |
"io" |
| 15 |
"math/bits" |
| 16 |
"sync" |
| 17 |
|
| 18 |
"github.com/klauspost/compress/internal/regmask" |
| 19 |
) |
| 20 |
|
| 21 |
const ( |
| 22 |
maxCodeLen = 16 // max length of Huffman code |
| 23 |
maxCodeLenMask = 15 // mask for max length of Huffman code |
| 24 |
// The next three numbers come from the RFC section 3.2.7, with the |
| 25 |
// additional proviso in section 3.2.5 which implies that distance codes |
| 26 |
// 30 and 31 should never occur in compressed data. |
| 27 |
maxNumLit = 286 |
| 28 |
maxNumDist = 30 |
| 29 |
numCodes = 19 // number of codes in Huffman meta-code |
| 30 |
|
| 31 |
debugDecode = false |
| 32 |
) |
| 33 |
|
| 34 |
// Value of length - 3 and extra bits. |
| 35 |
type lengthExtra struct { |
| 36 |
length, extra uint8 |
| 37 |
} |
| 38 |
|
| 39 |
var decCodeToLen = [32]lengthExtra{{length: 0x0, extra: 0x0}, {length: 0x1, extra: 0x0}, {length: 0x2, extra: 0x0}, {length: 0x3, extra: 0x0}, {length: 0x4, extra: 0x0}, {length: 0x5, extra: 0x0}, {length: 0x6, extra: 0x0}, {length: 0x7, extra: 0x0}, {length: 0x8, extra: 0x1}, {length: 0xa, extra: 0x1}, {length: 0xc, extra: 0x1}, {length: 0xe, extra: 0x1}, {length: 0x10, extra: 0x2}, {length: 0x14, extra: 0x2}, {length: 0x18, extra: 0x2}, {length: 0x1c, extra: 0x2}, {length: 0x20, extra: 0x3}, {length: 0x28, extra: 0x3}, {length: 0x30, extra: 0x3}, {length: 0x38, extra: 0x3}, {length: 0x40, extra: 0x4}, {length: 0x50, extra: 0x4}, {length: 0x60, extra: 0x4}, {length: 0x70, extra: 0x4}, {length: 0x80, extra: 0x5}, {length: 0xa0, extra: 0x5}, {length: 0xc0, extra: 0x5}, {length: 0xe0, extra: 0x5}, {length: 0xff, extra: 0x0}, {length: 0x0, extra: 0x0}, {length: 0x0, extra: 0x0}, {length: 0x0, extra: 0x0}} |
| 40 |
|
| 41 |
var bitMask32 = [32]uint32{ |
| 42 |
0, 1, 3, 7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF, |
| 43 |
0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, |
| 44 |
0x1ffff, 0x3ffff, 0x7FFFF, 0xfFFFF, 0x1fFFFF, 0x3fFFFF, 0x7fFFFF, 0xffFFFF, |
| 45 |
0x1ffFFFF, 0x3ffFFFF, 0x7ffFFFF, 0xfffFFFF, 0x1fffFFFF, 0x3fffFFFF, 0x7fffFFFF, |
| 46 |
} // up to 32 bits |
| 47 |
|
| 48 |
// Initialize the fixedHuffmanDecoder only once upon first use. |
| 49 |
var fixedOnce sync.Once |
| 50 |
var fixedHuffmanDecoder huffmanDecoder |
| 51 |
|
| 52 |
// A CorruptInputError reports the presence of corrupt input at a given offset. |
| 53 |
type CorruptInputError = flate.CorruptInputError |
| 54 |
|
| 55 |
// An InternalError reports an error in the flate code itself. |
| 56 |
type InternalError string |
| 57 |
|
| 58 |
func (e InternalError) Error() string { return "flate: internal error: " + string(e) } |
| 59 |
|
| 60 |
// A ReadError reports an error encountered while reading input. |
| 61 |
// |
| 62 |
// Deprecated: No longer returned. |
| 63 |
type ReadError = flate.ReadError |
| 64 |
|
| 65 |
// A WriteError reports an error encountered while writing output. |
| 66 |
// |
| 67 |
// Deprecated: No longer returned. |
| 68 |
type WriteError = flate.WriteError |
| 69 |
|
| 70 |
// Resetter resets a ReadCloser returned by NewReader or NewReaderDict to |
| 71 |
// to switch to a new underlying Reader. This permits reusing a ReadCloser |
| 72 |
// instead of allocating a new one. |
| 73 |
type Resetter interface { |
| 74 |
// Reset discards any buffered data and resets the Resetter as if it was |
| 75 |
// newly initialized with the given reader. |
| 76 |
Reset(r io.Reader, dict []byte) error |
| 77 |
} |
| 78 |
|
| 79 |
// The data structure for decoding Huffman tables is based on that of |
| 80 |
// zlib. There is a lookup table of a fixed bit width (huffmanChunkBits), |
| 81 |
// For codes smaller than the table width, there are multiple entries |
| 82 |
// (each combination of trailing bits has the same value). For codes |
| 83 |
// larger than the table width, the table contains a link to an overflow |
| 84 |
// table. The width of each entry in the link table is the maximum code |
| 85 |
// size minus the chunk width. |
| 86 |
// |
| 87 |
// Note that you can do a lookup in the table even without all bits |
| 88 |
// filled. Since the extra bits are zero, and the DEFLATE Huffman codes |
| 89 |
// have the property that shorter codes come before longer ones, the |
| 90 |
// bit length estimate in the result is a lower bound on the actual |
| 91 |
// number of bits. |
| 92 |
// |
| 93 |
// See the following: |
| 94 |
// http://www.gzip.org/algorithm.txt |
| 95 |
|
| 96 |
// chunk & 15 is number of bits |
| 97 |
// chunk >> 4 is value, including table link |
| 98 |
|
| 99 |
const ( |
| 100 |
huffmanChunkBits = 9 |
| 101 |
huffmanNumChunks = 1 << huffmanChunkBits |
| 102 |
huffmanCountMask = 15 |
| 103 |
huffmanValueShift = 4 |
| 104 |
) |
| 105 |
|
| 106 |
type huffmanDecoder struct { |
| 107 |
maxRead int // the maximum number of bits we can read and not overread |
| 108 |
chunks *[huffmanNumChunks]uint16 // chunks as described above |
| 109 |
links [][]uint16 // overflow links |
| 110 |
linkMask uint32 // mask the width of the link table |
| 111 |
} |
| 112 |
|
| 113 |
// Initialize Huffman decoding tables from array of code lengths. |
| 114 |
// Following this function, h is guaranteed to be initialized into a complete |
| 115 |
// tree (i.e., neither over-subscribed nor under-subscribed). The exception is a |
| 116 |
// degenerate case where the tree has only a single symbol with length 1. Empty |
| 117 |
// trees are permitted. |
| 118 |
func (h *huffmanDecoder) init(lengths []int) bool { |
| 119 |
// Sanity enables additional runtime tests during Huffman |
| 120 |
// table construction. It's intended to be used during |
| 121 |
// development to supplement the currently ad-hoc unit tests. |
| 122 |
const sanity = false |
| 123 |
|
| 124 |
if h.chunks == nil { |
| 125 |
h.chunks = new([huffmanNumChunks]uint16) |
| 126 |
} |
| 127 |
|
| 128 |
if h.maxRead != 0 { |
| 129 |
*h = huffmanDecoder{chunks: h.chunks, links: h.links} |
| 130 |
} |
| 131 |
|
| 132 |
// Count number of codes of each length, |
| 133 |
// compute maxRead and max length. |
| 134 |
var count [maxCodeLen]int |
| 135 |
var min, max int |
| 136 |
for _, n := range lengths { |
| 137 |
if n == 0 { |
| 138 |
continue |
| 139 |
} |
| 140 |
if min == 0 || n < min { |
| 141 |
min = n |
| 142 |
} |
| 143 |
if n > max { |
| 144 |
max = n |
| 145 |
} |
| 146 |
count[n&maxCodeLenMask]++ |
| 147 |
} |
| 148 |
|
| 149 |
// Empty tree. The decompressor.huffSym function will fail later if the tree |
| 150 |
// is used. Technically, an empty tree is only valid for the HDIST tree and |
| 151 |
// not the HCLEN and HLIT tree. However, a stream with an empty HCLEN tree |
| 152 |
// is guaranteed to fail since it will attempt to use the tree to decode the |
| 153 |
// codes for the HLIT and HDIST trees. Similarly, an empty HLIT tree is |
| 154 |
// guaranteed to fail later since the compressed data section must be |
| 155 |
// composed of at least one symbol (the end-of-block marker). |
| 156 |
if max == 0 { |
| 157 |
return true |
| 158 |
} |
| 159 |
|
| 160 |
code := 0 |
| 161 |
var nextcode [maxCodeLen]int |
| 162 |
for i := min; i <= max; i++ { |
| 163 |
code <<= 1 |
| 164 |
nextcode[i&maxCodeLenMask] = code |
| 165 |
code += count[i&maxCodeLenMask] |
| 166 |
} |
| 167 |
|
| 168 |
// Check that the coding is complete (i.e., that we've |
| 169 |
// assigned all 2-to-the-max possible bit sequences). |
| 170 |
// Exception: To be compatible with zlib, we also need to |
| 171 |
// accept degenerate single-code codings. See also |
| 172 |
// TestDegenerateHuffmanCoding. |
| 173 |
if code != 1<<uint(max) && !(code == 1 && max == 1) { |
| 174 |
if debugDecode { |
| 175 |
fmt.Println("coding failed, code, max:", code, max, code == 1<<uint(max), code == 1 && max == 1, "(one should be true)") |
| 176 |
} |
| 177 |
return false |
| 178 |
} |
| 179 |
|
| 180 |
h.maxRead = min |
| 181 |
|
| 182 |
chunks := h.chunks[:] |
| 183 |
for i := range chunks { |
| 184 |
chunks[i] = 0 |
| 185 |
} |
| 186 |
|
| 187 |
if max > huffmanChunkBits { |
| 188 |
numLinks := 1 << (uint(max) - huffmanChunkBits) |
| 189 |
h.linkMask = uint32(numLinks - 1) |
| 190 |
|
| 191 |
// create link tables |
| 192 |
link := nextcode[huffmanChunkBits+1] >> 1 |
| 193 |
if cap(h.links) < huffmanNumChunks-link { |
| 194 |
h.links = make([][]uint16, huffmanNumChunks-link) |
| 195 |
} else { |
| 196 |
h.links = h.links[:huffmanNumChunks-link] |
| 197 |
} |
| 198 |
for j := uint(link); j < huffmanNumChunks; j++ { |
| 199 |
reverse := int(bits.Reverse16(uint16(j))) |
| 200 |
reverse >>= uint(16 - huffmanChunkBits) |
| 201 |
off := j - uint(link) |
| 202 |
if sanity && h.chunks[reverse] != 0 { |
| 203 |
panic("impossible: overwriting existing chunk") |
| 204 |
} |
| 205 |
h.chunks[reverse] = uint16(off<<huffmanValueShift | (huffmanChunkBits + 1)) |
| 206 |
if cap(h.links[off]) < numLinks { |
| 207 |
h.links[off] = make([]uint16, numLinks) |
| 208 |
} else { |
| 209 |
h.links[off] = h.links[off][:numLinks] |
| 210 |
} |
| 211 |
} |
| 212 |
} else { |
| 213 |
h.links = h.links[:0] |
| 214 |
} |
| 215 |
|
| 216 |
for i, n := range lengths { |
| 217 |
if n == 0 { |
| 218 |
continue |
| 219 |
} |
| 220 |
code := nextcode[n] |
| 221 |
nextcode[n]++ |
| 222 |
chunk := uint16(i<<huffmanValueShift | n) |
| 223 |
reverse := int(bits.Reverse16(uint16(code))) |
| 224 |
reverse >>= uint(16 - n) |
| 225 |
if n <= huffmanChunkBits { |
| 226 |
for off := reverse; off < len(h.chunks); off += 1 << uint(n) { |
| 227 |
// We should never need to overwrite |
| 228 |
// an existing chunk. Also, 0 is |
| 229 |
// never a valid chunk, because the |
| 230 |
// lower 4 "count" bits should be |
| 231 |
// between 1 and 15. |
| 232 |
if sanity && h.chunks[off] != 0 { |
| 233 |
panic("impossible: overwriting existing chunk") |
| 234 |
} |
| 235 |
h.chunks[off] = chunk |
| 236 |
} |
| 237 |
} else { |
| 238 |
j := reverse & (huffmanNumChunks - 1) |
| 239 |
if sanity && h.chunks[j]&huffmanCountMask != huffmanChunkBits+1 { |
| 240 |
// Longer codes should have been |
| 241 |
// associated with a link table above. |
| 242 |
panic("impossible: not an indirect chunk") |
| 243 |
} |
| 244 |
value := h.chunks[j] >> huffmanValueShift |
| 245 |
linktab := h.links[value] |
| 246 |
reverse >>= huffmanChunkBits |
| 247 |
for off := reverse; off < len(linktab); off += 1 << uint(n-huffmanChunkBits) { |
| 248 |
if sanity && linktab[off] != 0 { |
| 249 |
panic("impossible: overwriting existing chunk") |
| 250 |
} |
| 251 |
linktab[off] = chunk |
| 252 |
} |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
if sanity { |
| 257 |
// Above we've sanity checked that we never overwrote |
| 258 |
// an existing entry. Here we additionally check that |
| 259 |
// we filled the tables completely. |
| 260 |
for i, chunk := range h.chunks { |
| 261 |
if chunk == 0 { |
| 262 |
// As an exception, in the degenerate |
| 263 |
// single-code case, we allow odd |
| 264 |
// chunks to be missing. |
| 265 |
if code == 1 && i%2 == 1 { |
| 266 |
continue |
| 267 |
} |
| 268 |
panic("impossible: missing chunk") |
| 269 |
} |
| 270 |
} |
| 271 |
for _, linktab := range h.links { |
| 272 |
for _, chunk := range linktab { |
| 273 |
if chunk == 0 { |
| 274 |
panic("impossible: missing chunk") |
| 275 |
} |
| 276 |
} |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
return true |
| 281 |
} |
| 282 |
|
| 283 |
// Reader is the actual read interface needed by NewReader. |
| 284 |
// If the passed in io.Reader does not also have ReadByte, |
| 285 |
// the NewReader will introduce its own buffering. |
| 286 |
type Reader interface { |
| 287 |
io.Reader |
| 288 |
io.ByteReader |
| 289 |
} |
| 290 |
|
| 291 |
type step uint8 |
| 292 |
|
| 293 |
const ( |
| 294 |
copyData step = iota + 1 |
| 295 |
nextBlock |
| 296 |
huffmanBytesBuffer |
| 297 |
huffmanBytesReader |
| 298 |
huffmanBufioReader |
| 299 |
huffmanStringsReader |
| 300 |
huffmanGenericReader |
| 301 |
) |
| 302 |
|
| 303 |
// flushMode tells decompressor when to return data |
| 304 |
type flushMode uint8 |
| 305 |
|
| 306 |
const ( |
| 307 |
syncFlush flushMode = iota // return data after sync flush block |
| 308 |
partialFlush // return data after each block |
| 309 |
) |
| 310 |
|
| 311 |
// Decompress state. |
| 312 |
type decompressor struct { |
| 313 |
// Input source. |
| 314 |
r Reader |
| 315 |
roffset int64 |
| 316 |
|
| 317 |
// Huffman decoders for literal/length, distance. |
| 318 |
h1, h2 huffmanDecoder |
| 319 |
|
| 320 |
// Length arrays used to define Huffman codes. |
| 321 |
bits *[maxNumLit + maxNumDist]int |
| 322 |
codebits *[numCodes]int |
| 323 |
|
| 324 |
// Output history, buffer. |
| 325 |
dict dictDecoder |
| 326 |
|
| 327 |
// Next step in the decompression, |
| 328 |
// and decompression state. |
| 329 |
step step |
| 330 |
stepState int |
| 331 |
err error |
| 332 |
toRead []byte |
| 333 |
hl, hd *huffmanDecoder |
| 334 |
copyLen int |
| 335 |
copyDist int |
| 336 |
|
| 337 |
// Temporary buffer (avoids repeated allocation). |
| 338 |
buf [4]byte |
| 339 |
|
| 340 |
// Input bits, in top of b. |
| 341 |
b uint32 |
| 342 |
|
| 343 |
nb uint |
| 344 |
final bool |
| 345 |
|
| 346 |
flushMode flushMode |
| 347 |
cb func(InflateCheckpoint) |
| 348 |
cp InflateCheckpoint |
| 349 |
hasCP bool // WithResumeFrom was supplied |
| 350 |
uncOffset int64 // baseline uncompressed offset (from a resume checkpoint) |
| 351 |
cpBuf []byte |
| 352 |
} |
| 353 |
|
| 354 |
func (f *decompressor) nextBlock() { |
| 355 |
for f.nb < 1+2 { |
| 356 |
if f.err = f.moreBits(); f.err != nil { |
| 357 |
return |
| 358 |
} |
| 359 |
} |
| 360 |
f.final = f.b&1 == 1 |
| 361 |
f.b >>= 1 |
| 362 |
typ := f.b & 3 |
| 363 |
f.b >>= 2 |
| 364 |
f.nb -= 1 + 2 |
| 365 |
switch typ { |
| 366 |
case 0: |
| 367 |
f.dataBlock() |
| 368 |
if debugDecode { |
| 369 |
fmt.Println("stored block") |
| 370 |
} |
| 371 |
case 1: |
| 372 |
// compressed, fixed Huffman tables |
| 373 |
f.hl = &fixedHuffmanDecoder |
| 374 |
f.hd = nil |
| 375 |
f.huffmanBlockDecoder() |
| 376 |
if debugDecode { |
| 377 |
fmt.Println("predefinied huffman block") |
| 378 |
} |
| 379 |
case 2: |
| 380 |
// compressed, dynamic Huffman tables |
| 381 |
if f.err = f.readHuffman(); f.err != nil { |
| 382 |
break |
| 383 |
} |
| 384 |
f.hl = &f.h1 |
| 385 |
f.hd = &f.h2 |
| 386 |
f.huffmanBlockDecoder() |
| 387 |
if debugDecode { |
| 388 |
fmt.Println("dynamic huffman block") |
| 389 |
} |
| 390 |
default: |
| 391 |
// 3 is reserved. |
| 392 |
if debugDecode { |
| 393 |
fmt.Println("reserved data block encountered") |
| 394 |
} |
| 395 |
f.err = CorruptInputError(f.roffset) |
| 396 |
} |
| 397 |
} |
| 398 |
|
| 399 |
func (f *decompressor) Read(b []byte) (int, error) { |
| 400 |
for { |
| 401 |
if len(f.toRead) > 0 { |
| 402 |
n := copy(b, f.toRead) |
| 403 |
f.toRead = f.toRead[n:] |
| 404 |
if len(f.toRead) == 0 { |
| 405 |
return n, f.err |
| 406 |
} |
| 407 |
return n, nil |
| 408 |
} |
| 409 |
if f.err != nil { |
| 410 |
return 0, f.err |
| 411 |
} |
| 412 |
|
| 413 |
f.doStep() |
| 414 |
|
| 415 |
if f.err != nil && len(f.toRead) == 0 { |
| 416 |
f.toRead = f.dict.readFlush() // Flush what's left in case of error |
| 417 |
} |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
// WriteTo implements the io.WriteTo interface for io.Copy and friends. |
| 422 |
func (f *decompressor) WriteTo(w io.Writer) (int64, error) { |
| 423 |
total := int64(0) |
| 424 |
flushed := false |
| 425 |
for { |
| 426 |
if len(f.toRead) > 0 { |
| 427 |
n, err := w.Write(f.toRead) |
| 428 |
total += int64(n) |
| 429 |
if err != nil { |
| 430 |
f.err = err |
| 431 |
return total, err |
| 432 |
} |
| 433 |
if n != len(f.toRead) { |
| 434 |
return total, io.ErrShortWrite |
| 435 |
} |
| 436 |
f.toRead = f.toRead[:0] |
| 437 |
} |
| 438 |
if f.err != nil && flushed { |
| 439 |
if f.err == io.EOF { |
| 440 |
return total, nil |
| 441 |
} |
| 442 |
return total, f.err |
| 443 |
} |
| 444 |
if f.err == nil { |
| 445 |
f.doStep() |
| 446 |
} |
| 447 |
if len(f.toRead) == 0 && f.err != nil && !flushed { |
| 448 |
f.toRead = f.dict.readFlush() // Flush what's left in case of error |
| 449 |
flushed = true |
| 450 |
} |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
func (f *decompressor) Close() error { |
| 455 |
if f.err == io.EOF { |
| 456 |
return nil |
| 457 |
} |
| 458 |
return f.err |
| 459 |
} |
| 460 |
|
| 461 |
// RFC 1951 section 3.2.7. |
| 462 |
// Compression with dynamic Huffman codes |
| 463 |
|
| 464 |
var codeOrder = [...]int{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15} |
| 465 |
|
| 466 |
func (f *decompressor) readHuffman() error { |
| 467 |
// HLIT[5], HDIST[5], HCLEN[4]. |
| 468 |
for f.nb < 5+5+4 { |
| 469 |
if err := f.moreBits(); err != nil { |
| 470 |
return err |
| 471 |
} |
| 472 |
} |
| 473 |
nlit := int(f.b&0x1F) + 257 |
| 474 |
if nlit > maxNumLit { |
| 475 |
if debugDecode { |
| 476 |
fmt.Println("nlit > maxNumLit", nlit) |
| 477 |
} |
| 478 |
return CorruptInputError(f.roffset) |
| 479 |
} |
| 480 |
f.b >>= 5 |
| 481 |
ndist := int(f.b&0x1F) + 1 |
| 482 |
if ndist > maxNumDist { |
| 483 |
if debugDecode { |
| 484 |
fmt.Println("ndist > maxNumDist", ndist) |
| 485 |
} |
| 486 |
return CorruptInputError(f.roffset) |
| 487 |
} |
| 488 |
f.b >>= 5 |
| 489 |
nclen := int(f.b&0xF) + 4 |
| 490 |
// numCodes is 19, so nclen is always valid. |
| 491 |
f.b >>= 4 |
| 492 |
f.nb -= 5 + 5 + 4 |
| 493 |
|
| 494 |
// (HCLEN+4)*3 bits: code lengths in the magic codeOrder order. |
| 495 |
for i := range nclen { |
| 496 |
for f.nb < 3 { |
| 497 |
if err := f.moreBits(); err != nil { |
| 498 |
return err |
| 499 |
} |
| 500 |
} |
| 501 |
f.codebits[codeOrder[i]] = int(f.b & 0x7) |
| 502 |
f.b >>= 3 |
| 503 |
f.nb -= 3 |
| 504 |
} |
| 505 |
for i := nclen; i < len(codeOrder); i++ { |
| 506 |
f.codebits[codeOrder[i]] = 0 |
| 507 |
} |
| 508 |
if !f.h1.init(f.codebits[0:]) { |
| 509 |
if debugDecode { |
| 510 |
fmt.Println("init codebits failed") |
| 511 |
} |
| 512 |
return CorruptInputError(f.roffset) |
| 513 |
} |
| 514 |
|
| 515 |
// HLIT + 257 code lengths, HDIST + 1 code lengths, |
| 516 |
// using the code length Huffman code. |
| 517 |
for i, n := 0, nlit+ndist; i < n; { |
| 518 |
x, err := f.huffSym(&f.h1) |
| 519 |
if err != nil { |
| 520 |
return err |
| 521 |
} |
| 522 |
if x < 16 { |
| 523 |
// Actual length. |
| 524 |
f.bits[i] = x |
| 525 |
i++ |
| 526 |
continue |
| 527 |
} |
| 528 |
// Repeat previous length or zero. |
| 529 |
var rep int |
| 530 |
var nb uint |
| 531 |
var b int |
| 532 |
switch x { |
| 533 |
default: |
| 534 |
return InternalError("unexpected length code") |
| 535 |
case 16: |
| 536 |
rep = 3 |
| 537 |
nb = 2 |
| 538 |
if i == 0 { |
| 539 |
if debugDecode { |
| 540 |
fmt.Println("i==0") |
| 541 |
} |
| 542 |
return CorruptInputError(f.roffset) |
| 543 |
} |
| 544 |
b = f.bits[i-1] |
| 545 |
case 17: |
| 546 |
rep = 3 |
| 547 |
nb = 3 |
| 548 |
b = 0 |
| 549 |
case 18: |
| 550 |
rep = 11 |
| 551 |
nb = 7 |
| 552 |
b = 0 |
| 553 |
} |
| 554 |
for f.nb < nb { |
| 555 |
if err := f.moreBits(); err != nil { |
| 556 |
if debugDecode { |
| 557 |
fmt.Println("morebits:", err) |
| 558 |
} |
| 559 |
return err |
| 560 |
} |
| 561 |
} |
| 562 |
rep += int(f.b & uint32(1<<(nb®mask.Shift32ByUint)-1)) |
| 563 |
f.b >>= nb & regmask.Shift32ByUint |
| 564 |
f.nb -= nb |
| 565 |
if i+rep > n { |
| 566 |
if debugDecode { |
| 567 |
fmt.Println("i+rep > n", i, rep, n) |
| 568 |
} |
| 569 |
return CorruptInputError(f.roffset) |
| 570 |
} |
| 571 |
for j := 0; j < rep; j++ { |
| 572 |
f.bits[i] = b |
| 573 |
i++ |
| 574 |
} |
| 575 |
} |
| 576 |
|
| 577 |
if !f.h1.init(f.bits[0:nlit]) || !f.h2.init(f.bits[nlit:nlit+ndist]) { |
| 578 |
if debugDecode { |
| 579 |
fmt.Println("init2 failed") |
| 580 |
} |
| 581 |
return CorruptInputError(f.roffset) |
| 582 |
} |
| 583 |
|
| 584 |
// As an optimization, we can initialize the maxRead bits to read at a time |
| 585 |
// for the HLIT tree to the length of the EOB marker since we know that |
| 586 |
// every block must terminate with one. This preserves the property that |
| 587 |
// we never read any extra bytes after the end of the DEFLATE stream. |
| 588 |
if f.h1.maxRead < f.bits[endBlockMarker] { |
| 589 |
f.h1.maxRead = f.bits[endBlockMarker] |
| 590 |
} |
| 591 |
if !f.final { |
| 592 |
// If not the final block, the smallest block possible is |
| 593 |
// a predefined table, BTYPE=01, with a single EOB marker. |
| 594 |
// This will take up 3 + 7 bits. |
| 595 |
f.h1.maxRead += 10 |
| 596 |
} |
| 597 |
|
| 598 |
return nil |
| 599 |
} |
| 600 |
|
| 601 |
// Copy a single uncompressed data block from input to output. |
| 602 |
func (f *decompressor) dataBlock() { |
| 603 |
// Uncompressed. |
| 604 |
// Discard current half-byte. |
| 605 |
left := (f.nb) & 7 |
| 606 |
f.nb -= left |
| 607 |
f.b >>= left |
| 608 |
|
| 609 |
offBytes := f.nb >> 3 |
| 610 |
// Unfilled values will be overwritten. |
| 611 |
f.buf[0] = uint8(f.b) |
| 612 |
f.buf[1] = uint8(f.b >> 8) |
| 613 |
f.buf[2] = uint8(f.b >> 16) |
| 614 |
f.buf[3] = uint8(f.b >> 24) |
| 615 |
|
| 616 |
f.roffset += int64(offBytes) |
| 617 |
f.nb, f.b = 0, 0 |
| 618 |
|
| 619 |
// Length then ones-complement of length. |
| 620 |
nr, err := io.ReadFull(f.r, f.buf[offBytes:4]) |
| 621 |
f.roffset += int64(nr) |
| 622 |
if err != nil { |
| 623 |
f.err = noEOF(err) |
| 624 |
return |
| 625 |
} |
| 626 |
n := uint16(f.buf[0]) | uint16(f.buf[1])<<8 |
| 627 |
nn := uint16(f.buf[2]) | uint16(f.buf[3])<<8 |
| 628 |
if nn != ^n { |
| 629 |
if debugDecode { |
| 630 |
ncomp := ^n |
| 631 |
fmt.Println("uint16(nn) != uint16(^n)", nn, ncomp) |
| 632 |
} |
| 633 |
f.err = CorruptInputError(f.roffset) |
| 634 |
return |
| 635 |
} |
| 636 |
|
| 637 |
if n == 0 { |
| 638 |
if f.flushMode == syncFlush { |
| 639 |
f.toRead = f.dict.readFlush() |
| 640 |
} |
| 641 |
|
| 642 |
f.finishBlock() |
| 643 |
return |
| 644 |
} |
| 645 |
|
| 646 |
f.copyLen = int(n) |
| 647 |
f.copyData() |
| 648 |
} |
| 649 |
|
| 650 |
// copyData copies f.copyLen bytes from the underlying reader into f.hist. |
| 651 |
// It pauses for reads when f.hist is full. |
| 652 |
func (f *decompressor) copyData() { |
| 653 |
buf := f.dict.writeSlice() |
| 654 |
if len(buf) > f.copyLen { |
| 655 |
buf = buf[:f.copyLen] |
| 656 |
} |
| 657 |
|
| 658 |
cnt, err := io.ReadFull(f.r, buf) |
| 659 |
f.roffset += int64(cnt) |
| 660 |
f.copyLen -= cnt |
| 661 |
f.dict.writeMark(cnt) |
| 662 |
if err != nil { |
| 663 |
f.err = noEOF(err) |
| 664 |
return |
| 665 |
} |
| 666 |
|
| 667 |
if f.dict.availWrite() == 0 || f.copyLen > 0 { |
| 668 |
f.toRead = f.dict.readFlush() |
| 669 |
f.step = copyData |
| 670 |
return |
| 671 |
} |
| 672 |
f.finishBlock() |
| 673 |
} |
| 674 |
|
| 675 |
func (f *decompressor) finishBlock() { |
| 676 |
if f.final { |
| 677 |
if f.dict.availRead() > 0 { |
| 678 |
f.toRead = f.dict.readFlush() |
| 679 |
} |
| 680 |
|
| 681 |
f.err = io.EOF |
| 682 |
} else if f.flushMode == partialFlush && f.dict.availRead() > 0 { |
| 683 |
f.toRead = f.dict.readFlush() |
| 684 |
} |
| 685 |
|
| 686 |
if f.cb != nil { |
| 687 |
bitPos := f.roffset*8 - int64(f.nb) |
| 688 |
f.cpBuf = f.dict.appendWindow(f.cpBuf[:0]) |
| 689 |
f.cb(InflateCheckpoint{ |
| 690 |
UncompressedOffset: f.uncOffset + f.dict.decoded(), |
| 691 |
CompressedOffset: bitPos / 8, |
| 692 |
Final: f.final, |
| 693 |
BitOffset: uint8(bitPos & 7), |
| 694 |
Window: f.cpBuf, |
| 695 |
}) |
| 696 |
} |
| 697 |
|
| 698 |
f.step = nextBlock |
| 699 |
} |
| 700 |
|
| 701 |
func (f *decompressor) doStep() { |
| 702 |
switch f.step { |
| 703 |
case copyData: |
| 704 |
f.copyData() |
| 705 |
case nextBlock: |
| 706 |
f.nextBlock() |
| 707 |
case huffmanBytesBuffer: |
| 708 |
f.huffmanBytesBuffer() |
| 709 |
case huffmanBytesReader: |
| 710 |
f.huffmanBytesReader() |
| 711 |
case huffmanBufioReader: |
| 712 |
f.huffmanBufioReader() |
| 713 |
case huffmanStringsReader: |
| 714 |
f.huffmanStringsReader() |
| 715 |
case huffmanGenericReader: |
| 716 |
f.huffmanGenericReader() |
| 717 |
default: |
| 718 |
panic("BUG: unexpected step state") |
| 719 |
} |
| 720 |
} |
| 721 |
|
| 722 |
// noEOF returns err, unless err == io.EOF, in which case it returns io.ErrUnexpectedEOF. |
| 723 |
func noEOF(e error) error { |
| 724 |
if e == io.EOF { |
| 725 |
return io.ErrUnexpectedEOF |
| 726 |
} |
| 727 |
return e |
| 728 |
} |
| 729 |
|
| 730 |
func (f *decompressor) moreBits() error { |
| 731 |
c, err := f.r.ReadByte() |
| 732 |
if err != nil { |
| 733 |
return noEOF(err) |
| 734 |
} |
| 735 |
f.roffset++ |
| 736 |
f.b |= uint32(c) << (f.nb & regmask.Shift32ByUint) |
| 737 |
f.nb += 8 |
| 738 |
return nil |
| 739 |
} |
| 740 |
|
| 741 |
// Read the next Huffman-encoded symbol from f according to h. |
| 742 |
func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) { |
| 743 |
// Since a huffmanDecoder can be empty or be composed of a degenerate tree |
| 744 |
// with single element, huffSym must error on these two edge cases. In both |
| 745 |
// cases, the chunks slice will be 0 for the invalid sequence, leading it |
| 746 |
// satisfy the n == 0 check below. |
| 747 |
n := uint(h.maxRead) |
| 748 |
// Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, |
| 749 |
// but is smart enough to keep local variables in registers, so use nb and b, |
| 750 |
// inline call to moreBits and reassign b,nb back to f on return. |
| 751 |
nb, b := f.nb, f.b |
| 752 |
for { |
| 753 |
for nb < n { |
| 754 |
c, err := f.r.ReadByte() |
| 755 |
if err != nil { |
| 756 |
f.b = b |
| 757 |
f.nb = nb |
| 758 |
return 0, noEOF(err) |
| 759 |
} |
| 760 |
f.roffset++ |
| 761 |
b |= uint32(c) << (nb & regmask.Shift32ByUint) |
| 762 |
nb += 8 |
| 763 |
} |
| 764 |
chunk := h.chunks[b&(huffmanNumChunks-1)] |
| 765 |
n = uint(chunk & huffmanCountMask) |
| 766 |
if n > huffmanChunkBits { |
| 767 |
chunk = h.links[chunk>>huffmanValueShift][(b>>huffmanChunkBits)&h.linkMask] |
| 768 |
n = uint(chunk & huffmanCountMask) |
| 769 |
} |
| 770 |
if n <= nb { |
| 771 |
if n == 0 { |
| 772 |
f.b = b |
| 773 |
f.nb = nb |
| 774 |
if debugDecode { |
| 775 |
fmt.Println("huffsym: n==0") |
| 776 |
} |
| 777 |
f.err = CorruptInputError(f.roffset) |
| 778 |
return 0, f.err |
| 779 |
} |
| 780 |
f.b = b >> (n & regmask.Shift32ByUint) |
| 781 |
f.nb = nb - n |
| 782 |
return int(chunk >> huffmanValueShift), nil |
| 783 |
} |
| 784 |
} |
| 785 |
} |
| 786 |
|
| 787 |
func makeReader(r io.Reader) Reader { |
| 788 |
if rr, ok := r.(Reader); ok { |
| 789 |
return rr |
| 790 |
} |
| 791 |
return bufio.NewReader(r) |
| 792 |
} |
| 793 |
|
| 794 |
func fixedHuffmanDecoderInit() { |
| 795 |
fixedOnce.Do(func() { |
| 796 |
// These come from the RFC section 3.2.6. |
| 797 |
var bits [288]int |
| 798 |
for i := range 144 { |
| 799 |
bits[i] = 8 |
| 800 |
} |
| 801 |
for i := 144; i < 256; i++ { |
| 802 |
bits[i] = 9 |
| 803 |
} |
| 804 |
for i := 256; i < 280; i++ { |
| 805 |
bits[i] = 7 |
| 806 |
} |
| 807 |
for i := 280; i < 288; i++ { |
| 808 |
bits[i] = 8 |
| 809 |
} |
| 810 |
fixedHuffmanDecoder.init(bits[:]) |
| 811 |
}) |
| 812 |
} |
| 813 |
|
| 814 |
func (f *decompressor) Reset(r io.Reader, dict []byte) error { |
| 815 |
*f = decompressor{ |
| 816 |
r: makeReader(r), |
| 817 |
bits: f.bits, |
| 818 |
codebits: f.codebits, |
| 819 |
h1: f.h1, |
| 820 |
h2: f.h2, |
| 821 |
dict: f.dict, |
| 822 |
step: nextBlock, |
| 823 |
} |
| 824 |
f.dict.init(maxMatchOffset, dict) |
| 825 |
return nil |
| 826 |
} |
| 827 |
|
| 828 |
// ResetCP will adjust the input to the provided checkpoint. |
| 829 |
// It is assumed the input stream is forwarded to cp.CompressedOffset. |
| 830 |
func (f *decompressor) ResetCP(r io.Reader, cp InflateCheckpoint) error { |
| 831 |
*f = decompressor{ |
| 832 |
r: makeReader(r), |
| 833 |
bits: f.bits, |
| 834 |
codebits: f.codebits, |
| 835 |
h1: f.h1, |
| 836 |
h2: f.h2, |
| 837 |
dict: f.dict, |
| 838 |
step: nextBlock, |
| 839 |
cpBuf: f.cpBuf, |
| 840 |
} |
| 841 |
return f.applyCP(cp) |
| 842 |
} |
| 843 |
|
| 844 |
// applyCP seeds the decompressor state from a resume checkpoint: |
| 845 |
// loads the sliding window, sets the absolute compressed/uncompressed |
| 846 |
// offsets, and skips cp.BitOffset bits into the first input byte so |
| 847 |
// the next decode aligns with the start of a deflate block. |
| 848 |
func (f *decompressor) applyCP(cp InflateCheckpoint) error { |
| 849 |
f.dict.init(maxMatchOffset, cp.Window) |
| 850 |
f.roffset = cp.CompressedOffset |
| 851 |
f.uncOffset = cp.UncompressedOffset |
| 852 |
f.final = cp.Final |
| 853 |
f.b = 0 |
| 854 |
f.nb = 0 |
| 855 |
if cp.BitOffset > 0 { |
| 856 |
c, err := f.r.ReadByte() |
| 857 |
if err != nil { |
| 858 |
return noEOF(err) |
| 859 |
} |
| 860 |
f.roffset++ |
| 861 |
f.b = uint32(c) >> cp.BitOffset |
| 862 |
f.nb = 8 - uint(cp.BitOffset) |
| 863 |
} |
| 864 |
return nil |
| 865 |
} |
| 866 |
|
| 867 |
type ReaderOpt func(*decompressor) |
| 868 |
|
| 869 |
// WithPartialBlock tells decompressor to return after each block, |
| 870 |
// so it can read data written with partial flush |
| 871 |
func WithPartialBlock() ReaderOpt { |
| 872 |
return func(f *decompressor) { |
| 873 |
f.flushMode = partialFlush |
| 874 |
} |
| 875 |
} |
| 876 |
|
| 877 |
// WithDict initializes the reader with a preset dictionary |
| 878 |
func WithDict(dict []byte) ReaderOpt { |
| 879 |
return func(f *decompressor) { |
| 880 |
f.dict.init(maxMatchOffset, dict) |
| 881 |
} |
| 882 |
} |
| 883 |
|
| 884 |
// InflateCheckpoint provides a resumable checkpoint for inflate. |
| 885 |
type InflateCheckpoint struct { |
| 886 |
UncompressedOffset int64 // Byte offset in the decompressed stream |
| 887 |
CompressedOffset int64 // Byte offset in the compressed stream |
| 888 |
Final bool // True if this is the final block |
| 889 |
BitOffset uint8 // 0-7 bits |
| 890 |
Window []byte // 32KB sliding window dictionary |
| 891 |
} |
| 892 |
|
| 893 |
// WithEobCallback will call the provided function after each block |
| 894 |
// with the current gzip checkpoint. |
| 895 |
// After returning the provided window can no longer be referenced. |
| 896 |
// The callback will not be triggered after a block is marked "final". |
| 897 |
// The callback is not retained after Reset. |
| 898 |
func WithEobCallback(cb func(InflateCheckpoint)) ReaderOpt { |
| 899 |
return func(f *decompressor) { |
| 900 |
f.cb = cb |
| 901 |
} |
| 902 |
} |
| 903 |
|
| 904 |
// WithResumeFrom will adjust the input to the provided checkpoint. |
| 905 |
// It is assumed the input stream is forwarded to the provided offset. |
| 906 |
// The checkpoint is removed when Reset is called. |
| 907 |
func WithResumeFrom(cp InflateCheckpoint) ReaderOpt { |
| 908 |
return func(f *decompressor) { |
| 909 |
f.cp = cp |
| 910 |
f.hasCP = true |
| 911 |
} |
| 912 |
} |
| 913 |
|
| 914 |
// NewReaderOpts returns new reader with provided options |
| 915 |
func NewReaderOpts(r io.Reader, opts ...ReaderOpt) io.ReadCloser { |
| 916 |
fixedHuffmanDecoderInit() |
| 917 |
|
| 918 |
var f decompressor |
| 919 |
f.r = makeReader(r) |
| 920 |
f.bits = new([maxNumLit + maxNumDist]int) |
| 921 |
f.codebits = new([numCodes]int) |
| 922 |
f.step = nextBlock |
| 923 |
f.dict.init(maxMatchOffset, nil) |
| 924 |
|
| 925 |
for _, opt := range opts { |
| 926 |
opt(&f) |
| 927 |
} |
| 928 |
|
| 929 |
if f.hasCP { |
| 930 |
if err := f.applyCP(f.cp); err != nil { |
| 931 |
f.err = err |
| 932 |
} |
| 933 |
} |
| 934 |
|
| 935 |
return &f |
| 936 |
} |
| 937 |
|
| 938 |
// NewReader returns a new ReadCloser that can be used |
| 939 |
// to read the uncompressed version of r. |
| 940 |
// If r does not also implement io.ByteReader, |
| 941 |
// the decompressor may read more data than necessary from r. |
| 942 |
// It is the caller's responsibility to call Close on the ReadCloser |
| 943 |
// when finished reading. |
| 944 |
// |
| 945 |
// The ReadCloser returned by NewReader also implements Resetter. |
| 946 |
func NewReader(r io.Reader) io.ReadCloser { |
| 947 |
return NewReaderOpts(r) |
| 948 |
} |
| 949 |
|
| 950 |
// NewReaderDict is like NewReader but initializes the reader |
| 951 |
// with a preset dictionary. The returned Reader behaves as if |
| 952 |
// the uncompressed data stream started with the given dictionary, |
| 953 |
// which has already been read. NewReaderDict is typically used |
| 954 |
// to read data compressed by NewWriterDict. |
| 955 |
// |
| 956 |
// The ReadCloser returned by NewReader also implements Resetter. |
| 957 |
func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser { |
| 958 |
return NewReaderOpts(r, WithDict(dict)) |
| 959 |
} |