Debian Codegraph @

flate/huffman_bit_writer.go

raw
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
6
7 import (
8 "fmt"
9 "io"
10 "math"
11
12 "github.com/klauspost/compress/internal/le"
13 )
14
15 const (
16 // The largest offset code.
17 offsetCodeCount = 30
18
19 // The special code used to mark the end of a block.
20 endBlockMarker = 256
21
22 // The first length code.
23 lengthCodesStart = 257
24
25 // The number of codegen codes.
26 codegenCodeCount = 19
27 badCode = 255
28
29 // maxPredefinedTokens is the maximum number of tokens
30 // where we check if fixed size is smaller.
31 maxPredefinedTokens = 250
32
33 // bufferFlushSize indicates the buffer size
34 // after which bytes are flushed to the writer.
35 // Should preferably be a multiple of 6, since
36 // we accumulate 6 bytes between writes to the buffer.
37 bufferFlushSize = 246
38 )
39
40 // Minimum length code that emits bits.
41 const lengthExtraBitsMinCode = 8
42
43 // The number of extra bits needed by length code X - LENGTH_CODES_START.
44 var lengthExtraBits = [32]uint8{
45 /* 257 */ 0, 0, 0,
46 /* 260 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2,
47 /* 270 */ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,
48 /* 280 */ 4, 5, 5, 5, 5, 0,
49 }
50
51 // The length indicated by length code X - LENGTH_CODES_START.
52 var lengthBase = [32]uint8{
53 0, 1, 2, 3, 4, 5, 6, 7, 8, 10,
54 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
55 64, 80, 96, 112, 128, 160, 192, 224, 255,
56 }
57
58 // Minimum offset code that emits bits.
59 const offsetExtraBitsMinCode = 4
60
61 // offset code word extra bits.
62 var offsetExtraBits = [32]int8{
63 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
64 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
65 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
66 /* extended window */
67 14, 14,
68 }
69
70 var offsetCombined = [32]uint32{}
71
72 func init() {
73 var offsetBase = [32]uint32{
74 /* normal deflate */
75 0x000000, 0x000001, 0x000002, 0x000003, 0x000004,
76 0x000006, 0x000008, 0x00000c, 0x000010, 0x000018,
77 0x000020, 0x000030, 0x000040, 0x000060, 0x000080,
78 0x0000c0, 0x000100, 0x000180, 0x000200, 0x000300,
79 0x000400, 0x000600, 0x000800, 0x000c00, 0x001000,
80 0x001800, 0x002000, 0x003000, 0x004000, 0x006000,
81
82 /* extended window */
83 0x008000, 0x00c000,
84 }
85
86 for i := range offsetCombined[:] {
87 // Don't use extended window values...
88 if offsetExtraBits[i] == 0 || offsetBase[i] > 0x006000 {
89 continue
90 }
91 offsetCombined[i] = uint32(offsetExtraBits[i]) | (offsetBase[i] << 8)
92 }
93 }
94
95 // The odd order in which the codegen code sizes are written.
96 var codegenOrder = []uint32{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
97
98 type huffmanBitWriter struct {
99 // writer is the underlying writer.
100 // Do not use it directly; use the write method, which ensures
101 // that Write errors are sticky.
102 writer io.Writer
103
104 // Data waiting to be written is bytes[0:nbytes]
105 // and then the low nbits of bits.
106 bits uint64
107 nbits uint8
108 nbytes uint8
109 lastHuffMan bool
110 literalEncoding *huffmanEncoder
111 tmpLitEncoding *huffmanEncoder
112 offsetEncoding *huffmanEncoder
113 codegenEncoding *huffmanEncoder
114 err error
115 lastHeader int
116 // Set between 0 (reused block can be up to 2x the size)
117 logNewTablePenalty uint
118 bytes [256 + 8]byte
119 literalFreq [lengthCodesStart + 32]uint16
120 offsetFreq [32]uint16
121 codegenFreq [codegenCodeCount]uint16
122
123 // codegen must have an extra space for the final symbol.
124 codegen [literalCount + offsetCodeCount + 1]uint8
125 }
126
127 // Huffman reuse.
128 //
129 // The huffmanBitWriter supports reusing huffman tables and thereby combining block sections.
130 //
131 // This is controlled by several variables:
132 //
133 // If lastHeader is non-zero the Huffman table can be reused.
134 // This also indicates that a Huffman table has been generated that can output all
135 // possible symbols.
136 // It also indicates that an EOB has not yet been emitted, so if a new tabel is generated
137 // an EOB with the previous table must be written.
138 //
139 // If lastHuffMan is set, a table for outputting literals has been generated and offsets are invalid.
140 //
141 // An incoming block estimates the output size of a new table using a 'fresh' by calculating the
142 // optimal size and adding a penalty in 'logNewTablePenalty'.
143 // A Huffman table is not optimal, which is why we add a penalty, and generating a new table
144 // is slower both for compression and decompression.
145
146 func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter {
147 return &huffmanBitWriter{
148 writer: w,
149 literalEncoding: newHuffmanEncoder(literalCount),
150 tmpLitEncoding: newHuffmanEncoder(literalCount),
151 codegenEncoding: newHuffmanEncoder(codegenCodeCount),
152 offsetEncoding: newHuffmanEncoder(offsetCodeCount),
153 }
154 }
155
156 func (w *huffmanBitWriter) reset(writer io.Writer) {
157 w.writer = writer
158 w.bits, w.nbits, w.nbytes, w.err = 0, 0, 0, nil
159 w.lastHeader = 0
160 w.lastHuffMan = false
161 }
162
163 func (w *huffmanBitWriter) canReuse(t *tokens) (ok bool) {
164 a := t.offHist[:offsetCodeCount]
165 b := w.offsetEncoding.codes
166 b = b[:len(a)]
167 for i, v := range a {
168 if v != 0 && b[i].zero() {
169 return false
170 }
171 }
172
173 a = t.extraHist[:literalCount-256]
174 b = w.literalEncoding.codes[256:literalCount]
175 b = b[:len(a)]
176 for i, v := range a {
177 if v != 0 && b[i].zero() {
178 return false
179 }
180 }
181
182 a = t.litHist[:256]
183 b = w.literalEncoding.codes[:len(a)]
184 for i, v := range a {
185 if v != 0 && b[i].zero() {
186 return false
187 }
188 }
189 return true
190 }
191
192 func (w *huffmanBitWriter) flush() {
193 if w.err != nil {
194 w.nbits = 0
195 return
196 }
197 if w.lastHeader > 0 {
198 // We owe an EOB
199 w.writeCode(w.literalEncoding.codes[endBlockMarker])
200 w.lastHeader = 0
201 }
202 n := w.nbytes
203 for w.nbits != 0 {
204 w.bytes[n] = byte(w.bits)
205 w.bits >>= 8
206 if w.nbits > 8 { // Avoid underflow
207 w.nbits -= 8
208 } else {
209 w.nbits = 0
210 }
211 n++
212 }
213 w.bits = 0
214 if n > 0 {
215 w.write(w.bytes[:n])
216 }
217 w.nbytes = 0
218 }
219
220 func (w *huffmanBitWriter) write(b []byte) {
221 if w.err != nil {
222 return
223 }
224 _, w.err = w.writer.Write(b)
225 }
226
227 func (w *huffmanBitWriter) writeBits(b int32, nb uint8) {
228 w.bits |= uint64(b) << (w.nbits & 63)
229 w.nbits += nb
230 if w.nbits >= 48 {
231 w.writeOutBits()
232 }
233 }
234
235 func (w *huffmanBitWriter) writeBytes(bytes []byte) {
236 if w.err != nil {
237 return
238 }
239 n := w.nbytes
240 if w.nbits&7 != 0 {
241 w.err = InternalError("writeBytes with unfinished bits")
242 return
243 }
244 for w.nbits != 0 {
245 w.bytes[n] = byte(w.bits)
246 w.bits >>= 8
247 w.nbits -= 8
248 n++
249 }
250 if n != 0 {
251 w.write(w.bytes[:n])
252 }
253 w.nbytes = 0
254 w.write(bytes)
255 }
256
257 // RFC 1951 3.2.7 specifies a special run-length encoding for specifying
258 // the literal and offset lengths arrays (which are concatenated into a single
259 // array). This method generates that run-length encoding.
260 //
261 // The result is written into the codegen array, and the frequencies
262 // of each code is written into the codegenFreq array.
263 // Codes 0-15 are single byte codes. Codes 16-18 are followed by additional
264 // information. Code badCode is an end marker
265 //
266 // numLiterals The number of literals in literalEncoding
267 // numOffsets The number of offsets in offsetEncoding
268 // litenc, offenc The literal and offset encoder to use
269 func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litEnc, offEnc *huffmanEncoder) {
270 for i := range w.codegenFreq {
271 w.codegenFreq[i] = 0
272 }
273 // Note that we are using codegen both as a temporary variable for holding
274 // a copy of the frequencies, and as the place where we put the result.
275 // This is fine because the output is always shorter than the input used
276 // so far.
277 codegen := w.codegen[:] // cache
278 // Copy the concatenated code sizes to codegen. Put a marker at the end.
279 cgnl := codegen[:numLiterals]
280 for i := range cgnl {
281 cgnl[i] = litEnc.codes[i].len()
282 }
283
284 cgnl = codegen[numLiterals : numLiterals+numOffsets]
285 for i := range cgnl {
286 cgnl[i] = offEnc.codes[i].len()
287 }
288 codegen[numLiterals+numOffsets] = badCode
289
290 size := codegen[0]
291 count := 1
292 outIndex := 0
293 for inIndex := 1; size != badCode; inIndex++ {
294 // INVARIANT: We have seen "count" copies of size that have not yet
295 // had output generated for them.
296 nextSize := codegen[inIndex]
297 if nextSize == size {
298 count++
299 continue
300 }
301 // We need to generate codegen indicating "count" of size.
302 if size != 0 {
303 codegen[outIndex] = size
304 outIndex++
305 w.codegenFreq[size]++
306 count--
307 for count >= 3 {
308 n := min(6, count)
309 codegen[outIndex] = 16
310 outIndex++
311 codegen[outIndex] = uint8(n - 3)
312 outIndex++
313 w.codegenFreq[16]++
314 count -= n
315 }
316 } else {
317 for count >= 11 {
318 n := min(138, count)
319 codegen[outIndex] = 18
320 outIndex++
321 codegen[outIndex] = uint8(n - 11)
322 outIndex++
323 w.codegenFreq[18]++
324 count -= n
325 }
326 if count >= 3 {
327 // count >= 3 && count <= 10
328 codegen[outIndex] = 17
329 outIndex++
330 codegen[outIndex] = uint8(count - 3)
331 outIndex++
332 w.codegenFreq[17]++
333 count = 0
334 }
335 }
336 count--
337 for ; count >= 0; count-- {
338 codegen[outIndex] = size
339 outIndex++
340 w.codegenFreq[size]++
341 }
342 // Set up invariant for next time through the loop.
343 size = nextSize
344 count = 1
345 }
346 // Marker indicating the end of the codegen.
347 codegen[outIndex] = badCode
348 }
349
350 func (w *huffmanBitWriter) codegens() int {
351 numCodegens := len(w.codegenFreq)
352 for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 {
353 numCodegens--
354 }
355 return numCodegens
356 }
357
358 func (w *huffmanBitWriter) headerSize() (size, numCodegens int) {
359 numCodegens = len(w.codegenFreq)
360 for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 {
361 numCodegens--
362 }
363 return 3 + 5 + 5 + 4 + (3 * numCodegens) +
364 w.codegenEncoding.bitLength(w.codegenFreq[:]) +
365 int(w.codegenFreq[16])*2 +
366 int(w.codegenFreq[17])*3 +
367 int(w.codegenFreq[18])*7, numCodegens
368 }
369
370 // dynamicSize returns the size of dynamically encoded data in bits.
371 func (w *huffmanBitWriter) dynamicReuseSize(litEnc, offEnc *huffmanEncoder) (size int) {
372 size = litEnc.bitLength(w.literalFreq[:]) +
373 offEnc.bitLength(w.offsetFreq[:])
374 return size
375 }
376
377 // dynamicSize returns the size of dynamically encoded data in bits.
378 func (w *huffmanBitWriter) dynamicSize(litEnc, offEnc *huffmanEncoder, extraBits int) (size, numCodegens int) {
379 header, numCodegens := w.headerSize()
380 size = header +
381 litEnc.bitLength(w.literalFreq[:]) +
382 offEnc.bitLength(w.offsetFreq[:]) +
383 extraBits
384 return size, numCodegens
385 }
386
387 // extraBitSize will return the number of bits that will be written
388 // as "extra" bits on matches.
389 func (w *huffmanBitWriter) extraBitSize() int {
390 total := 0
391 for i, n := range w.literalFreq[257:literalCount] {
392 total += int(n) * int(lengthExtraBits[i&31])
393 }
394 for i, n := range w.offsetFreq[:offsetCodeCount] {
395 total += int(n) * int(offsetExtraBits[i&31])
396 }
397 return total
398 }
399
400 // fixedSize returns the size of dynamically encoded data in bits.
401 func (w *huffmanBitWriter) fixedSize(extraBits int) int {
402 return 3 +
403 fixedLiteralEncoding.bitLength(w.literalFreq[:]) +
404 fixedOffsetEncoding.bitLength(w.offsetFreq[:]) +
405 extraBits
406 }
407
408 // storedSize calculates the stored size, including header.
409 // The function returns the size in bits and whether the block
410 // fits inside a single block.
411 func (w *huffmanBitWriter) storedSize(in []byte) (int, bool) {
412 if in == nil {
413 return 0, false
414 }
415 if len(in) <= maxStoreBlockSize {
416 return (len(in) + 5) * 8, true
417 }
418 return 0, false
419 }
420
421 func (w *huffmanBitWriter) writeCode(c hcode) {
422 // The function does not get inlined if we "& 63" the shift.
423 w.bits |= c.code64() << (w.nbits & 63)
424 w.nbits += c.len()
425 if w.nbits >= 48 {
426 w.writeOutBits()
427 }
428 }
429
430 // writeOutBits will write bits to the buffer.
431 func (w *huffmanBitWriter) writeOutBits() {
432 bits := w.bits
433 w.bits >>= 48
434 w.nbits -= 48
435 n := w.nbytes
436
437 // We overwrite, but faster...
438 le.Store64(w.bytes[:], n, bits)
439 n += 6
440
441 if n >= bufferFlushSize {
442 if w.err != nil {
443 n = 0
444 return
445 }
446 w.write(w.bytes[:n])
447 n = 0
448 }
449
450 w.nbytes = n
451 }
452
453 // Write the header of a dynamic Huffman block to the output stream.
454 //
455 // numLiterals The number of literals specified in codegen
456 // numOffsets The number of offsets specified in codegen
457 // numCodegens The number of codegens used in codegen
458 func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, numCodegens int, isEof bool) {
459 if w.err != nil {
460 return
461 }
462 var firstBits int32 = 4
463 if isEof {
464 firstBits = 5
465 }
466 w.writeBits(firstBits, 3)
467 w.writeBits(int32(numLiterals-257), 5)
468 w.writeBits(int32(numOffsets-1), 5)
469 w.writeBits(int32(numCodegens-4), 4)
470
471 for i := range numCodegens {
472 value := uint(w.codegenEncoding.codes[codegenOrder[i]].len())
473 w.writeBits(int32(value), 3)
474 }
475
476 i := 0
477 for {
478 var codeWord = uint32(w.codegen[i])
479 i++
480 if codeWord == badCode {
481 break
482 }
483 w.writeCode(w.codegenEncoding.codes[codeWord])
484
485 switch codeWord {
486 case 16:
487 w.writeBits(int32(w.codegen[i]), 2)
488 i++
489 case 17:
490 w.writeBits(int32(w.codegen[i]), 3)
491 i++
492 case 18:
493 w.writeBits(int32(w.codegen[i]), 7)
494 i++
495 }
496 }
497 }
498
499 // writeStoredHeader will write a stored header.
500 // If the stored block is only used for EOF,
501 // it is replaced with a fixed huffman block.
502 func (w *huffmanBitWriter) writeStoredHeader(length int, isEof bool) {
503 if w.err != nil {
504 return
505 }
506 if w.lastHeader > 0 {
507 // We owe an EOB
508 w.writeCode(w.literalEncoding.codes[endBlockMarker])
509 w.lastHeader = 0
510 }
511
512 // To write EOF, use a fixed encoding block. 10 bits instead of 5 bytes.
513 if length == 0 && isEof {
514 w.writeFixedHeader(isEof)
515 // EOB: 7 bits, value: 0
516 w.writeBits(0, 7)
517 w.flush()
518 return
519 }
520
521 var flag int32
522 if isEof {
523 flag = 1
524 }
525 w.writeBits(flag, 3)
526 w.flush()
527 w.writeBits(int32(length), 16)
528 w.writeBits(int32(^uint16(length)), 16)
529 }
530
531 func (w *huffmanBitWriter) writeFixedHeader(isEof bool) {
532 if w.err != nil {
533 return
534 }
535 if w.lastHeader > 0 {
536 // We owe an EOB
537 w.writeCode(w.literalEncoding.codes[endBlockMarker])
538 w.lastHeader = 0
539 }
540
541 // Indicate that we are a fixed Huffman block
542 var value int32 = 2
543 if isEof {
544 value = 3
545 }
546 w.writeBits(value, 3)
547 }
548
549 // writeBlock will write a block of tokens with the smallest encoding.
550 // The original input can be supplied, and if the huffman encoded data
551 // is larger than the original bytes, the data will be written as a
552 // stored block.
553 // If the input is nil, the tokens will always be Huffman encoded.
554 func (w *huffmanBitWriter) writeBlock(tokens *tokens, eof bool, input []byte) {
555 if w.err != nil {
556 return
557 }
558
559 tokens.AddEOB()
560 if w.lastHeader > 0 {
561 // We owe an EOB
562 w.writeCode(w.literalEncoding.codes[endBlockMarker])
563 w.lastHeader = 0
564 }
565 numLiterals, numOffsets := w.indexTokens(tokens, false)
566 w.generate()
567 var extraBits int
568 storedSize, storable := w.storedSize(input)
569 if storable {
570 extraBits = w.extraBitSize()
571 }
572
573 // Figure out smallest code.
574 // Fixed Huffman baseline.
575 var literalEncoding = fixedLiteralEncoding
576 var offsetEncoding = fixedOffsetEncoding
577 var size = math.MaxInt32
578 if tokens.n < maxPredefinedTokens {
579 size = w.fixedSize(extraBits)
580 }
581
582 // Dynamic Huffman?
583 var numCodegens int
584
585 // Generate codegen and codegenFrequencies, which indicates how to encode
586 // the literalEncoding and the offsetEncoding.
587 w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding)
588 w.codegenEncoding.generate(w.codegenFreq[:], 7)
589 dynamicSize, numCodegens := w.dynamicSize(w.literalEncoding, w.offsetEncoding, extraBits)
590
591 if dynamicSize < size {
592 size = dynamicSize
593 literalEncoding = w.literalEncoding
594 offsetEncoding = w.offsetEncoding
595 }
596
597 // Stored bytes?
598 if storable && storedSize <= size {
599 w.writeStoredHeader(len(input), eof)
600 w.writeBytes(input)
601 return
602 }
603
604 // Huffman.
605 if literalEncoding == fixedLiteralEncoding {
606 w.writeFixedHeader(eof)
607 } else {
608 w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
609 }
610
611 // Write the tokens.
612 w.writeTokens(tokens.Slice(), literalEncoding.codes, offsetEncoding.codes)
613 }
614
615 // writeBlockDynamic encodes a block using a dynamic Huffman table.
616 // This should be used if the symbols used have a disproportionate
617 // histogram distribution.
618 // If input is supplied and the compression savings are below 1/16th of the
619 // input size the block is stored.
620 func (w *huffmanBitWriter) writeBlockDynamic(tokens *tokens, eof bool, input []byte, sync bool) {
621 if w.err != nil {
622 return
623 }
624
625 sync = sync || eof
626 if sync {
627 tokens.AddEOB()
628 }
629
630 // We cannot reuse pure huffman table, and must mark as EOF.
631 if (w.lastHuffMan || eof) && w.lastHeader > 0 {
632 // We will not try to reuse.
633 w.writeCode(w.literalEncoding.codes[endBlockMarker])
634 w.lastHeader = 0
635 w.lastHuffMan = false
636 }
637
638 // fillReuse enables filling of empty values.
639 // This will make encodings always reusable without testing.
640 // However, this does not appear to benefit on most cases.
641 const fillReuse = false
642
643 // Check if we can reuse...
644 if !fillReuse && w.lastHeader > 0 && !w.canReuse(tokens) {
645 w.writeCode(w.literalEncoding.codes[endBlockMarker])
646 w.lastHeader = 0
647 }
648
649 numLiterals, numOffsets := w.indexTokens(tokens, true)
650 extraBits := 0
651 ssize, storable := w.storedSize(input)
652
653 const usePrefs = true
654 if storable || w.lastHeader > 0 {
655 extraBits = w.extraBitSize()
656 }
657
658 var size int
659
660 // Check if we should reuse.
661 if w.lastHeader > 0 {
662 // Estimate size for using a new table.
663 // Use the previous header size as the best estimate.
664 newSize := w.lastHeader + tokens.EstimatedBits()
665 newSize += int(w.literalEncoding.codes[endBlockMarker].len()) + newSize>>w.logNewTablePenalty
666
667 // The estimated size is calculated as an optimal table.
668 // We add a penalty to make it more realistic and re-use a bit more.
669 reuseSize := w.dynamicReuseSize(w.literalEncoding, w.offsetEncoding) + extraBits
670
671 // Check if a new table is better.
672 if newSize < reuseSize {
673 // Write the EOB we owe.
674 w.writeCode(w.literalEncoding.codes[endBlockMarker])
675 size = newSize
676 w.lastHeader = 0
677 } else {
678 size = reuseSize
679 }
680
681 if tokens.n < maxPredefinedTokens {
682 if preSize := w.fixedSize(extraBits) + 7; usePrefs && preSize < size {
683 // Check if we get a reasonable size decrease.
684 if storable && ssize <= size {
685 w.writeStoredHeader(len(input), eof)
686 w.writeBytes(input)
687 return
688 }
689 w.writeFixedHeader(eof)
690 if !sync {
691 tokens.AddEOB()
692 }
693 w.writeTokens(tokens.Slice(), fixedLiteralEncoding.codes, fixedOffsetEncoding.codes)
694 return
695 }
696 }
697 // Check if we get a reasonable size decrease.
698 if storable && ssize <= size {
699 w.writeStoredHeader(len(input), eof)
700 w.writeBytes(input)
701 return
702 }
703 }
704
705 // We want a new block/table
706 if w.lastHeader == 0 {
707 if fillReuse && !sync {
708 w.fillTokens()
709 numLiterals, numOffsets = maxNumLit, maxNumDist
710 } else {
711 w.literalFreq[endBlockMarker] = 1
712 }
713
714 w.generate()
715 // Generate codegen and codegenFrequencies, which indicates how to encode
716 // the literalEncoding and the offsetEncoding.
717 w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding)
718 w.codegenEncoding.generate(w.codegenFreq[:], 7)
719
720 var numCodegens int
721 if fillReuse && !sync {
722 // Reindex for accurate size...
723 w.indexTokens(tokens, true)
724 }
725 size, numCodegens = w.dynamicSize(w.literalEncoding, w.offsetEncoding, extraBits)
726
727 // Store predefined, if we don't get a reasonable improvement.
728 if tokens.n < maxPredefinedTokens {
729 if preSize := w.fixedSize(extraBits); usePrefs && preSize <= size {
730 // Store bytes, if we don't get an improvement.
731 if storable && ssize <= preSize {
732 w.writeStoredHeader(len(input), eof)
733 w.writeBytes(input)
734 return
735 }
736 w.writeFixedHeader(eof)
737 if !sync {
738 tokens.AddEOB()
739 }
740 w.writeTokens(tokens.Slice(), fixedLiteralEncoding.codes, fixedOffsetEncoding.codes)
741 return
742 }
743 }
744
745 if storable && ssize <= size {
746 // Store bytes, if we don't get an improvement.
747 w.writeStoredHeader(len(input), eof)
748 w.writeBytes(input)
749 return
750 }
751
752 // Write Huffman table.
753 w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
754 if !sync {
755 w.lastHeader, _ = w.headerSize()
756 }
757 w.lastHuffMan = false
758 }
759
760 if sync {
761 w.lastHeader = 0
762 }
763 // Write the tokens.
764 w.writeTokens(tokens.Slice(), w.literalEncoding.codes, w.offsetEncoding.codes)
765 }
766
767 func (w *huffmanBitWriter) fillTokens() {
768 for i, v := range w.literalFreq[:literalCount] {
769 if v == 0 {
770 w.literalFreq[i] = 1
771 }
772 }
773 for i, v := range w.offsetFreq[:offsetCodeCount] {
774 if v == 0 {
775 w.offsetFreq[i] = 1
776 }
777 }
778 }
779
780 // indexTokens indexes a slice of tokens, and updates
781 // literalFreq and offsetFreq, and generates literalEncoding
782 // and offsetEncoding.
783 // The number of literal and offset tokens is returned.
784 func (w *huffmanBitWriter) indexTokens(t *tokens, alwaysEOB bool) (numLiterals, numOffsets int) {
785 //copy(w.literalFreq[:], t.litHist[:])
786 *(*[256]uint16)(w.literalFreq[:]) = t.litHist
787 //copy(w.literalFreq[256:], t.extraHist[:])
788 *(*[32]uint16)(w.literalFreq[256:]) = t.extraHist
789 w.offsetFreq = t.offHist
790
791 if t.n == 0 {
792 return
793 }
794 if alwaysEOB {
795 w.literalFreq[endBlockMarker] = 1
796 }
797
798 // get the number of literals
799 numLiterals = len(w.literalFreq)
800 for w.literalFreq[numLiterals-1] == 0 {
801 numLiterals--
802 }
803 // get the number of offsets
804 numOffsets = len(w.offsetFreq)
805 for numOffsets > 0 && w.offsetFreq[numOffsets-1] == 0 {
806 numOffsets--
807 }
808 if numOffsets == 0 {
809 // We haven't found a single match. If we want to go with the dynamic encoding,
810 // we should count at least one offset to be sure that the offset huffman tree could be encoded.
811 w.offsetFreq[0] = 1
812 numOffsets = 1
813 }
814 return
815 }
816
817 func (w *huffmanBitWriter) generate() {
818 w.literalEncoding.generate(w.literalFreq[:literalCount], 15)
819 w.offsetEncoding.generate(w.offsetFreq[:offsetCodeCount], 15)
820 }
821
822 // writeTokens writes a slice of tokens to the output.
823 // codes for literal and offset encoding must be supplied.
824 func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) {
825 if w.err != nil {
826 return
827 }
828 if len(tokens) == 0 {
829 return
830 }
831
832 // Only last token should be endBlockMarker.
833 var deferEOB bool
834 if tokens[len(tokens)-1] == endBlockMarker {
835 tokens = tokens[:len(tokens)-1]
836 deferEOB = true
837 }
838
839 // Create slices up to the next power of two to avoid bounds checks.
840 lits := leCodes[:256]
841 offs := oeCodes[:32]
842 lengths := leCodes[lengthCodesStart:]
843 lengths = lengths[:32]
844
845 // Go 1.16 LOVES having these on stack.
846 bits, nbits, nbytes := w.bits, w.nbits, w.nbytes
847
848 for _, t := range tokens {
849 if t < 256 {
850 //w.writeCode(lits[t.literal()])
851 c := lits[t]
852 bits |= c.code64() << (nbits & 63)
853 nbits += c.len()
854 if nbits >= 48 {
855 le.Store64(w.bytes[:], nbytes, bits)
856 bits >>= 48
857 nbits -= 48
858 nbytes += 6
859 if nbytes >= bufferFlushSize {
860 if w.err != nil {
861 nbytes = 0
862 return
863 }
864 _, w.err = w.writer.Write(w.bytes[:nbytes])
865 nbytes = 0
866 }
867 }
868 continue
869 }
870
871 // Write the length
872 length := t.length()
873 lengthCode := lengthCode(length) & 31
874 if false {
875 w.writeCode(lengths[lengthCode])
876 } else {
877 // inlined
878 c := lengths[lengthCode]
879 bits |= c.code64() << (nbits & 63)
880 nbits += c.len()
881 if nbits >= 48 {
882 le.Store64(w.bytes[:], nbytes, bits)
883 bits >>= 48
884 nbits -= 48
885 nbytes += 6
886 if nbytes >= bufferFlushSize {
887 if w.err != nil {
888 nbytes = 0
889 return
890 }
891 _, w.err = w.writer.Write(w.bytes[:nbytes])
892 nbytes = 0
893 }
894 }
895 }
896
897 if lengthCode >= lengthExtraBitsMinCode {
898 extraLengthBits := lengthExtraBits[lengthCode]
899 //w.writeBits(extraLength, extraLengthBits)
900 extraLength := int32(length - lengthBase[lengthCode])
901 bits |= uint64(extraLength) << (nbits & 63)
902 nbits += extraLengthBits
903 if nbits >= 48 {
904 le.Store64(w.bytes[:], nbytes, bits)
905 bits >>= 48
906 nbits -= 48
907 nbytes += 6
908 if nbytes >= bufferFlushSize {
909 if w.err != nil {
910 nbytes = 0
911 return
912 }
913 _, w.err = w.writer.Write(w.bytes[:nbytes])
914 nbytes = 0
915 }
916 }
917 }
918 // Write the offset
919 offset := t.offset()
920 offsetCode := (offset >> 16) & 31
921 if false {
922 w.writeCode(offs[offsetCode])
923 } else {
924 // inlined
925 c := offs[offsetCode]
926 bits |= c.code64() << (nbits & 63)
927 nbits += c.len()
928 if nbits >= 48 {
929 le.Store64(w.bytes[:], nbytes, bits)
930 bits >>= 48
931 nbits -= 48
932 nbytes += 6
933 if nbytes >= bufferFlushSize {
934 if w.err != nil {
935 nbytes = 0
936 return
937 }
938 _, w.err = w.writer.Write(w.bytes[:nbytes])
939 nbytes = 0
940 }
941 }
942 }
943
944 if offsetCode >= offsetExtraBitsMinCode {
945 offsetComb := offsetCombined[offsetCode]
946 //w.writeBits(extraOffset, extraOffsetBits)
947 bits |= uint64((offset-(offsetComb>>8))&matchOffsetOnlyMask) << (nbits & 63)
948 nbits += uint8(offsetComb)
949 if nbits >= 48 {
950 le.Store64(w.bytes[:], nbytes, bits)
951 bits >>= 48
952 nbits -= 48
953 nbytes += 6
954 if nbytes >= bufferFlushSize {
955 if w.err != nil {
956 nbytes = 0
957 return
958 }
959 _, w.err = w.writer.Write(w.bytes[:nbytes])
960 nbytes = 0
961 }
962 }
963 }
964 }
965 // Restore...
966 w.bits, w.nbits, w.nbytes = bits, nbits, nbytes
967
968 if deferEOB {
969 w.writeCode(leCodes[endBlockMarker])
970 }
971 }
972
973 // huffOffset is a static offset encoder used for huffman only encoding.
974 // It can be reused since we will not be encoding offset values.
975 var huffOffset *huffmanEncoder
976
977 func init() {
978 w := newHuffmanBitWriter(nil)
979 w.offsetFreq[0] = 1
980 huffOffset = newHuffmanEncoder(offsetCodeCount)
981 huffOffset.generate(w.offsetFreq[:offsetCodeCount], 15)
982 }
983
984 // writeBlockHuff encodes a block of bytes as either
985 // Huffman encoded literals or uncompressed bytes if the
986 // results only gains very little from compression.
987 func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) {
988 if w.err != nil {
989 return
990 }
991
992 // Clear histogram
993 for i := range w.literalFreq[:] {
994 w.literalFreq[i] = 0
995 }
996 if !w.lastHuffMan {
997 for i := range w.offsetFreq[:] {
998 w.offsetFreq[i] = 0
999 }
1000 }
1001
1002 const numLiterals = endBlockMarker + 1
1003 const numOffsets = 1
1004
1005 // Add everything as literals
1006 // We have to estimate the header size.
1007 // Assume header is around 70 bytes:
1008 // https://stackoverflow.com/a/25454430
1009 const guessHeaderSizeBits = 70 * 8
1010 histogram(input, w.literalFreq[:numLiterals])
1011 ssize, storable := w.storedSize(input)
1012 if storable && len(input) > 1024 {
1013 // Quick check for incompressible content.
1014 abs := float64(0)
1015 avg := float64(len(input)) / 256
1016 max := float64(len(input) * 2)
1017 for _, v := range w.literalFreq[:256] {
1018 diff := float64(v) - avg
1019 abs += diff * diff
1020 if abs > max {
1021 break
1022 }
1023 }
1024 if abs < max {
1025 if debugDeflate {
1026 fmt.Println("stored", abs, "<", max)
1027 }
1028 // No chance we can compress this...
1029 w.writeStoredHeader(len(input), eof)
1030 w.writeBytes(input)
1031 return
1032 }
1033 }
1034 w.literalFreq[endBlockMarker] = 1
1035 w.tmpLitEncoding.generate(w.literalFreq[:numLiterals], 15)
1036 estBits := w.tmpLitEncoding.canReuseBits(w.literalFreq[:numLiterals])
1037 if estBits < math.MaxInt32 {
1038 estBits += w.lastHeader
1039 if w.lastHeader == 0 {
1040 estBits += guessHeaderSizeBits
1041 }
1042 estBits += estBits >> w.logNewTablePenalty
1043 }
1044
1045 // Store bytes, if we don't get a reasonable improvement.
1046 if storable && ssize <= estBits {
1047 if debugDeflate {
1048 fmt.Println("stored,", ssize, "<=", estBits)
1049 }
1050 w.writeStoredHeader(len(input), eof)
1051 w.writeBytes(input)
1052 return
1053 }
1054
1055 if w.lastHeader > 0 {
1056 reuseSize := w.literalEncoding.canReuseBits(w.literalFreq[:256])
1057
1058 if estBits < reuseSize {
1059 if debugDeflate {
1060 fmt.Println("NOT reusing, reuse:", reuseSize/8, "> new:", estBits/8, "header est:", w.lastHeader/8, "bytes")
1061 }
1062 // We owe an EOB
1063 w.writeCode(w.literalEncoding.codes[endBlockMarker])
1064 w.lastHeader = 0
1065 } else if debugDeflate {
1066 fmt.Println("reusing, reuse:", reuseSize/8, "> new:", estBits/8, "- header est:", w.lastHeader/8)
1067 }
1068 }
1069
1070 count := 0
1071 if w.lastHeader == 0 {
1072 // Use the temp encoding, so swap.
1073 w.literalEncoding, w.tmpLitEncoding = w.tmpLitEncoding, w.literalEncoding
1074 // Generate codegen and codegenFrequencies, which indicates how to encode
1075 // the literalEncoding and the offsetEncoding.
1076 w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, huffOffset)
1077 w.codegenEncoding.generate(w.codegenFreq[:], 7)
1078 numCodegens := w.codegens()
1079
1080 // Huffman.
1081 w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
1082 w.lastHuffMan = true
1083 w.lastHeader, _ = w.headerSize()
1084 if debugDeflate {
1085 count += w.lastHeader
1086 fmt.Println("header:", count/8)
1087 }
1088 }
1089
1090 encoding := w.literalEncoding.codes[:256]
1091 // Go 1.16 LOVES having these on stack. At least 1.5x the speed.
1092 bits, nbits, nbytes := w.bits, w.nbits, w.nbytes
1093
1094 if debugDeflate {
1095 count -= int(nbytes)*8 + int(nbits)
1096 }
1097 // Unroll, write 3 codes/loop.
1098 // Fastest number of unrolls.
1099 for len(input) > 3 {
1100 // We must have at least 48 bits free.
1101 if nbits >= 8 {
1102 n := nbits >> 3
1103 le.Store64(w.bytes[:], nbytes, bits)
1104 bits >>= (n * 8) & 63
1105 nbits -= n * 8
1106 nbytes += n
1107 }
1108 if nbytes >= bufferFlushSize {
1109 if w.err != nil {
1110 nbytes = 0
1111 return
1112 }
1113 if debugDeflate {
1114 count += int(nbytes) * 8
1115 }
1116 _, w.err = w.writer.Write(w.bytes[:nbytes])
1117 nbytes = 0
1118 }
1119 a, b := encoding[input[0]], encoding[input[1]]
1120 bits |= a.code64() << (nbits & 63)
1121 bits |= b.code64() << ((nbits + a.len()) & 63)
1122 c := encoding[input[2]]
1123 nbits += b.len() + a.len()
1124 bits |= c.code64() << (nbits & 63)
1125 nbits += c.len()
1126 input = input[3:]
1127 }
1128
1129 // Remaining...
1130 for _, t := range input {
1131 if nbits >= 48 {
1132 le.Store64(w.bytes[:], nbytes, bits)
1133 bits >>= 48
1134 nbits -= 48
1135 nbytes += 6
1136 if nbytes >= bufferFlushSize {
1137 if w.err != nil {
1138 nbytes = 0
1139 return
1140 }
1141 if debugDeflate {
1142 count += int(nbytes) * 8
1143 }
1144 _, w.err = w.writer.Write(w.bytes[:nbytes])
1145 nbytes = 0
1146 }
1147 }
1148 // Bitwriting inlined, ~30% speedup
1149 c := encoding[t]
1150 bits |= c.code64() << (nbits & 63)
1151
1152 nbits += c.len()
1153 if debugDeflate {
1154 count += int(c.len())
1155 }
1156 }
1157 // Restore...
1158 w.bits, w.nbits, w.nbytes = bits, nbits, nbytes
1159
1160 if debugDeflate {
1161 nb := count + int(nbytes)*8 + int(nbits)
1162 fmt.Println("wrote", nb, "bits,", nb/8, "bytes.")
1163 }
1164 // Flush if needed to have space.
1165 if w.nbits >= 48 {
1166 w.writeOutBits()
1167 }
1168
1169 if eof || sync {
1170 w.writeCode(w.literalEncoding.codes[endBlockMarker])
1171 w.lastHeader = 0
1172 w.lastHuffMan = false
1173 }
1174 }