blob: 9d9151a0efdb0dcf87193ec712b209764e869e25 [file] [log] [blame]
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +00001// Copyright 2019+ Klaus Post. All rights reserved.
2// License information can be found in the LICENSE file.
3// Based on work by Yann Collet, released under BSD License.
4
5package zstd
6
7import (
8 "errors"
9 "fmt"
10 "math"
11 "math/bits"
12
13 "github.com/klauspost/compress/huff0"
14)
15
16type blockEnc struct {
17 size int
18 literals []byte
19 sequences []seq
20 coders seqCoders
21 litEnc *huff0.Scratch
22 wr bitWriter
23
24 extraLits int
25 last bool
26
27 output []byte
28 recentOffsets [3]uint32
29 prevRecentOffsets [3]uint32
30}
31
32// init should be used once the block has been created.
33// If called more than once, the effect is the same as calling reset.
34func (b *blockEnc) init() {
35 if cap(b.literals) < maxCompressedLiteralSize {
36 b.literals = make([]byte, 0, maxCompressedLiteralSize)
37 }
38 const defSeqs = 200
39 b.literals = b.literals[:0]
40 if cap(b.sequences) < defSeqs {
41 b.sequences = make([]seq, 0, defSeqs)
42 }
43 if cap(b.output) < maxCompressedBlockSize {
44 b.output = make([]byte, 0, maxCompressedBlockSize)
45 }
46 if b.coders.mlEnc == nil {
47 b.coders.mlEnc = &fseEncoder{}
48 b.coders.mlPrev = &fseEncoder{}
49 b.coders.ofEnc = &fseEncoder{}
50 b.coders.ofPrev = &fseEncoder{}
51 b.coders.llEnc = &fseEncoder{}
52 b.coders.llPrev = &fseEncoder{}
53 }
54 b.litEnc = &huff0.Scratch{}
55 b.reset(nil)
56}
57
58// initNewEncode can be used to reset offsets and encoders to the initial state.
59func (b *blockEnc) initNewEncode() {
60 b.recentOffsets = [3]uint32{1, 4, 8}
61 b.litEnc.Reuse = huff0.ReusePolicyNone
62 b.coders.setPrev(nil, nil, nil)
63}
64
65// reset will reset the block for a new encode, but in the same stream,
66// meaning that state will be carried over, but the block content is reset.
67// If a previous block is provided, the recent offsets are carried over.
68func (b *blockEnc) reset(prev *blockEnc) {
69 b.extraLits = 0
70 b.literals = b.literals[:0]
71 b.size = 0
72 b.sequences = b.sequences[:0]
73 b.output = b.output[:0]
74 b.last = false
75 if prev != nil {
76 b.recentOffsets = prev.prevRecentOffsets
77 }
78}
79
80// reset will reset the block for a new encode, but in the same stream,
81// meaning that state will be carried over, but the block content is reset.
82// If a previous block is provided, the recent offsets are carried over.
83func (b *blockEnc) swapEncoders(prev *blockEnc) {
84 b.coders.swap(&prev.coders)
85 b.litEnc, prev.litEnc = prev.litEnc, b.litEnc
86}
87
88// blockHeader contains the information for a block header.
89type blockHeader uint32
90
91// setLast sets the 'last' indicator on a block.
92func (h *blockHeader) setLast(b bool) {
93 if b {
94 *h = *h | 1
95 } else {
96 const mask = (1 << 24) - 2
97 *h = *h & mask
98 }
99}
100
101// setSize will store the compressed size of a block.
102func (h *blockHeader) setSize(v uint32) {
103 const mask = 7
104 *h = (*h)&mask | blockHeader(v<<3)
105}
106
107// setType sets the block type.
108func (h *blockHeader) setType(t blockType) {
109 const mask = 1 | (((1 << 24) - 1) ^ 7)
110 *h = (*h & mask) | blockHeader(t<<1)
111}
112
113// appendTo will append the block header to a slice.
114func (h blockHeader) appendTo(b []byte) []byte {
115 return append(b, uint8(h), uint8(h>>8), uint8(h>>16))
116}
117
118// String returns a string representation of the block.
119func (h blockHeader) String() string {
120 return fmt.Sprintf("Type: %d, Size: %d, Last:%t", (h>>1)&3, h>>3, h&1 == 1)
121}
122
123// literalsHeader contains literals header information.
124type literalsHeader uint64
125
126// setType can be used to set the type of literal block.
127func (h *literalsHeader) setType(t literalsBlockType) {
128 const mask = math.MaxUint64 - 3
129 *h = (*h & mask) | literalsHeader(t)
130}
131
132// setSize can be used to set a single size, for uncompressed and RLE content.
133func (h *literalsHeader) setSize(regenLen int) {
134 inBits := bits.Len32(uint32(regenLen))
135 // Only retain 2 bits
136 const mask = 3
137 lh := uint64(*h & mask)
138 switch {
139 case inBits < 5:
140 lh |= (uint64(regenLen) << 3) | (1 << 60)
141 if debug {
142 got := int(lh>>3) & 0xff
143 if got != regenLen {
144 panic(fmt.Sprint("litRegenSize = ", regenLen, "(want) != ", got, "(got)"))
145 }
146 }
147 case inBits < 12:
148 lh |= (1 << 2) | (uint64(regenLen) << 4) | (2 << 60)
149 case inBits < 20:
150 lh |= (3 << 2) | (uint64(regenLen) << 4) | (3 << 60)
151 default:
152 panic(fmt.Errorf("internal error: block too big (%d)", regenLen))
153 }
154 *h = literalsHeader(lh)
155}
156
157// setSizes will set the size of a compressed literals section and the input length.
158func (h *literalsHeader) setSizes(compLen, inLen int, single bool) {
159 compBits, inBits := bits.Len32(uint32(compLen)), bits.Len32(uint32(inLen))
160 // Only retain 2 bits
161 const mask = 3
162 lh := uint64(*h & mask)
163 switch {
164 case compBits <= 10 && inBits <= 10:
165 if !single {
166 lh |= 1 << 2
167 }
168 lh |= (uint64(inLen) << 4) | (uint64(compLen) << (10 + 4)) | (3 << 60)
169 if debug {
170 const mmask = (1 << 24) - 1
171 n := (lh >> 4) & mmask
172 if int(n&1023) != inLen {
173 panic(fmt.Sprint("regensize:", int(n&1023), "!=", inLen, inBits))
174 }
175 if int(n>>10) != compLen {
176 panic(fmt.Sprint("compsize:", int(n>>10), "!=", compLen, compBits))
177 }
178 }
179 case compBits <= 14 && inBits <= 14:
180 lh |= (2 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (14 + 4)) | (4 << 60)
181 if single {
182 panic("single stream used with more than 10 bits length.")
183 }
184 case compBits <= 18 && inBits <= 18:
185 lh |= (3 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (18 + 4)) | (5 << 60)
186 if single {
187 panic("single stream used with more than 10 bits length.")
188 }
189 default:
190 panic("internal error: block too big")
191 }
192 *h = literalsHeader(lh)
193}
194
195// appendTo will append the literals header to a byte slice.
196func (h literalsHeader) appendTo(b []byte) []byte {
197 size := uint8(h >> 60)
198 switch size {
199 case 1:
200 b = append(b, uint8(h))
201 case 2:
202 b = append(b, uint8(h), uint8(h>>8))
203 case 3:
204 b = append(b, uint8(h), uint8(h>>8), uint8(h>>16))
205 case 4:
206 b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24))
207 case 5:
208 b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24), uint8(h>>32))
209 default:
210 panic(fmt.Errorf("internal error: literalsHeader has invalid size (%d)", size))
211 }
212 return b
213}
214
215// size returns the output size with currently set values.
216func (h literalsHeader) size() int {
217 return int(h >> 60)
218}
219
220func (h literalsHeader) String() string {
221 return fmt.Sprintf("Type: %d, SizeFormat: %d, Size: 0x%d, Bytes:%d", literalsBlockType(h&3), (h>>2)&3, h&((1<<60)-1)>>4, h>>60)
222}
223
224// pushOffsets will push the recent offsets to the backup store.
225func (b *blockEnc) pushOffsets() {
226 b.prevRecentOffsets = b.recentOffsets
227}
228
229// pushOffsets will push the recent offsets to the backup store.
230func (b *blockEnc) popOffsets() {
231 b.recentOffsets = b.prevRecentOffsets
232}
233
234// matchOffset will adjust recent offsets and return the adjusted one,
235// if it matches a previous offset.
236func (b *blockEnc) matchOffset(offset, lits uint32) uint32 {
237 // Check if offset is one of the recent offsets.
238 // Adjusts the output offset accordingly.
239 // Gives a tiny bit of compression, typically around 1%.
240 if true {
241 if lits > 0 {
242 switch offset {
243 case b.recentOffsets[0]:
244 offset = 1
245 case b.recentOffsets[1]:
246 b.recentOffsets[1] = b.recentOffsets[0]
247 b.recentOffsets[0] = offset
248 offset = 2
249 case b.recentOffsets[2]:
250 b.recentOffsets[2] = b.recentOffsets[1]
251 b.recentOffsets[1] = b.recentOffsets[0]
252 b.recentOffsets[0] = offset
253 offset = 3
254 default:
255 b.recentOffsets[2] = b.recentOffsets[1]
256 b.recentOffsets[1] = b.recentOffsets[0]
257 b.recentOffsets[0] = offset
258 offset += 3
259 }
260 } else {
261 switch offset {
262 case b.recentOffsets[1]:
263 b.recentOffsets[1] = b.recentOffsets[0]
264 b.recentOffsets[0] = offset
265 offset = 1
266 case b.recentOffsets[2]:
267 b.recentOffsets[2] = b.recentOffsets[1]
268 b.recentOffsets[1] = b.recentOffsets[0]
269 b.recentOffsets[0] = offset
270 offset = 2
271 case b.recentOffsets[0] - 1:
272 b.recentOffsets[2] = b.recentOffsets[1]
273 b.recentOffsets[1] = b.recentOffsets[0]
274 b.recentOffsets[0] = offset
275 offset = 3
276 default:
277 b.recentOffsets[2] = b.recentOffsets[1]
278 b.recentOffsets[1] = b.recentOffsets[0]
279 b.recentOffsets[0] = offset
280 offset += 3
281 }
282 }
283 } else {
284 offset += 3
285 }
286 return offset
287}
288
289// encodeRaw can be used to set the output to a raw representation of supplied bytes.
290func (b *blockEnc) encodeRaw(a []byte) {
291 var bh blockHeader
292 bh.setLast(b.last)
293 bh.setSize(uint32(len(a)))
294 bh.setType(blockTypeRaw)
295 b.output = bh.appendTo(b.output[:0])
296 b.output = append(b.output, a...)
297 if debug {
298 println("Adding RAW block, length", len(a))
299 }
300}
301
302// encodeLits can be used if the block is only litLen.
303func (b *blockEnc) encodeLits() error {
304 var bh blockHeader
305 bh.setLast(b.last)
306 bh.setSize(uint32(len(b.literals)))
307
308 // Don't compress extremely small blocks
309 if len(b.literals) < 32 {
310 if debug {
311 println("Adding RAW block, length", len(b.literals))
312 }
313 bh.setType(blockTypeRaw)
314 b.output = bh.appendTo(b.output)
315 b.output = append(b.output, b.literals...)
316 return nil
317 }
318
319 var (
320 out []byte
321 reUsed, single bool
322 err error
323 )
324 if len(b.literals) >= 1024 {
325 // Use 4 Streams.
326 out, reUsed, err = huff0.Compress4X(b.literals, b.litEnc)
327 if len(out) > len(b.literals)-len(b.literals)>>4 {
328 // Bail out of compression is too little.
329 err = huff0.ErrIncompressible
330 }
331 } else if len(b.literals) > 32 {
332 // Use 1 stream
333 single = true
334 out, reUsed, err = huff0.Compress1X(b.literals, b.litEnc)
335 if len(out) > len(b.literals)-len(b.literals)>>4 {
336 // Bail out of compression is too little.
337 err = huff0.ErrIncompressible
338 }
339 } else {
340 err = huff0.ErrIncompressible
341 }
342
343 switch err {
344 case huff0.ErrIncompressible:
345 if debug {
346 println("Adding RAW block, length", len(b.literals))
347 }
348 bh.setType(blockTypeRaw)
349 b.output = bh.appendTo(b.output)
350 b.output = append(b.output, b.literals...)
351 return nil
352 case huff0.ErrUseRLE:
353 if debug {
354 println("Adding RLE block, length", len(b.literals))
355 }
356 bh.setType(blockTypeRLE)
357 b.output = bh.appendTo(b.output)
358 b.output = append(b.output, b.literals[0])
359 return nil
360 default:
361 return err
362 case nil:
363 }
364 // Compressed...
365 // Now, allow reuse
366 b.litEnc.Reuse = huff0.ReusePolicyAllow
367 bh.setType(blockTypeCompressed)
368 var lh literalsHeader
369 if reUsed {
370 if debug {
371 println("Reused tree, compressed to", len(out))
372 }
373 lh.setType(literalsBlockTreeless)
374 } else {
375 if debug {
376 println("New tree, compressed to", len(out), "tree size:", len(b.litEnc.OutTable))
377 }
378 lh.setType(literalsBlockCompressed)
379 }
380 // Set sizes
381 lh.setSizes(len(out), len(b.literals), single)
382 bh.setSize(uint32(len(out) + lh.size() + 1))
383
384 // Write block headers.
385 b.output = bh.appendTo(b.output)
386 b.output = lh.appendTo(b.output)
387 // Add compressed data.
388 b.output = append(b.output, out...)
389 // No sequences.
390 b.output = append(b.output, 0)
391 return nil
392}
393
394// encode will encode the block and put the output in b.output.
395func (b *blockEnc) encode() error {
396 if len(b.sequences) == 0 {
397 return b.encodeLits()
398 }
399 // We want some difference
400 if len(b.literals) > (b.size - (b.size >> 5)) {
401 return errIncompressible
402 }
403
404 var bh blockHeader
405 var lh literalsHeader
406 bh.setLast(b.last)
407 bh.setType(blockTypeCompressed)
408 b.output = bh.appendTo(b.output)
409
410 var (
411 out []byte
412 reUsed, single bool
413 err error
414 )
415 if len(b.literals) >= 1024 {
416 // Use 4 Streams.
417 out, reUsed, err = huff0.Compress4X(b.literals, b.litEnc)
418 if len(out) > len(b.literals)-len(b.literals)>>4 {
419 err = huff0.ErrIncompressible
420 }
421 } else if len(b.literals) > 32 {
422 // Use 1 stream
423 single = true
424 out, reUsed, err = huff0.Compress1X(b.literals, b.litEnc)
425 if len(out) > len(b.literals)-len(b.literals)>>4 {
426 err = huff0.ErrIncompressible
427 }
428 } else {
429 err = huff0.ErrIncompressible
430 }
431 switch err {
432 case huff0.ErrIncompressible:
433 lh.setType(literalsBlockRaw)
434 lh.setSize(len(b.literals))
435 b.output = lh.appendTo(b.output)
436 b.output = append(b.output, b.literals...)
437 if debug {
438 println("Adding literals RAW, length", len(b.literals))
439 }
440 case huff0.ErrUseRLE:
441 lh.setType(literalsBlockRLE)
442 lh.setSize(len(b.literals))
443 b.output = lh.appendTo(b.output)
444 b.output = append(b.output, b.literals[0])
445 if debug {
446 println("Adding literals RLE")
447 }
448 default:
449 if debug {
450 println("Adding literals ERROR:", err)
451 }
452 return err
453 case nil:
454 // Compressed litLen...
455 if reUsed {
456 if debug {
457 println("reused tree")
458 }
459 lh.setType(literalsBlockTreeless)
460 } else {
461 if debug {
462 println("new tree, size:", len(b.litEnc.OutTable))
463 }
464 lh.setType(literalsBlockCompressed)
465 if debug {
466 _, _, err := huff0.ReadTable(out, nil)
467 if err != nil {
468 panic(err)
469 }
470 }
471 }
472 lh.setSizes(len(out), len(b.literals), single)
473 if debug {
474 printf("Compressed %d literals to %d bytes", len(b.literals), len(out))
475 println("Adding literal header:", lh)
476 }
477 b.output = lh.appendTo(b.output)
478 b.output = append(b.output, out...)
479 b.litEnc.Reuse = huff0.ReusePolicyAllow
480 if debug {
481 println("Adding literals compressed")
482 }
483 }
484 // Sequence compression
485
486 // Write the number of sequences
487 switch {
488 case len(b.sequences) < 128:
489 b.output = append(b.output, uint8(len(b.sequences)))
490 case len(b.sequences) < 0x7f00: // TODO: this could be wrong
491 n := len(b.sequences)
492 b.output = append(b.output, 128+uint8(n>>8), uint8(n))
493 default:
494 n := len(b.sequences) - 0x7f00
495 b.output = append(b.output, 255, uint8(n), uint8(n>>8))
496 }
497 if debug {
498 println("Encoding", len(b.sequences), "sequences")
499 }
500 b.genCodes()
501 llEnc := b.coders.llEnc
502 ofEnc := b.coders.ofEnc
503 mlEnc := b.coders.mlEnc
504 err = llEnc.normalizeCount(len(b.sequences))
505 if err != nil {
506 return err
507 }
508 err = ofEnc.normalizeCount(len(b.sequences))
509 if err != nil {
510 return err
511 }
512 err = mlEnc.normalizeCount(len(b.sequences))
513 if err != nil {
514 return err
515 }
516
517 // Choose the best compression mode for each type.
518 // Will evaluate the new vs predefined and previous.
519 chooseComp := func(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) {
520 // See if predefined/previous is better
521 hist := cur.count[:cur.symbolLen]
522 nSize := cur.approxSize(hist) + cur.maxHeaderSize()
523 predefSize := preDef.approxSize(hist)
524 prevSize := prev.approxSize(hist)
525
526 // Add a small penalty for new encoders.
527 // Don't bother with extremely small (<2 byte gains).
528 nSize = nSize + (nSize+2*8*16)>>4
529 switch {
530 case predefSize <= prevSize && predefSize <= nSize || forcePreDef:
531 if debug {
532 println("Using predefined", predefSize>>3, "<=", nSize>>3)
533 }
534 return preDef, compModePredefined
535 case prevSize <= nSize:
536 if debug {
537 println("Using previous", prevSize>>3, "<=", nSize>>3)
538 }
539 return prev, compModeRepeat
540 default:
541 if debug {
542 println("Using new, predef", predefSize>>3, ". previous:", prevSize>>3, ">", nSize>>3, "header max:", cur.maxHeaderSize()>>3, "bytes")
543 println("tl:", cur.actualTableLog, "symbolLen:", cur.symbolLen, "norm:", cur.norm[:cur.symbolLen], "hist", cur.count[:cur.symbolLen])
544 }
545 return cur, compModeFSE
546 }
547 }
548
549 // Write compression mode
550 var mode uint8
551 if llEnc.useRLE {
552 mode |= uint8(compModeRLE) << 6
553 llEnc.setRLE(b.sequences[0].llCode)
554 if debug {
555 println("llEnc.useRLE")
556 }
557 } else {
558 var m seqCompMode
559 llEnc, m = chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths])
560 mode |= uint8(m) << 6
561 }
562 if ofEnc.useRLE {
563 mode |= uint8(compModeRLE) << 4
564 ofEnc.setRLE(b.sequences[0].ofCode)
565 if debug {
566 println("ofEnc.useRLE")
567 }
568 } else {
569 var m seqCompMode
570 ofEnc, m = chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets])
571 mode |= uint8(m) << 4
572 }
573
574 if mlEnc.useRLE {
575 mode |= uint8(compModeRLE) << 2
576 mlEnc.setRLE(b.sequences[0].mlCode)
577 if debug {
578 println("mlEnc.useRLE, code: ", b.sequences[0].mlCode, "value", b.sequences[0].matchLen)
579 }
580 } else {
581 var m seqCompMode
582 mlEnc, m = chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths])
583 mode |= uint8(m) << 2
584 }
585 b.output = append(b.output, mode)
586 if debug {
587 printf("Compression modes: 0b%b", mode)
588 }
589 b.output, err = llEnc.writeCount(b.output)
590 if err != nil {
591 return err
592 }
593 start := len(b.output)
594 b.output, err = ofEnc.writeCount(b.output)
595 if err != nil {
596 return err
597 }
598 if false {
599 println("block:", b.output[start:], "tablelog", ofEnc.actualTableLog, "maxcount:", ofEnc.maxCount)
600 fmt.Printf("selected TableLog: %d, Symbol length: %d\n", ofEnc.actualTableLog, ofEnc.symbolLen)
601 for i, v := range ofEnc.norm[:ofEnc.symbolLen] {
602 fmt.Printf("%3d: %5d -> %4d \n", i, ofEnc.count[i], v)
603 }
604 }
605 b.output, err = mlEnc.writeCount(b.output)
606 if err != nil {
607 return err
608 }
609
610 // Maybe in block?
611 wr := &b.wr
612 wr.reset(b.output)
613
614 var ll, of, ml cState
615
616 // Current sequence
617 seq := len(b.sequences) - 1
618 s := b.sequences[seq]
619 llEnc.setBits(llBitsTable[:])
620 mlEnc.setBits(mlBitsTable[:])
621 ofEnc.setBits(nil)
622
623 llTT, ofTT, mlTT := llEnc.ct.symbolTT[:256], ofEnc.ct.symbolTT[:256], mlEnc.ct.symbolTT[:256]
624
625 // We have 3 bounds checks here (and in the loop).
626 // Since we are iterating backwards it is kinda hard to avoid.
627 llB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode]
628 ll.init(wr, &llEnc.ct, llB)
629 of.init(wr, &ofEnc.ct, ofB)
630 wr.flush32()
631 ml.init(wr, &mlEnc.ct, mlB)
632
633 // Each of these lookups also generates a bounds check.
634 wr.addBits32NC(s.litLen, llB.outBits)
635 wr.addBits32NC(s.matchLen, mlB.outBits)
636 wr.flush32()
637 wr.addBits32NC(s.offset, ofB.outBits)
638 if debugSequences {
639 println("Encoded seq", seq, s, "codes:", s.llCode, s.mlCode, s.ofCode, "states:", ll.state, ml.state, of.state, "bits:", llB, mlB, ofB)
640 }
641 seq--
642 if llEnc.maxBits+mlEnc.maxBits+ofEnc.maxBits <= 32 {
643 // No need to flush (common)
644 for seq >= 0 {
645 s = b.sequences[seq]
646 wr.flush32()
647 llB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode]
648 // tabelog max is 8 for all.
649 of.encode(ofB)
650 ml.encode(mlB)
651 ll.encode(llB)
652 wr.flush32()
653
654 // We checked that all can stay within 32 bits
655 wr.addBits32NC(s.litLen, llB.outBits)
656 wr.addBits32NC(s.matchLen, mlB.outBits)
657 wr.addBits32NC(s.offset, ofB.outBits)
658
659 if debugSequences {
660 println("Encoded seq", seq, s)
661 }
662
663 seq--
664 }
665 } else {
666 for seq >= 0 {
667 s = b.sequences[seq]
668 wr.flush32()
669 llB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode]
670 // tabelog max is below 8 for each.
671 of.encode(ofB)
672 ml.encode(mlB)
673 ll.encode(llB)
674 wr.flush32()
675
676 // ml+ll = max 32 bits total
677 wr.addBits32NC(s.litLen, llB.outBits)
678 wr.addBits32NC(s.matchLen, mlB.outBits)
679 wr.flush32()
680 wr.addBits32NC(s.offset, ofB.outBits)
681
682 if debugSequences {
683 println("Encoded seq", seq, s)
684 }
685
686 seq--
687 }
688 }
689 ml.flush(mlEnc.actualTableLog)
690 of.flush(ofEnc.actualTableLog)
691 ll.flush(llEnc.actualTableLog)
692 err = wr.close()
693 if err != nil {
694 return err
695 }
696 b.output = wr.out
697
698 if len(b.output)-3 >= b.size {
699 // Maybe even add a bigger margin.
700 b.litEnc.Reuse = huff0.ReusePolicyNone
701 return errIncompressible
702 }
703
704 // Size is output minus block header.
705 bh.setSize(uint32(len(b.output)) - 3)
706 if debug {
707 println("Rewriting block header", bh)
708 }
709 _ = bh.appendTo(b.output[:0])
710 b.coders.setPrev(llEnc, mlEnc, ofEnc)
711 return nil
712}
713
714var errIncompressible = errors.New("uncompressible")
715
716func (b *blockEnc) genCodes() {
717 if len(b.sequences) == 0 {
718 // nothing to do
719 return
720 }
721
722 if len(b.sequences) > math.MaxUint16 {
723 panic("can only encode up to 64K sequences")
724 }
725 // No bounds checks after here:
726 llH := b.coders.llEnc.Histogram()[:256]
727 ofH := b.coders.ofEnc.Histogram()[:256]
728 mlH := b.coders.mlEnc.Histogram()[:256]
729 for i := range llH {
730 llH[i] = 0
731 }
732 for i := range ofH {
733 ofH[i] = 0
734 }
735 for i := range mlH {
736 mlH[i] = 0
737 }
738
739 var llMax, ofMax, mlMax uint8
740 for i, seq := range b.sequences {
741 v := llCode(seq.litLen)
742 seq.llCode = v
743 llH[v]++
744 if v > llMax {
745 llMax = v
746 }
747
748 v = ofCode(seq.offset)
749 seq.ofCode = v
750 ofH[v]++
751 if v > ofMax {
752 ofMax = v
753 }
754
755 v = mlCode(seq.matchLen)
756 seq.mlCode = v
757 mlH[v]++
758 if v > mlMax {
759 mlMax = v
760 if debug && mlMax > maxMatchLengthSymbol {
761 panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d), matchlen: %d", mlMax, seq.matchLen))
762 }
763 }
764 b.sequences[i] = seq
765 }
766 maxCount := func(a []uint32) int {
767 var max uint32
768 for _, v := range a {
769 if v > max {
770 max = v
771 }
772 }
773 return int(max)
774 }
775 if mlMax > maxMatchLengthSymbol {
776 panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d)", mlMax))
777 }
778 if ofMax > maxOffsetBits {
779 panic(fmt.Errorf("ofMax > maxOffsetBits (%d)", ofMax))
780 }
781 if llMax > maxLiteralLengthSymbol {
782 panic(fmt.Errorf("llMax > maxLiteralLengthSymbol (%d)", llMax))
783 }
784
785 b.coders.mlEnc.HistogramFinished(mlMax, maxCount(mlH[:mlMax+1]))
786 b.coders.ofEnc.HistogramFinished(ofMax, maxCount(ofH[:ofMax+1]))
787 b.coders.llEnc.HistogramFinished(llMax, maxCount(llH[:llMax+1]))
788}