Debian Codegraph @

zstd/dict.go

raw
1 package zstd
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "io"
9 "math"
10 "sort"
11
12 "github.com/klauspost/compress/huff0"
13 )
14
15 type dict struct {
16 id uint32
17
18 litEnc *huff0.Scratch
19 llDec, ofDec, mlDec sequenceDec
20 offsets [3]int
21 content []byte
22 }
23
24 const dictMagic = "\x37\xa4\x30\xec"
25
26 // Maximum dictionary size for the reference implementation (1.5.3) is 2 GiB.
27 const dictMaxLength = 1 << 31
28
29 // ID returns the dictionary id or 0 if d is nil.
30 func (d *dict) ID() uint32 {
31 if d == nil {
32 return 0
33 }
34 return d.id
35 }
36
37 // ContentSize returns the dictionary content size or 0 if d is nil.
38 func (d *dict) ContentSize() int {
39 if d == nil {
40 return 0
41 }
42 return len(d.content)
43 }
44
45 // Content returns the dictionary content.
46 func (d *dict) Content() []byte {
47 if d == nil {
48 return nil
49 }
50 return d.content
51 }
52
53 // Offsets returns the initial offsets.
54 func (d *dict) Offsets() [3]int {
55 if d == nil {
56 return [3]int{}
57 }
58 return d.offsets
59 }
60
61 // LitEncoder returns the literal encoder.
62 func (d *dict) LitEncoder() *huff0.Scratch {
63 if d == nil {
64 return nil
65 }
66 return d.litEnc
67 }
68
69 // Load a dictionary as described in
70 // https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format
71 func loadDict(b []byte) (*dict, error) {
72 // Check static field size.
73 if len(b) <= 8+(3*4) {
74 return nil, io.ErrUnexpectedEOF
75 }
76 d := dict{
77 llDec: sequenceDec{fse: &fseDecoder{}},
78 ofDec: sequenceDec{fse: &fseDecoder{}},
79 mlDec: sequenceDec{fse: &fseDecoder{}},
80 }
81 if string(b[:4]) != dictMagic {
82 return nil, ErrMagicMismatch
83 }
84 d.id = binary.LittleEndian.Uint32(b[4:8])
85 if d.id == 0 {
86 return nil, errors.New("dictionaries cannot have ID 0")
87 }
88
89 // Read literal table
90 var err error
91 d.litEnc, b, err = huff0.ReadTable(b[8:], nil)
92 if err != nil {
93 return nil, fmt.Errorf("loading literal table: %w", err)
94 }
95 d.litEnc.Reuse = huff0.ReusePolicyMust
96
97 br := byteReader{
98 b: b,
99 off: 0,
100 }
101 readDec := func(i tableIndex, dec *fseDecoder) error {
102 if err := dec.readNCount(&br, uint16(maxTableSymbol[i])); err != nil {
103 return err
104 }
105 if br.overread() {
106 return io.ErrUnexpectedEOF
107 }
108 err = dec.transform(symbolTableX[i])
109 if err != nil {
110 println("Transform table error:", err)
111 return err
112 }
113 if debugDecoder || debugEncoder {
114 println("Read table ok", "symbolLen:", dec.symbolLen)
115 }
116 // Set decoders as predefined so they aren't reused.
117 dec.preDefined = true
118 return nil
119 }
120
121 if err := readDec(tableOffsets, d.ofDec.fse); err != nil {
122 return nil, err
123 }
124 if err := readDec(tableMatchLengths, d.mlDec.fse); err != nil {
125 return nil, err
126 }
127 if err := readDec(tableLiteralLengths, d.llDec.fse); err != nil {
128 return nil, err
129 }
130 if br.remain() < 12 {
131 return nil, io.ErrUnexpectedEOF
132 }
133
134 d.offsets[0] = int(br.Uint32())
135 br.advance(4)
136 d.offsets[1] = int(br.Uint32())
137 br.advance(4)
138 d.offsets[2] = int(br.Uint32())
139 br.advance(4)
140 if d.offsets[0] <= 0 || d.offsets[1] <= 0 || d.offsets[2] <= 0 {
141 return nil, errors.New("invalid offset in dictionary")
142 }
143 d.content = make([]byte, br.remain())
144 copy(d.content, br.unread())
145 if d.offsets[0] > len(d.content) || d.offsets[1] > len(d.content) || d.offsets[2] > len(d.content) {
146 return nil, fmt.Errorf("initial offset bigger than dictionary content size %d, offsets: %v", len(d.content), d.offsets)
147 }
148
149 return &d, nil
150 }
151
152 // InspectDictionary loads a zstd dictionary and provides functions to inspect the content.
153 func InspectDictionary(b []byte) (interface {
154 ID() uint32
155 ContentSize() int
156 Content() []byte
157 Offsets() [3]int
158 LitEncoder() *huff0.Scratch
159 }, error) {
160 initPredefined()
161 d, err := loadDict(b)
162 return d, err
163 }
164
165 type BuildDictOptions struct {
166 // Dictionary ID.
167 ID uint32
168
169 // Content to use to create dictionary tables.
170 Contents [][]byte
171
172 // History to use for all blocks.
173 History []byte
174
175 // Offsets to use.
176 Offsets [3]int
177
178 // CompatV155 will make the dictionary compatible with Zstd v1.5.5 and earlier.
179 // See https://github.com/facebook/zstd/issues/3724
180 CompatV155 bool
181
182 // Use the specified encoder level.
183 // The dictionary will be built using the specified encoder level,
184 // which will reflect speed and make the dictionary tailored for that level.
185 // If not set SpeedBestCompression will be used.
186 Level EncoderLevel
187
188 // DebugOut will write stats and other details here if set.
189 DebugOut io.Writer
190 }
191
192 func BuildDict(o BuildDictOptions) ([]byte, error) {
193 initPredefined()
194 hist := o.History
195 contents := o.Contents
196 debug := o.DebugOut != nil
197 println := func(args ...any) {
198 if o.DebugOut != nil {
199 fmt.Fprintln(o.DebugOut, args...)
200 }
201 }
202 printf := func(s string, args ...any) {
203 if o.DebugOut != nil {
204 fmt.Fprintf(o.DebugOut, s, args...)
205 }
206 }
207 print := func(args ...any) {
208 if o.DebugOut != nil {
209 fmt.Fprint(o.DebugOut, args...)
210 }
211 }
212
213 if int64(len(hist)) > dictMaxLength {
214 return nil, fmt.Errorf("dictionary of size %d > %d", len(hist), int64(dictMaxLength))
215 }
216 if len(hist) < 8 {
217 return nil, fmt.Errorf("dictionary of size %d < %d", len(hist), 8)
218 }
219 if len(contents) == 0 {
220 return nil, errors.New("no content provided")
221 }
222 d := dict{
223 id: o.ID,
224 litEnc: nil,
225 llDec: sequenceDec{},
226 ofDec: sequenceDec{},
227 mlDec: sequenceDec{},
228 offsets: o.Offsets,
229 content: hist,
230 }
231 block := blockEnc{lowMem: false}
232 block.init()
233 var enc encoder
234 if o.Level != 0 {
235 eOpts := encoderOptions{
236 level: o.Level,
237 blockSize: maxMatchLen,
238 windowSize: maxMatchLen,
239 dict: &d,
240 lowMem: false,
241 }
242 enc = eOpts.encoder()
243 } else {
244 o.Level = SpeedBestCompression
245 enc = encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}})
246 }
247 var (
248 remain [256]int
249 ll [256]int
250 ml [256]int
251 of [256]int
252 )
253 addValues := func(dst *[256]int, src []byte) {
254 for _, v := range src {
255 dst[v]++
256 }
257 }
258 addHist := func(dst *[256]int, src *[256]uint32) {
259 for i, v := range src {
260 dst[i] += int(v)
261 }
262 }
263 seqs := 0
264 nUsed := 0
265 litTotal := 0
266 newOffsets := make(map[uint32]int, 1000)
267 for _, b := range contents {
268 block.reset(nil)
269 if len(b) < 8 {
270 continue
271 }
272 nUsed++
273 enc.Reset(&d, true)
274 enc.Encode(&block, b)
275 addValues(&remain, block.literals)
276 litTotal += len(block.literals)
277 if len(block.sequences) == 0 {
278 continue
279 }
280 seqs += len(block.sequences)
281 block.genCodes()
282 addHist(&ll, block.coders.llEnc.Histogram())
283 addHist(&ml, block.coders.mlEnc.Histogram())
284 addHist(&of, block.coders.ofEnc.Histogram())
285 for i, seq := range block.sequences {
286 if i > 3 {
287 break
288 }
289 offset := seq.offset
290 if offset == 0 {
291 continue
292 }
293 if int(offset) >= len(o.History) {
294 continue
295 }
296 if offset > 3 {
297 newOffsets[offset-3]++
298 } else {
299 // Repeat codes reference the training Offsets. Skip unset
300 // (zero) entries so they are not ranked as real offsets.
301 prev := o.Offsets[offset-1]
302 if prev > 0 {
303 newOffsets[uint32(prev)]++
304 }
305 }
306 }
307 }
308 // Find most used offsets.
309 var sortedOffsets []uint32
310 for k := range newOffsets {
311 if k == 0 {
312 continue
313 }
314 sortedOffsets = append(sortedOffsets, k)
315 }
316 sort.Slice(sortedOffsets, func(i, j int) bool {
317 a, b := sortedOffsets[i], sortedOffsets[j]
318 ca, cb := newOffsets[a], newOffsets[b]
319 if ca == cb {
320 // Prefer the longer offset
321 return a > b
322 }
323 return ca > cb
324 })
325 if debug {
326 print("Offsets:")
327 for i, v := range sortedOffsets {
328 if i > 20 {
329 break
330 }
331 printf("[%d: %d],", v, newOffsets[v])
332 }
333 println("")
334 }
335 // Dictionary recent-offsets must be three positive values within the
336 // history. Ranked matches may be fewer (or empty when only unset
337 // repeat codes were seen), so fill remaining slots with defaults.
338 used := make(map[int]bool, 3)
339 var finalOffsets [3]int
340 nOff := 0
341 for _, v := range sortedOffsets {
342 iv := int(v)
343 if iv <= 0 || iv > len(hist) || used[iv] {
344 continue
345 }
346 finalOffsets[nOff] = iv
347 used[iv] = true
348 nOff++
349 if nOff == 3 {
350 break
351 }
352 }
353 for _, def := range []int{1, 4, 8} {
354 if nOff == 3 {
355 break
356 }
357 if def <= len(hist) && !used[def] {
358 finalOffsets[nOff] = def
359 used[def] = true
360 nOff++
361 }
362 }
363 for def := 1; nOff < 3 && def <= len(hist); def++ {
364 if !used[def] {
365 finalOffsets[nOff] = def
366 used[def] = true
367 nOff++
368 }
369 }
370 if nOff < 3 {
371 return nil, fmt.Errorf("could not determine 3 valid dictionary offsets (history size %d)", len(hist))
372 }
373 o.Offsets = finalOffsets
374 if debug {
375 println("New repeat offsets", o.Offsets)
376 }
377
378 if nUsed == 0 || seqs == 0 {
379 return nil, fmt.Errorf("%d blocks, %d sequences found", nUsed, seqs)
380 }
381 if litTotal == 0 {
382 return nil, errors.New("0 literals found")
383 }
384 if debug {
385 println("Sequences:", seqs, "Blocks:", nUsed, "Literals:", litTotal)
386 }
387 if seqs/nUsed < 512 {
388 // Use 512 as minimum.
389 nUsed = seqs / 512
390 if nUsed == 0 {
391 nUsed = 1
392 }
393 }
394 copyHist := func(dst *fseEncoder, src *[256]int) ([]byte, error) {
395 hist := dst.Histogram()
396 var maxSym uint8
397 var maxCount int
398 var fakeLength int
399 for i, v := range src {
400 if v > 0 {
401 v = v / nUsed
402 if v == 0 {
403 v = 1
404 }
405 }
406 if v > maxCount {
407 maxCount = v
408 }
409 if v != 0 {
410 maxSym = uint8(i)
411 }
412 fakeLength += v
413 hist[i] = uint32(v)
414 }
415
416 // Ensure we aren't trying to represent RLE.
417 if maxCount == fakeLength {
418 for i := range hist {
419 if uint8(i) == maxSym {
420 fakeLength++
421 maxSym++
422 hist[i+1] = 1
423 if maxSym > 1 {
424 break
425 }
426 }
427 if hist[0] == 0 {
428 fakeLength++
429 hist[i] = 1
430 if maxSym > 1 {
431 break
432 }
433 }
434 }
435 }
436
437 dst.HistogramFinished(maxSym, maxCount)
438 dst.reUsed = false
439 dst.useRLE = false
440 err := dst.normalizeCount(fakeLength)
441 if err != nil {
442 return nil, err
443 }
444 if debug {
445 println("RAW:", dst.count[:maxSym+1], "NORM:", dst.norm[:maxSym+1], "LEN:", fakeLength)
446 }
447 return dst.writeCount(nil)
448 }
449 if debug {
450 print("Literal lengths: ")
451 }
452 llTable, err := copyHist(block.coders.llEnc, &ll)
453 if err != nil {
454 return nil, err
455 }
456 if debug {
457 print("Match lengths: ")
458 }
459 mlTable, err := copyHist(block.coders.mlEnc, &ml)
460 if err != nil {
461 return nil, err
462 }
463 if debug {
464 print("Offsets: ")
465 }
466 ofTable, err := copyHist(block.coders.ofEnc, &of)
467 if err != nil {
468 return nil, err
469 }
470
471 // Literal table
472 avgSize := min(litTotal, huff0.BlockSizeMax/2)
473 huffBuff := make([]byte, 0, avgSize)
474 // Target size
475 div := max(litTotal/avgSize, 1)
476 if debug {
477 println("Huffman weights:")
478 }
479 for i, n := range remain[:] {
480 if n > 0 {
481 n = n / div
482 // Allow all entries to be represented.
483 if n == 0 {
484 n = 1
485 }
486 huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...)
487 if debug {
488 printf("[%d: %d], ", i, n)
489 }
490 }
491 }
492 if o.CompatV155 && remain[255]/div == 0 {
493 huffBuff = append(huffBuff, 255)
494 }
495 scratch := &huff0.Scratch{TableLog: 11}
496 for tries := range 255 {
497 scratch = &huff0.Scratch{TableLog: 11}
498 _, _, err = huff0.Compress1X(huffBuff, scratch)
499 if err == nil {
500 break
501 }
502 if debug {
503 printf("Try %d: Huffman error: %v\n", tries+1, err)
504 }
505 huffBuff = huffBuff[:0]
506 if tries == 250 {
507 if debug {
508 println("Huffman: Bailing out with predefined table")
509 }
510
511 // Bail out.... Just generate something
512 huffBuff = append(huffBuff, bytes.Repeat([]byte{255}, 10000)...)
513 for i := range 128 {
514 huffBuff = append(huffBuff, byte(i))
515 }
516 continue
517 }
518 if errors.Is(err, huff0.ErrIncompressible) {
519 // Try truncating least common.
520 for i, n := range remain[:] {
521 if n > 0 {
522 n = n / (div * (i + 1))
523 if n > 0 {
524 huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...)
525 }
526 }
527 }
528 if o.CompatV155 && len(huffBuff) > 0 && huffBuff[len(huffBuff)-1] != 255 {
529 huffBuff = append(huffBuff, 255)
530 }
531 if len(huffBuff) == 0 {
532 huffBuff = append(huffBuff, 0, 255)
533 }
534 }
535 if errors.Is(err, huff0.ErrUseRLE) {
536 for i, n := range remain[:] {
537 n = n / (div * (i + 1))
538 // Allow all entries to be represented.
539 if n == 0 {
540 n = 1
541 }
542 huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...)
543 }
544 }
545 }
546
547 var out bytes.Buffer
548 out.Write([]byte(dictMagic))
549 out.Write(binary.LittleEndian.AppendUint32(nil, o.ID))
550 out.Write(scratch.OutTable)
551 if debug {
552 println("huff table:", len(scratch.OutTable), "bytes")
553 println("of table:", len(ofTable), "bytes")
554 println("ml table:", len(mlTable), "bytes")
555 println("ll table:", len(llTable), "bytes")
556 }
557 out.Write(ofTable)
558 out.Write(mlTable)
559 out.Write(llTable)
560 out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[0])))
561 out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[1])))
562 out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[2])))
563 out.Write(hist)
564 if _, err := loadDict(out.Bytes()); err != nil {
565 return nil, fmt.Errorf("built dictionary failed validation: %w", err)
566 }
567 if debug {
568 i, err := InspectDictionary(out.Bytes())
569 if err != nil {
570 panic(err)
571 }
572 println("ID:", i.ID())
573 println("Content size:", i.ContentSize())
574 println("Encoder:", i.LitEncoder() != nil)
575 println("Offsets:", i.Offsets())
576 var totalSize int
577 for _, b := range contents {
578 totalSize += len(b)
579 }
580
581 encWith := func(opts ...EOption) int {
582 enc, err := NewWriter(nil, opts...)
583 if err != nil {
584 panic(err)
585 }
586 defer enc.Close()
587 var dst []byte
588 var totalSize int
589 for _, b := range contents {
590 dst = enc.EncodeAll(b, dst[:0])
591 totalSize += len(dst)
592 }
593 return totalSize
594 }
595 plain := encWith(WithEncoderLevel(o.Level))
596 withDict := encWith(WithEncoderLevel(o.Level), WithEncoderDict(out.Bytes()))
597 println("Input size:", totalSize)
598 println("Plain Compressed:", plain)
599 println("Dict Compressed:", withDict)
600 println("Saved:", plain-withDict, (plain-withDict)/len(contents), "bytes per input (rounded down)")
601 }
602 return out.Bytes(), nil
603 }