| 1 |
// Copyright 2009 The Go Authors. All rights reserved. |
| 2 |
// Copyright (c) 2015 Klaus Post |
| 3 |
// Use of this source code is governed by a BSD-style |
| 4 |
// license that can be found in the LICENSE file. |
| 5 |
|
| 6 |
package flate |
| 7 |
|
| 8 |
import ( |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
"math" |
| 13 |
|
| 14 |
"github.com/klauspost/compress/internal/le" |
| 15 |
) |
| 16 |
|
| 17 |
const ( |
| 18 |
NoCompression = 0 |
| 19 |
BestSpeed = 1 |
| 20 |
BestCompression = 9 |
| 21 |
DefaultCompression = -1 |
| 22 |
|
| 23 |
// HuffmanOnly disables Lempel-Ziv match searching and only performs Huffman |
| 24 |
// entropy encoding. This mode is useful in compressing data that has |
| 25 |
// already been compressed with an LZ style algorithm (e.g. Snappy or LZ4) |
| 26 |
// that lacks an entropy encoder. Compression gains are achieved when |
| 27 |
// certain bytes in the input stream occur more frequently than others. |
| 28 |
// |
| 29 |
// Note that HuffmanOnly produces a compressed output that is |
| 30 |
// RFC 1951 compliant. That is, any valid DEFLATE decompressor will |
| 31 |
// continue to be able to decompress this output. |
| 32 |
HuffmanOnly = -2 |
| 33 |
ConstantCompression = HuffmanOnly // compatibility alias. |
| 34 |
|
| 35 |
logWindowSize = 15 |
| 36 |
windowSize = 1 << logWindowSize |
| 37 |
windowMask = windowSize - 1 |
| 38 |
logMaxOffsetSize = 15 // Standard DEFLATE |
| 39 |
minMatchLength = 4 // The smallest match that the compressor looks for |
| 40 |
maxMatchLength = 258 // The longest match for the compressor |
| 41 |
minOffsetSize = 1 // The shortest offset that makes any sense |
| 42 |
|
| 43 |
// The maximum number of tokens we will encode at the time. |
| 44 |
// Smaller sizes usually creates less optimal blocks. |
| 45 |
// Bigger can make context switching slow. |
| 46 |
// We use this for levels 7-9, so we make it big. |
| 47 |
maxFlateBlockTokens = 1 << 15 |
| 48 |
maxStoreBlockSize = 65535 |
| 49 |
hashBits = 17 // After 17 performance degrades |
| 50 |
hashSize = 1 << hashBits |
| 51 |
hashMask = (1 << hashBits) - 1 |
| 52 |
hashShift = (hashBits + minMatchLength - 1) / minMatchLength |
| 53 |
maxHashOffset = 1 << 28 |
| 54 |
|
| 55 |
skipNever = math.MaxInt32 |
| 56 |
|
| 57 |
debugDeflate = false |
| 58 |
) |
| 59 |
|
| 60 |
type compressionLevel struct { |
| 61 |
good, lazy, nice, chain, fastSkipHashing, level int |
| 62 |
} |
| 63 |
|
| 64 |
// Compression levels have been rebalanced from zlib deflate defaults |
| 65 |
// to give a bigger spread in speed and compression. |
| 66 |
// See https://blog.klauspost.com/rebalancing-deflate-compression-levels/ |
| 67 |
var levels = []compressionLevel{ |
| 68 |
{}, // 0 |
| 69 |
// Level 1-6 uses specialized algorithm - values not used |
| 70 |
{0, 0, 0, 0, 0, 1}, |
| 71 |
{0, 0, 0, 0, 0, 2}, |
| 72 |
{0, 0, 0, 0, 0, 3}, |
| 73 |
{0, 0, 0, 0, 0, 4}, |
| 74 |
{0, 0, 0, 0, 0, 5}, |
| 75 |
{0, 0, 0, 0, 0, 6}, |
| 76 |
// Levels 7-9 use increasingly more lazy matching |
| 77 |
// and increasingly stringent conditions for "good enough". |
| 78 |
{8, 12, 16, 24, skipNever, 7}, |
| 79 |
{16, 30, 40, 64, skipNever, 8}, |
| 80 |
{32, 258, 258, 1024, skipNever, 9}, |
| 81 |
} |
| 82 |
|
| 83 |
// advancedState contains state for the advanced levels, with bigger hash tables, etc. |
| 84 |
type advancedState struct { |
| 85 |
// deflate state |
| 86 |
length int |
| 87 |
offset int |
| 88 |
maxInsertIndex int |
| 89 |
chainHead int |
| 90 |
hashOffset int |
| 91 |
|
| 92 |
ii uint16 // position of last match, intended to overflow to reset. |
| 93 |
|
| 94 |
// input window: unprocessed data is window[index:windowEnd] |
| 95 |
index int |
| 96 |
hashMatch [maxMatchLength + minMatchLength]uint32 |
| 97 |
|
| 98 |
// Input hash chains |
| 99 |
// hashHead[hashValue] contains the largest inputIndex with the specified hash value |
| 100 |
// If hashHead[hashValue] is within the current window, then |
| 101 |
// hashPrev[hashHead[hashValue] & windowMask] contains the previous index |
| 102 |
// with the same hash value. |
| 103 |
hashHead [hashSize]uint32 |
| 104 |
hashPrev [windowSize]uint32 |
| 105 |
} |
| 106 |
|
| 107 |
type compressor struct { |
| 108 |
compressionLevel |
| 109 |
|
| 110 |
h *huffmanEncoder |
| 111 |
w *huffmanBitWriter |
| 112 |
|
| 113 |
// compression algorithm |
| 114 |
fill func(*compressor, []byte) int // copy data to window |
| 115 |
step func(*compressor) // process window |
| 116 |
|
| 117 |
window []byte |
| 118 |
windowEnd int |
| 119 |
blockStart int // window index where current tokens start |
| 120 |
err error |
| 121 |
|
| 122 |
// queued output tokens |
| 123 |
tokens tokens |
| 124 |
fast fastEnc |
| 125 |
state *advancedState |
| 126 |
|
| 127 |
sync bool // requesting flush |
| 128 |
byteAvailable bool // if true, still need to process window[index-1]. |
| 129 |
} |
| 130 |
|
| 131 |
func (d *compressor) fillDeflate(b []byte) int { |
| 132 |
s := d.state |
| 133 |
if s.index >= 2*windowSize-(minMatchLength+maxMatchLength) { |
| 134 |
// shift the window by windowSize |
| 135 |
//copy(d.window[:], d.window[windowSize:2*windowSize]) |
| 136 |
*(*[windowSize]byte)(d.window) = *(*[windowSize]byte)(d.window[windowSize:]) |
| 137 |
s.index -= windowSize |
| 138 |
d.windowEnd -= windowSize |
| 139 |
if d.blockStart >= windowSize { |
| 140 |
d.blockStart -= windowSize |
| 141 |
} else { |
| 142 |
d.blockStart = math.MaxInt32 |
| 143 |
} |
| 144 |
s.hashOffset += windowSize |
| 145 |
if s.hashOffset > maxHashOffset { |
| 146 |
delta := s.hashOffset - 1 |
| 147 |
s.hashOffset -= delta |
| 148 |
s.chainHead -= delta |
| 149 |
// Iterate over slices instead of arrays to avoid copying |
| 150 |
// the entire table onto the stack (Issue #18625). |
| 151 |
for i, v := range s.hashPrev[:] { |
| 152 |
if int(v) > delta { |
| 153 |
s.hashPrev[i] = uint32(int(v) - delta) |
| 154 |
} else { |
| 155 |
s.hashPrev[i] = 0 |
| 156 |
} |
| 157 |
} |
| 158 |
for i, v := range s.hashHead[:] { |
| 159 |
if int(v) > delta { |
| 160 |
s.hashHead[i] = uint32(int(v) - delta) |
| 161 |
} else { |
| 162 |
s.hashHead[i] = 0 |
| 163 |
} |
| 164 |
} |
| 165 |
} |
| 166 |
} |
| 167 |
n := copy(d.window[d.windowEnd:], b) |
| 168 |
d.windowEnd += n |
| 169 |
return n |
| 170 |
} |
| 171 |
|
| 172 |
func (d *compressor) writeBlock(tok *tokens, index int, eof bool) error { |
| 173 |
if index > 0 || eof { |
| 174 |
var window []byte |
| 175 |
if d.blockStart <= index { |
| 176 |
window = d.window[d.blockStart:index] |
| 177 |
} |
| 178 |
d.blockStart = index |
| 179 |
//d.w.writeBlock(tok, eof, window) |
| 180 |
d.w.writeBlockDynamic(tok, eof, window, d.sync) |
| 181 |
return d.w.err |
| 182 |
} |
| 183 |
return nil |
| 184 |
} |
| 185 |
|
| 186 |
// writeBlockSkip writes the current block and uses the number of tokens |
| 187 |
// to determine if the block should be stored on no matches, or |
| 188 |
// only huffman encoded. |
| 189 |
func (d *compressor) writeBlockSkip(tok *tokens, index int, eof bool) error { |
| 190 |
if index > 0 || eof { |
| 191 |
if d.blockStart <= index { |
| 192 |
window := d.window[d.blockStart:index] |
| 193 |
// If we removed less than a 64th of all literals |
| 194 |
// we huffman compress the block. |
| 195 |
if int(tok.n) > len(window)-int(tok.n>>6) { |
| 196 |
d.w.writeBlockHuff(eof, window, d.sync) |
| 197 |
} else { |
| 198 |
// Write a dynamic huffman block. |
| 199 |
d.w.writeBlockDynamic(tok, eof, window, d.sync) |
| 200 |
} |
| 201 |
} else { |
| 202 |
d.w.writeBlock(tok, eof, nil) |
| 203 |
} |
| 204 |
d.blockStart = index |
| 205 |
return d.w.err |
| 206 |
} |
| 207 |
return nil |
| 208 |
} |
| 209 |
|
| 210 |
// fillWindow will fill the current window with the supplied |
| 211 |
// dictionary and calculate all hashes. |
| 212 |
// This is much faster than doing a full encode. |
| 213 |
// Should only be used after a start/reset. |
| 214 |
func (d *compressor) fillWindow(b []byte) { |
| 215 |
// Do not fill window if we are in store-only or huffman mode. |
| 216 |
if d.level <= 0 && d.level > -MinCustomWindowSize { |
| 217 |
return |
| 218 |
} |
| 219 |
if d.fast != nil { |
| 220 |
// encode the last data, but discard the result |
| 221 |
if len(b) > maxMatchOffset { |
| 222 |
b = b[len(b)-maxMatchOffset:] |
| 223 |
} |
| 224 |
d.fast.Encode(&d.tokens, b) |
| 225 |
d.tokens.Reset() |
| 226 |
return |
| 227 |
} |
| 228 |
s := d.state |
| 229 |
// If we are given too much, cut it. |
| 230 |
if len(b) > windowSize { |
| 231 |
b = b[len(b)-windowSize:] |
| 232 |
} |
| 233 |
// Add all to window. |
| 234 |
n := copy(d.window[d.windowEnd:], b) |
| 235 |
|
| 236 |
// Calculate 256 hashes at the time (more L1 cache hits) |
| 237 |
loops := (n + 256 - minMatchLength) / 256 |
| 238 |
for j := range loops { |
| 239 |
startindex := j * 256 |
| 240 |
end := min(startindex+256+minMatchLength-1, n) |
| 241 |
tocheck := d.window[startindex:end] |
| 242 |
dstSize := len(tocheck) - minMatchLength + 1 |
| 243 |
|
| 244 |
if dstSize <= 0 { |
| 245 |
continue |
| 246 |
} |
| 247 |
|
| 248 |
dst := s.hashMatch[:dstSize] |
| 249 |
bulkHash4(tocheck, dst) |
| 250 |
var newH uint32 |
| 251 |
for i, val := range dst { |
| 252 |
di := i + startindex |
| 253 |
newH = val & hashMask |
| 254 |
// Get previous value with the same hash. |
| 255 |
// Our chain should point to the previous value. |
| 256 |
s.hashPrev[di&windowMask] = s.hashHead[newH] |
| 257 |
// Set the head of the hash chain to us. |
| 258 |
s.hashHead[newH] = uint32(di + s.hashOffset) |
| 259 |
} |
| 260 |
} |
| 261 |
// Update window information. |
| 262 |
d.windowEnd += n |
| 263 |
d.blockStart = d.windowEnd |
| 264 |
s.index = n |
| 265 |
} |
| 266 |
|
| 267 |
// Try to find a match starting at index whose length is greater than prevSize. |
| 268 |
// We only look at chainCount possibilities before giving up. |
| 269 |
// pos = s.index, prevHead = s.chainHead-s.hashOffset, prevLength=minMatchLength-1, lookahead |
| 270 |
func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, offset int, ok bool) { |
| 271 |
minMatchLook := min(lookahead, maxMatchLength) |
| 272 |
|
| 273 |
win := d.window[0 : pos+minMatchLook] |
| 274 |
|
| 275 |
// We quit when we get a match that's at least nice long |
| 276 |
nice := min(d.nice, len(win)-pos) |
| 277 |
|
| 278 |
// If we've got a match that's good enough, only look in 1/4 the chain. |
| 279 |
tries := d.chain |
| 280 |
length = minMatchLength - 1 |
| 281 |
|
| 282 |
wEnd := win[pos+length] |
| 283 |
wPos := win[pos:] |
| 284 |
minIndex := max(pos-windowSize, 0) |
| 285 |
offset = 0 |
| 286 |
|
| 287 |
if d.chain < 100 { |
| 288 |
for i := prevHead; tries > 0; tries-- { |
| 289 |
if wEnd == win[i+length] { |
| 290 |
n := matchLen(win[i:i+minMatchLook], wPos) |
| 291 |
if n > length { |
| 292 |
length = n |
| 293 |
offset = pos - i |
| 294 |
ok = true |
| 295 |
if n >= nice { |
| 296 |
// The match is good enough that we don't try to find a better one. |
| 297 |
break |
| 298 |
} |
| 299 |
wEnd = win[pos+n] |
| 300 |
} |
| 301 |
} |
| 302 |
if i <= minIndex { |
| 303 |
// hashPrev[i & windowMask] has already been overwritten, so stop now. |
| 304 |
break |
| 305 |
} |
| 306 |
i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset |
| 307 |
if i < minIndex { |
| 308 |
break |
| 309 |
} |
| 310 |
} |
| 311 |
return |
| 312 |
} |
| 313 |
|
| 314 |
// Minimum gain to accept a match. |
| 315 |
cGain := 4 |
| 316 |
|
| 317 |
// Some like it higher (CSV), some like it lower (JSON) |
| 318 |
const baseCost = 3 |
| 319 |
// Base is 4 bytes at with an additional cost. |
| 320 |
// Matches must be better than this. |
| 321 |
|
| 322 |
for i := prevHead; tries > 0; tries-- { |
| 323 |
if wEnd == win[i+length] { |
| 324 |
n := matchLen(win[i:i+minMatchLook], wPos) |
| 325 |
if n > length { |
| 326 |
// Calculate gain. Estimate |
| 327 |
newGain := d.h.bitLengthRaw(wPos[:n]) - int(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int(lengthExtraBits[lengthCodes[(n-3)&255]]) |
| 328 |
|
| 329 |
//fmt.Println("gain:", newGain, "prev:", cGain, "raw:", d.h.bitLengthRaw(wPos[:n]), "this-len:", n, "prev-len:", length) |
| 330 |
if newGain > cGain { |
| 331 |
length = n |
| 332 |
offset = pos - i |
| 333 |
cGain = newGain |
| 334 |
ok = true |
| 335 |
if n >= nice { |
| 336 |
// The match is good enough that we don't try to find a better one. |
| 337 |
break |
| 338 |
} |
| 339 |
wEnd = win[pos+n] |
| 340 |
} |
| 341 |
} |
| 342 |
} |
| 343 |
if i <= minIndex { |
| 344 |
// hashPrev[i & windowMask] has already been overwritten, so stop now. |
| 345 |
break |
| 346 |
} |
| 347 |
i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset |
| 348 |
if i < minIndex { |
| 349 |
break |
| 350 |
} |
| 351 |
} |
| 352 |
return |
| 353 |
} |
| 354 |
|
| 355 |
func (d *compressor) writeStoredBlock(buf []byte) error { |
| 356 |
if d.w.writeStoredHeader(len(buf), false); d.w.err != nil { |
| 357 |
return d.w.err |
| 358 |
} |
| 359 |
d.w.writeBytes(buf) |
| 360 |
return d.w.err |
| 361 |
} |
| 362 |
|
| 363 |
// hash4 returns a hash representation of the first 4 bytes |
| 364 |
// of the supplied slice. |
| 365 |
// The caller must ensure that len(b) >= 4. |
| 366 |
func hash4(b []byte) uint32 { |
| 367 |
return hash4u(le.Load32(b, 0), hashBits) |
| 368 |
} |
| 369 |
|
| 370 |
// hash4 returns the hash of u to fit in a hash table with h bits. |
| 371 |
// Preferably h should be a constant and should always be <32. |
| 372 |
func hash4u(u uint32, h uint8) uint32 { |
| 373 |
return (u * prime4bytes) >> (32 - h) |
| 374 |
} |
| 375 |
|
| 376 |
// bulkHash4 will compute hashes using the same |
| 377 |
// algorithm as hash4 |
| 378 |
func bulkHash4(b []byte, dst []uint32) { |
| 379 |
if len(b) < 4 { |
| 380 |
return |
| 381 |
} |
| 382 |
hb := le.Load32(b, 0) |
| 383 |
|
| 384 |
dst[0] = hash4u(hb, hashBits) |
| 385 |
end := len(b) - 4 + 1 |
| 386 |
for i := 1; i < end; i++ { |
| 387 |
hb = (hb >> 8) | uint32(b[i+3])<<24 |
| 388 |
dst[i] = hash4u(hb, hashBits) |
| 389 |
} |
| 390 |
} |
| 391 |
|
| 392 |
func (d *compressor) initDeflate() { |
| 393 |
d.window = make([]byte, 2*windowSize) |
| 394 |
d.byteAvailable = false |
| 395 |
d.err = nil |
| 396 |
if d.state == nil { |
| 397 |
return |
| 398 |
} |
| 399 |
s := d.state |
| 400 |
s.index = 0 |
| 401 |
s.hashOffset = 1 |
| 402 |
s.length = minMatchLength - 1 |
| 403 |
s.offset = 0 |
| 404 |
s.chainHead = -1 |
| 405 |
} |
| 406 |
|
| 407 |
// deflateLazy is the same as deflate, but with d.fastSkipHashing == skipNever, |
| 408 |
// meaning it always has lazy matching on. |
| 409 |
func (d *compressor) deflateLazy() { |
| 410 |
s := d.state |
| 411 |
// Sanity enables additional runtime tests. |
| 412 |
// It's intended to be used during development |
| 413 |
// to supplement the currently ad-hoc unit tests. |
| 414 |
const sanity = debugDeflate |
| 415 |
|
| 416 |
if d.windowEnd-s.index < minMatchLength+maxMatchLength && !d.sync { |
| 417 |
return |
| 418 |
} |
| 419 |
if d.windowEnd != s.index && d.chain > 100 { |
| 420 |
// Get literal huffman coder. |
| 421 |
if d.h == nil { |
| 422 |
d.h = newHuffmanEncoder(maxFlateBlockTokens) |
| 423 |
} |
| 424 |
var tmp [256]uint16 |
| 425 |
toIndex := d.window[s.index:d.windowEnd] |
| 426 |
toIndex = toIndex[:min(len(toIndex), maxFlateBlockTokens)] |
| 427 |
for _, v := range toIndex { |
| 428 |
tmp[v]++ |
| 429 |
} |
| 430 |
d.h.generate(tmp[:], 15) |
| 431 |
} |
| 432 |
|
| 433 |
s.maxInsertIndex = d.windowEnd - (minMatchLength - 1) |
| 434 |
|
| 435 |
for { |
| 436 |
if sanity && s.index > d.windowEnd { |
| 437 |
panic("index > windowEnd") |
| 438 |
} |
| 439 |
lookahead := d.windowEnd - s.index |
| 440 |
if lookahead < minMatchLength+maxMatchLength { |
| 441 |
if !d.sync { |
| 442 |
return |
| 443 |
} |
| 444 |
if sanity && s.index > d.windowEnd { |
| 445 |
panic("index > windowEnd") |
| 446 |
} |
| 447 |
if lookahead == 0 { |
| 448 |
// Flush current output block if any. |
| 449 |
if d.byteAvailable { |
| 450 |
// There is still one pending token that needs to be flushed |
| 451 |
d.tokens.AddLiteral(d.window[s.index-1]) |
| 452 |
d.byteAvailable = false |
| 453 |
} |
| 454 |
if d.tokens.n > 0 { |
| 455 |
if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { |
| 456 |
return |
| 457 |
} |
| 458 |
d.tokens.Reset() |
| 459 |
} |
| 460 |
return |
| 461 |
} |
| 462 |
} |
| 463 |
if s.index < s.maxInsertIndex { |
| 464 |
// Update the hash |
| 465 |
hash := hash4(d.window[s.index:]) |
| 466 |
ch := s.hashHead[hash] |
| 467 |
s.chainHead = int(ch) |
| 468 |
s.hashPrev[s.index&windowMask] = ch |
| 469 |
s.hashHead[hash] = uint32(s.index + s.hashOffset) |
| 470 |
} |
| 471 |
prevLength := s.length |
| 472 |
prevOffset := s.offset |
| 473 |
s.length = minMatchLength - 1 |
| 474 |
s.offset = 0 |
| 475 |
minIndex := max(s.index-windowSize, 0) |
| 476 |
|
| 477 |
if s.chainHead-s.hashOffset >= minIndex && lookahead > prevLength && prevLength < d.lazy { |
| 478 |
if newLength, newOffset, ok := d.findMatch(s.index, s.chainHead-s.hashOffset, lookahead); ok { |
| 479 |
s.length = newLength |
| 480 |
s.offset = newOffset |
| 481 |
} |
| 482 |
} |
| 483 |
|
| 484 |
if prevLength >= minMatchLength && s.length <= prevLength { |
| 485 |
// No better match, but check for better match at end... |
| 486 |
// |
| 487 |
// Skip forward a number of bytes. |
| 488 |
// Offset of 2 seems to yield best results. 3 is sometimes better. |
| 489 |
const checkOff = 2 |
| 490 |
|
| 491 |
// Check all, except full length |
| 492 |
if prevLength < maxMatchLength-checkOff { |
| 493 |
prevIndex := s.index - 1 |
| 494 |
if prevIndex+prevLength < s.maxInsertIndex { |
| 495 |
end := min(lookahead, maxMatchLength+checkOff) |
| 496 |
end += prevIndex |
| 497 |
|
| 498 |
// Hash at match end. |
| 499 |
h := hash4(d.window[prevIndex+prevLength:]) |
| 500 |
ch2 := int(s.hashHead[h]) - s.hashOffset - prevLength |
| 501 |
if prevIndex-ch2 != prevOffset && ch2 > minIndex+checkOff { |
| 502 |
length := matchLen(d.window[prevIndex+checkOff:end], d.window[ch2+checkOff:]) |
| 503 |
// It seems like a pure length metric is best. |
| 504 |
if length > prevLength { |
| 505 |
prevLength = length |
| 506 |
prevOffset = prevIndex - ch2 |
| 507 |
|
| 508 |
// Extend back... |
| 509 |
for i := checkOff - 1; i >= 0; i-- { |
| 510 |
if prevLength >= maxMatchLength || d.window[prevIndex+i] != d.window[ch2+i] { |
| 511 |
// Emit tokens we "owe" |
| 512 |
for j := 0; j <= i; j++ { |
| 513 |
d.tokens.AddLiteral(d.window[prevIndex+j]) |
| 514 |
if d.tokens.n == maxFlateBlockTokens { |
| 515 |
// The block includes the current character |
| 516 |
if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { |
| 517 |
return |
| 518 |
} |
| 519 |
d.tokens.Reset() |
| 520 |
} |
| 521 |
s.index++ |
| 522 |
if s.index < s.maxInsertIndex { |
| 523 |
h := hash4(d.window[s.index:]) |
| 524 |
ch := s.hashHead[h] |
| 525 |
s.chainHead = int(ch) |
| 526 |
s.hashPrev[s.index&windowMask] = ch |
| 527 |
s.hashHead[h] = uint32(s.index + s.hashOffset) |
| 528 |
} |
| 529 |
} |
| 530 |
break |
| 531 |
} else { |
| 532 |
prevLength++ |
| 533 |
} |
| 534 |
} |
| 535 |
} else if false { |
| 536 |
// Check one further ahead. |
| 537 |
// Only rarely better, disabled for now. |
| 538 |
prevIndex++ |
| 539 |
h := hash4(d.window[prevIndex+prevLength:]) |
| 540 |
ch2 := int(s.hashHead[h]) - s.hashOffset - prevLength |
| 541 |
if prevIndex-ch2 != prevOffset && ch2 > minIndex+checkOff { |
| 542 |
length := matchLen(d.window[prevIndex+checkOff:end], d.window[ch2+checkOff:]) |
| 543 |
// It seems like a pure length metric is best. |
| 544 |
if length > prevLength+checkOff { |
| 545 |
prevLength = length |
| 546 |
prevOffset = prevIndex - ch2 |
| 547 |
prevIndex-- |
| 548 |
|
| 549 |
// Extend back... |
| 550 |
for i := checkOff; i >= 0; i-- { |
| 551 |
if prevLength >= maxMatchLength || d.window[prevIndex+i] != d.window[ch2+i-1] { |
| 552 |
// Emit tokens we "owe" |
| 553 |
for j := 0; j <= i; j++ { |
| 554 |
d.tokens.AddLiteral(d.window[prevIndex+j]) |
| 555 |
if d.tokens.n == maxFlateBlockTokens { |
| 556 |
// The block includes the current character |
| 557 |
if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { |
| 558 |
return |
| 559 |
} |
| 560 |
d.tokens.Reset() |
| 561 |
} |
| 562 |
s.index++ |
| 563 |
if s.index < s.maxInsertIndex { |
| 564 |
h := hash4(d.window[s.index:]) |
| 565 |
ch := s.hashHead[h] |
| 566 |
s.chainHead = int(ch) |
| 567 |
s.hashPrev[s.index&windowMask] = ch |
| 568 |
s.hashHead[h] = uint32(s.index + s.hashOffset) |
| 569 |
} |
| 570 |
} |
| 571 |
break |
| 572 |
} else { |
| 573 |
prevLength++ |
| 574 |
} |
| 575 |
} |
| 576 |
} |
| 577 |
} |
| 578 |
} |
| 579 |
} |
| 580 |
} |
| 581 |
} |
| 582 |
// There was a match at the previous step, and the current match is |
| 583 |
// not better. Output the previous match. |
| 584 |
d.tokens.AddMatch(uint32(prevLength-3), uint32(prevOffset-minOffsetSize)) |
| 585 |
|
| 586 |
// Insert in the hash table all strings up to the end of the match. |
| 587 |
// index and index-1 are already inserted. If there is not enough |
| 588 |
// lookahead, the last two strings are not inserted into the hash |
| 589 |
// table. |
| 590 |
newIndex := s.index + prevLength - 1 |
| 591 |
// Calculate missing hashes |
| 592 |
end := min(newIndex, s.maxInsertIndex) |
| 593 |
end += minMatchLength - 1 |
| 594 |
startindex := min(s.index+1, s.maxInsertIndex) |
| 595 |
tocheck := d.window[startindex:end] |
| 596 |
dstSize := len(tocheck) - minMatchLength + 1 |
| 597 |
if dstSize > 0 { |
| 598 |
dst := s.hashMatch[:dstSize] |
| 599 |
bulkHash4(tocheck, dst) |
| 600 |
var newH uint32 |
| 601 |
for i, val := range dst { |
| 602 |
di := i + startindex |
| 603 |
newH = val & hashMask |
| 604 |
// Get previous value with the same hash. |
| 605 |
// Our chain should point to the previous value. |
| 606 |
s.hashPrev[di&windowMask] = s.hashHead[newH] |
| 607 |
// Set the head of the hash chain to us. |
| 608 |
s.hashHead[newH] = uint32(di + s.hashOffset) |
| 609 |
} |
| 610 |
} |
| 611 |
|
| 612 |
s.index = newIndex |
| 613 |
d.byteAvailable = false |
| 614 |
s.length = minMatchLength - 1 |
| 615 |
if d.tokens.n == maxFlateBlockTokens { |
| 616 |
// The block includes the current character |
| 617 |
if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { |
| 618 |
return |
| 619 |
} |
| 620 |
d.tokens.Reset() |
| 621 |
} |
| 622 |
s.ii = 0 |
| 623 |
} else { |
| 624 |
// Reset, if we got a match this run. |
| 625 |
if s.length >= minMatchLength { |
| 626 |
s.ii = 0 |
| 627 |
} |
| 628 |
// We have a byte waiting. Emit it. |
| 629 |
if d.byteAvailable { |
| 630 |
s.ii++ |
| 631 |
d.tokens.AddLiteral(d.window[s.index-1]) |
| 632 |
if d.tokens.n == maxFlateBlockTokens { |
| 633 |
if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { |
| 634 |
return |
| 635 |
} |
| 636 |
d.tokens.Reset() |
| 637 |
} |
| 638 |
s.index++ |
| 639 |
|
| 640 |
// If we have a long run of no matches, skip additional bytes |
| 641 |
// Resets when s.ii overflows after 64KB. |
| 642 |
if n := int(s.ii) - d.chain; n > 0 { |
| 643 |
n = 1 + int(n>>6) |
| 644 |
for j := 0; j < n; j++ { |
| 645 |
if s.index >= d.windowEnd-1 { |
| 646 |
break |
| 647 |
} |
| 648 |
d.tokens.AddLiteral(d.window[s.index-1]) |
| 649 |
if d.tokens.n == maxFlateBlockTokens { |
| 650 |
if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { |
| 651 |
return |
| 652 |
} |
| 653 |
d.tokens.Reset() |
| 654 |
} |
| 655 |
// Index... |
| 656 |
if s.index < s.maxInsertIndex { |
| 657 |
h := hash4(d.window[s.index:]) |
| 658 |
ch := s.hashHead[h] |
| 659 |
s.chainHead = int(ch) |
| 660 |
s.hashPrev[s.index&windowMask] = ch |
| 661 |
s.hashHead[h] = uint32(s.index + s.hashOffset) |
| 662 |
} |
| 663 |
s.index++ |
| 664 |
} |
| 665 |
// Flush last byte |
| 666 |
d.tokens.AddLiteral(d.window[s.index-1]) |
| 667 |
d.byteAvailable = false |
| 668 |
// s.length = minMatchLength - 1 // not needed, since s.ii is reset above, so it should never be > minMatchLength |
| 669 |
if d.tokens.n == maxFlateBlockTokens { |
| 670 |
if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { |
| 671 |
return |
| 672 |
} |
| 673 |
d.tokens.Reset() |
| 674 |
} |
| 675 |
} |
| 676 |
} else { |
| 677 |
s.index++ |
| 678 |
d.byteAvailable = true |
| 679 |
} |
| 680 |
} |
| 681 |
} |
| 682 |
} |
| 683 |
|
| 684 |
func (d *compressor) store() { |
| 685 |
if d.windowEnd > 0 && (d.windowEnd == maxStoreBlockSize || d.sync) { |
| 686 |
d.err = d.writeStoredBlock(d.window[:d.windowEnd]) |
| 687 |
d.windowEnd = 0 |
| 688 |
} |
| 689 |
} |
| 690 |
|
| 691 |
// fillWindow will fill the buffer with data for huffman-only compression. |
| 692 |
// The number of bytes copied is returned. |
| 693 |
func (d *compressor) fillBlock(b []byte) int { |
| 694 |
n := copy(d.window[d.windowEnd:], b) |
| 695 |
d.windowEnd += n |
| 696 |
return n |
| 697 |
} |
| 698 |
|
| 699 |
// storeHuff will compress and store the currently added data, |
| 700 |
// if enough has been accumulated or we at the end of the stream. |
| 701 |
// Any error that occurred will be in d.err |
| 702 |
func (d *compressor) storeHuff() { |
| 703 |
if d.windowEnd < len(d.window) && !d.sync || d.windowEnd == 0 { |
| 704 |
return |
| 705 |
} |
| 706 |
d.w.writeBlockHuff(false, d.window[:d.windowEnd], d.sync) |
| 707 |
d.err = d.w.err |
| 708 |
d.windowEnd = 0 |
| 709 |
} |
| 710 |
|
| 711 |
// storeFast will compress and store the currently added data, |
| 712 |
// if enough has been accumulated or we at the end of the stream. |
| 713 |
// Any error that occurred will be in d.err |
| 714 |
func (d *compressor) storeFast() { |
| 715 |
// We only compress if we have maxStoreBlockSize. |
| 716 |
if d.windowEnd < len(d.window) { |
| 717 |
if !d.sync { |
| 718 |
return |
| 719 |
} |
| 720 |
// Handle extremely small sizes. |
| 721 |
if d.windowEnd < 128 { |
| 722 |
if d.windowEnd == 0 { |
| 723 |
return |
| 724 |
} |
| 725 |
if d.windowEnd <= 32 { |
| 726 |
d.err = d.writeStoredBlock(d.window[:d.windowEnd]) |
| 727 |
} else { |
| 728 |
d.w.writeBlockHuff(false, d.window[:d.windowEnd], true) |
| 729 |
d.err = d.w.err |
| 730 |
} |
| 731 |
d.tokens.Reset() |
| 732 |
d.windowEnd = 0 |
| 733 |
d.fast.Reset() |
| 734 |
return |
| 735 |
} |
| 736 |
} |
| 737 |
|
| 738 |
d.fast.Encode(&d.tokens, d.window[:d.windowEnd]) |
| 739 |
// If we made zero matches, store the block as is. |
| 740 |
if d.tokens.n == 0 { |
| 741 |
d.err = d.writeStoredBlock(d.window[:d.windowEnd]) |
| 742 |
// If we removed less than 1/16th, huffman compress the block. |
| 743 |
} else if int(d.tokens.n) > d.windowEnd-(d.windowEnd>>4) { |
| 744 |
d.w.writeBlockHuff(false, d.window[:d.windowEnd], d.sync) |
| 745 |
d.err = d.w.err |
| 746 |
} else { |
| 747 |
d.w.writeBlockDynamic(&d.tokens, false, d.window[:d.windowEnd], d.sync) |
| 748 |
d.err = d.w.err |
| 749 |
} |
| 750 |
d.tokens.Reset() |
| 751 |
d.windowEnd = 0 |
| 752 |
} |
| 753 |
|
| 754 |
// write will add input byte to the stream. |
| 755 |
// Unless an error occurs all bytes will be consumed. |
| 756 |
func (d *compressor) write(b []byte) (n int, err error) { |
| 757 |
if d.err != nil { |
| 758 |
return 0, d.err |
| 759 |
} |
| 760 |
n = len(b) |
| 761 |
for len(b) > 0 { |
| 762 |
if d.windowEnd == len(d.window) || d.sync { |
| 763 |
d.step(d) |
| 764 |
} |
| 765 |
b = b[d.fill(d, b):] |
| 766 |
if d.err != nil { |
| 767 |
return 0, d.err |
| 768 |
} |
| 769 |
} |
| 770 |
return n, d.err |
| 771 |
} |
| 772 |
|
| 773 |
func (d *compressor) syncFlush() error { |
| 774 |
d.sync = true |
| 775 |
if d.err != nil { |
| 776 |
return d.err |
| 777 |
} |
| 778 |
d.step(d) |
| 779 |
if d.err == nil { |
| 780 |
d.w.writeStoredHeader(0, false) |
| 781 |
d.w.flush() |
| 782 |
d.err = d.w.err |
| 783 |
} |
| 784 |
d.sync = false |
| 785 |
return d.err |
| 786 |
} |
| 787 |
|
| 788 |
func (d *compressor) init(w io.Writer, level int) (err error) { |
| 789 |
d.w = newHuffmanBitWriter(w) |
| 790 |
|
| 791 |
switch { |
| 792 |
case level == NoCompression: |
| 793 |
d.window = make([]byte, maxStoreBlockSize) |
| 794 |
d.fill = (*compressor).fillBlock |
| 795 |
d.step = (*compressor).store |
| 796 |
case level == ConstantCompression: |
| 797 |
d.w.logNewTablePenalty = 10 |
| 798 |
d.window = make([]byte, 32<<10) |
| 799 |
d.fill = (*compressor).fillBlock |
| 800 |
d.step = (*compressor).storeHuff |
| 801 |
case level == DefaultCompression: |
| 802 |
level = 5 |
| 803 |
fallthrough |
| 804 |
case level >= 1 && level <= 6: |
| 805 |
d.w.logNewTablePenalty = 7 |
| 806 |
d.fast = newFastEnc(level) |
| 807 |
d.window = make([]byte, maxStoreBlockSize) |
| 808 |
d.fill = (*compressor).fillBlock |
| 809 |
d.step = (*compressor).storeFast |
| 810 |
case 7 <= level && level <= 9: |
| 811 |
d.w.logNewTablePenalty = 8 |
| 812 |
d.state = &advancedState{} |
| 813 |
d.compressionLevel = levels[level] |
| 814 |
d.initDeflate() |
| 815 |
d.fill = (*compressor).fillDeflate |
| 816 |
d.step = (*compressor).deflateLazy |
| 817 |
case -level >= MinCustomWindowSize && -level <= MaxCustomWindowSize: |
| 818 |
d.w.logNewTablePenalty = 7 |
| 819 |
d.fast = &fastEncL5Window{maxOffset: int32(-level), cur: maxStoreBlockSize} |
| 820 |
d.window = make([]byte, maxStoreBlockSize) |
| 821 |
d.fill = (*compressor).fillBlock |
| 822 |
d.step = (*compressor).storeFast |
| 823 |
default: |
| 824 |
return fmt.Errorf("flate: invalid compression level %d: want value in range [-2, 9]", level) |
| 825 |
} |
| 826 |
d.level = level |
| 827 |
return nil |
| 828 |
} |
| 829 |
|
| 830 |
// reset the state of the compressor. |
| 831 |
func (d *compressor) reset(w io.Writer) { |
| 832 |
d.w.reset(w) |
| 833 |
d.sync = false |
| 834 |
d.err = nil |
| 835 |
// We only need to reset a few things for Snappy. |
| 836 |
if d.fast != nil { |
| 837 |
d.fast.Reset() |
| 838 |
d.windowEnd = 0 |
| 839 |
d.tokens.Reset() |
| 840 |
return |
| 841 |
} |
| 842 |
switch d.compressionLevel.chain { |
| 843 |
case 0: |
| 844 |
// level was NoCompression or ConstantCompression. |
| 845 |
d.windowEnd = 0 |
| 846 |
default: |
| 847 |
s := d.state |
| 848 |
s.chainHead = -1 |
| 849 |
for i := range s.hashHead { |
| 850 |
s.hashHead[i] = 0 |
| 851 |
} |
| 852 |
for i := range s.hashPrev { |
| 853 |
s.hashPrev[i] = 0 |
| 854 |
} |
| 855 |
s.hashOffset = 1 |
| 856 |
s.index, d.windowEnd = 0, 0 |
| 857 |
d.blockStart, d.byteAvailable = 0, false |
| 858 |
d.tokens.Reset() |
| 859 |
s.length = minMatchLength - 1 |
| 860 |
s.offset = 0 |
| 861 |
s.ii = 0 |
| 862 |
s.maxInsertIndex = 0 |
| 863 |
} |
| 864 |
} |
| 865 |
|
| 866 |
func (d *compressor) close() error { |
| 867 |
if d.err != nil { |
| 868 |
return d.err |
| 869 |
} |
| 870 |
d.sync = true |
| 871 |
d.step(d) |
| 872 |
if d.err != nil { |
| 873 |
return d.err |
| 874 |
} |
| 875 |
if d.w.writeStoredHeader(0, true); d.w.err != nil { |
| 876 |
return d.w.err |
| 877 |
} |
| 878 |
d.w.flush() |
| 879 |
d.w.reset(nil) |
| 880 |
return d.w.err |
| 881 |
} |
| 882 |
|
| 883 |
// NewWriter returns a new Writer compressing data at the given level. |
| 884 |
// Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression); |
| 885 |
// higher levels typically run slower but compress more. |
| 886 |
// Level 0 (NoCompression) does not attempt any compression; it only adds the |
| 887 |
// necessary DEFLATE framing. |
| 888 |
// Level -1 (DefaultCompression) uses the default compression level. |
| 889 |
// Level -2 (ConstantCompression) will use Huffman compression only, giving |
| 890 |
// a very fast compression for all types of input, but sacrificing considerable |
| 891 |
// compression efficiency. |
| 892 |
// |
| 893 |
// If level is in the range [-2, 9] then the error returned will be nil. |
| 894 |
// Otherwise the error returned will be non-nil. |
| 895 |
func NewWriter(w io.Writer, level int) (*Writer, error) { |
| 896 |
var dw Writer |
| 897 |
if err := dw.d.init(w, level); err != nil { |
| 898 |
return nil, err |
| 899 |
} |
| 900 |
return &dw, nil |
| 901 |
} |
| 902 |
|
| 903 |
// NewWriterDict is like NewWriter but initializes the new |
| 904 |
// Writer with a preset dictionary. The returned Writer behaves |
| 905 |
// as if the dictionary had been written to it without producing |
| 906 |
// any compressed output. The compressed data written to w |
| 907 |
// can only be decompressed by a Reader initialized with the |
| 908 |
// same dictionary. |
| 909 |
func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) { |
| 910 |
zw, err := NewWriter(w, level) |
| 911 |
if err != nil { |
| 912 |
return nil, err |
| 913 |
} |
| 914 |
zw.d.fillWindow(dict) |
| 915 |
zw.dict = append(zw.dict, dict...) // duplicate dictionary for Reset method. |
| 916 |
return zw, err |
| 917 |
} |
| 918 |
|
| 919 |
// MinCustomWindowSize is the minimum window size that can be sent to NewWriterWindow. |
| 920 |
const MinCustomWindowSize = 32 |
| 921 |
|
| 922 |
// MaxCustomWindowSize is the maximum custom window that can be sent to NewWriterWindow. |
| 923 |
const MaxCustomWindowSize = windowSize |
| 924 |
|
| 925 |
// NewWriterWindow returns a new Writer compressing data with a custom window size. |
| 926 |
// windowSize must be from MinCustomWindowSize to MaxCustomWindowSize. |
| 927 |
func NewWriterWindow(w io.Writer, windowSize int) (*Writer, error) { |
| 928 |
if windowSize < MinCustomWindowSize { |
| 929 |
return nil, errors.New("flate: requested window size less than MinWindowSize") |
| 930 |
} |
| 931 |
if windowSize > MaxCustomWindowSize { |
| 932 |
return nil, errors.New("flate: requested window size bigger than MaxCustomWindowSize") |
| 933 |
} |
| 934 |
var dw Writer |
| 935 |
if err := dw.d.init(w, -windowSize); err != nil { |
| 936 |
return nil, err |
| 937 |
} |
| 938 |
return &dw, nil |
| 939 |
} |
| 940 |
|
| 941 |
// A Writer takes data written to it and writes the compressed |
| 942 |
// form of that data to an underlying writer (see NewWriter). |
| 943 |
type Writer struct { |
| 944 |
d compressor |
| 945 |
dict []byte |
| 946 |
} |
| 947 |
|
| 948 |
// Write writes data to w, which will eventually write the |
| 949 |
// compressed form of data to its underlying writer. |
| 950 |
func (w *Writer) Write(data []byte) (n int, err error) { |
| 951 |
return w.d.write(data) |
| 952 |
} |
| 953 |
|
| 954 |
// Flush flushes any pending data to the underlying writer. |
| 955 |
// It is useful mainly in compressed network protocols, to ensure that |
| 956 |
// a remote reader has enough data to reconstruct a packet. |
| 957 |
// Flush does not return until the data has been written. |
| 958 |
// Calling Flush when there is no pending data still causes the Writer |
| 959 |
// to emit a sync marker of at least 4 bytes. |
| 960 |
// If the underlying writer returns an error, Flush returns that error. |
| 961 |
// |
| 962 |
// In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH. |
| 963 |
func (w *Writer) Flush() error { |
| 964 |
// For more about flushing: |
| 965 |
// http://www.bolet.org/~pornin/deflate-flush.html |
| 966 |
return w.d.syncFlush() |
| 967 |
} |
| 968 |
|
| 969 |
// Close flushes and closes the writer. |
| 970 |
func (w *Writer) Close() error { |
| 971 |
return w.d.close() |
| 972 |
} |
| 973 |
|
| 974 |
// Reset discards the writer's state and makes it equivalent to |
| 975 |
// the result of NewWriter or NewWriterDict called with dst |
| 976 |
// and w's level and dictionary. |
| 977 |
func (w *Writer) Reset(dst io.Writer) { |
| 978 |
if len(w.dict) > 0 { |
| 979 |
// w was created with NewWriterDict |
| 980 |
w.d.reset(dst) |
| 981 |
if dst != nil { |
| 982 |
w.d.fillWindow(w.dict) |
| 983 |
} |
| 984 |
} else { |
| 985 |
// w was created with NewWriter |
| 986 |
w.d.reset(dst) |
| 987 |
} |
| 988 |
} |
| 989 |
|
| 990 |
// ResetDict discards the writer's state and makes it equivalent to |
| 991 |
// the result of NewWriter or NewWriterDict called with dst |
| 992 |
// and w's level, but sets a specific dictionary. |
| 993 |
func (w *Writer) ResetDict(dst io.Writer, dict []byte) { |
| 994 |
w.dict = dict |
| 995 |
w.d.reset(dst) |
| 996 |
w.d.fillWindow(w.dict) |
| 997 |
} |