Debian Codegraph @

dict/builder.go

raw
1 // Copyright 2023+ Klaus Post. 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 dict
6
7 import (
8 "bytes"
9 "encoding/binary"
10 "errors"
11 "fmt"
12 "io"
13 "math/rand"
14 "sort"
15 "time"
16
17 "github.com/klauspost/compress/s2"
18 "github.com/klauspost/compress/zstd"
19 )
20
21 type match struct {
22 hash uint32
23 n uint32
24 offset int64
25 }
26
27 type matchValue struct {
28 value []byte
29 followBy map[uint32]uint32
30 preceededBy map[uint32]uint32
31 }
32
33 type Options struct {
34 // MaxDictSize is the max size of the backreference dictionary.
35 MaxDictSize int
36
37 // HashBytes is the minimum length to index.
38 // Must be >=4 and <=8
39 HashBytes int
40
41 // Debug output
42 Output io.Writer
43
44 // ZstdDictID is the Zstd dictionary ID to use.
45 // Leave at zero to generate a random ID.
46 ZstdDictID uint32
47
48 // ZstdDictCompat will make the dictionary compatible with Zstd v1.5.5 and earlier.
49 // See https://github.com/facebook/zstd/issues/3724
50 ZstdDictCompat bool
51
52 // Use the specified encoder level for Zstandard dictionaries.
53 // The dictionary will be built using the specified encoder level,
54 // which will reflect speed and make the dictionary tailored for that level.
55 // If not set zstd.SpeedBestCompression will be used.
56 ZstdLevel zstd.EncoderLevel
57
58 outFormat int
59 }
60
61 const (
62 formatRaw = iota
63 formatZstd
64 formatS2
65 )
66
67 // BuildZstdDict will build a Zstandard dictionary from the provided input.
68 func BuildZstdDict(input [][]byte, o Options) ([]byte, error) {
69 o.outFormat = formatZstd
70 if o.ZstdDictID == 0 {
71 rng := rand.New(rand.NewSource(time.Now().UnixNano()))
72 o.ZstdDictID = 32768 + uint32(rng.Int31n((1<<31)-32768))
73 }
74 return buildDict(input, o)
75 }
76
77 // BuildS2Dict will build a S2 dictionary from the provided input.
78 func BuildS2Dict(input [][]byte, o Options) ([]byte, error) {
79 o.outFormat = formatS2
80 if o.MaxDictSize > s2.MaxDictSize {
81 return nil, errors.New("max dict size too large")
82 }
83 return buildDict(input, o)
84 }
85
86 // BuildRawDict will build a raw dictionary from the provided input.
87 // This can be used for deflate, lz4 and others.
88 func BuildRawDict(input [][]byte, o Options) ([]byte, error) {
89 o.outFormat = formatRaw
90 return buildDict(input, o)
91 }
92
93 func buildDict(input [][]byte, o Options) ([]byte, error) {
94 matches := make(map[uint32]uint32)
95 offsets := make(map[uint32]int64)
96 var total uint64
97
98 wantLen := o.MaxDictSize
99 hashBytes := o.HashBytes
100 if len(input) == 0 {
101 return nil, fmt.Errorf("no input provided")
102 }
103 if hashBytes < 4 || hashBytes > 8 {
104 return nil, fmt.Errorf("HashBytes must be >= 4 and <= 8")
105 }
106 println := func(args ...any) {
107 if o.Output != nil {
108 fmt.Fprintln(o.Output, args...)
109 }
110 }
111 printf := func(s string, args ...any) {
112 if o.Output != nil {
113 fmt.Fprintf(o.Output, s, args...)
114 }
115 }
116 found := make(map[uint32]struct{})
117 for i, b := range input {
118 for k := range found {
119 delete(found, k)
120 }
121 for i := range b {
122 rem := b[i:]
123 if len(rem) < 8 {
124 break
125 }
126 h := hashLen(binary.LittleEndian.Uint64(rem), 32, uint8(hashBytes))
127 if _, ok := found[h]; ok {
128 // Only count first occurrence
129 continue
130 }
131 matches[h]++
132 offsets[h] += int64(i)
133 total++
134 found[h] = struct{}{}
135 }
136 printf("\r input %d indexed...", i)
137 }
138 threshold := uint32(total / uint64(len(matches)))
139 println("\nTotal", total, "match", len(matches), "avg", threshold)
140 sorted := make([]match, 0, len(matches)/2)
141 for k, v := range matches {
142 if v <= threshold {
143 continue
144 }
145 sorted = append(sorted, match{hash: k, n: v, offset: offsets[k]})
146 }
147 sort.Slice(sorted, func(i, j int) bool {
148 if true {
149 // Group very similar counts together and emit low offsets first.
150 // This will keep together strings that are very similar.
151 deltaN := int(sorted[i].n) - int(sorted[j].n)
152 if deltaN < 0 {
153 deltaN = -deltaN
154 }
155 if uint32(deltaN) < sorted[i].n/32 {
156 return sorted[i].offset < sorted[j].offset
157 }
158 } else {
159 if sorted[i].n == sorted[j].n {
160 return sorted[i].offset < sorted[j].offset
161 }
162 }
163 return sorted[i].n > sorted[j].n
164 })
165 println("Sorted len:", len(sorted))
166 if len(sorted) > wantLen {
167 sorted = sorted[:wantLen]
168 }
169 lowestOcc := sorted[len(sorted)-1].n
170 println("Cropped len:", len(sorted), "Lowest occurrence:", lowestOcc)
171
172 wantMatches := make(map[uint32]uint32, len(sorted))
173 for _, v := range sorted {
174 wantMatches[v.hash] = v.n
175 }
176
177 output := make(map[uint32]matchValue, len(sorted))
178 var remainCnt [256]int
179 var remainTotal int
180 var firstOffsets []int
181 for i, b := range input {
182 for i := range b {
183 rem := b[i:]
184 if len(rem) < 8 {
185 break
186 }
187 var prev []byte
188 if i > hashBytes {
189 prev = b[i-hashBytes:]
190 }
191
192 h := hashLen(binary.LittleEndian.Uint64(rem), 32, uint8(hashBytes))
193 if _, ok := wantMatches[h]; !ok {
194 remainCnt[rem[0]]++
195 remainTotal++
196 continue
197 }
198 mv := output[h]
199 if len(mv.value) == 0 {
200 var tmp = make([]byte, hashBytes)
201 copy(tmp[:], rem)
202 mv.value = tmp[:]
203 }
204 if mv.followBy == nil {
205 mv.followBy = make(map[uint32]uint32, 4)
206 mv.preceededBy = make(map[uint32]uint32, 4)
207 }
208 if len(rem) > hashBytes+8 {
209 // Check if we should add next as well.
210 hNext := hashLen(binary.LittleEndian.Uint64(rem[hashBytes:]), 32, uint8(hashBytes))
211 if _, ok := wantMatches[hNext]; ok {
212 mv.followBy[hNext]++
213 }
214 }
215 if len(prev) >= 8 {
216 // Check if we should prev next as well.
217 hPrev := hashLen(binary.LittleEndian.Uint64(prev), 32, uint8(hashBytes))
218 if _, ok := wantMatches[hPrev]; ok {
219 mv.preceededBy[hPrev]++
220 }
221 }
222 output[h] = mv
223 }
224 printf("\rinput %d re-indexed...", i)
225 }
226 println("")
227 dst := make([][]byte, 0, wantLen/hashBytes)
228 added := 0
229 const printUntil = 500
230 for i, e := range sorted {
231 if added > o.MaxDictSize {
232 println("Ending. Next Occurrence:", e.n)
233 break
234 }
235 m, ok := output[e.hash]
236 if !ok {
237 // Already added
238 continue
239 }
240 wantLen := max(e.n/uint32(hashBytes)/4, lowestOcc)
241
242 var tmp = make([]byte, 0, hashBytes*2)
243 {
244 sortedPrev := make([]match, 0, len(m.followBy))
245 for k, v := range m.preceededBy {
246 if _, ok := output[k]; v < wantLen || !ok {
247 continue
248 }
249 sortedPrev = append(sortedPrev, match{
250 hash: k,
251 n: v,
252 })
253 }
254 if len(sortedPrev) > 0 {
255 sort.Slice(sortedPrev, func(i, j int) bool {
256 return sortedPrev[i].n > sortedPrev[j].n
257 })
258 bestPrev := output[sortedPrev[0].hash]
259 tmp = append(tmp, bestPrev.value...)
260 }
261 }
262 tmp = append(tmp, m.value...)
263 delete(output, e.hash)
264
265 sortedFollow := make([]match, 0, len(m.followBy))
266 for {
267 var nh uint32 // Next hash
268 stopAfter := false
269 {
270 sortedFollow = sortedFollow[:0]
271 for k, v := range m.followBy {
272 if _, ok := output[k]; !ok {
273 continue
274 }
275 sortedFollow = append(sortedFollow, match{
276 hash: k,
277 n: v,
278 offset: offsets[k],
279 })
280 }
281 if len(sortedFollow) == 0 {
282 // Step back
283 // Extremely small impact, but helps longer hashes a bit.
284 const stepBack = 2
285 if stepBack > 0 && len(tmp) >= hashBytes+stepBack {
286 var t8 [8]byte
287 copy(t8[:], tmp[len(tmp)-hashBytes-stepBack:])
288 m, ok = output[hashLen(binary.LittleEndian.Uint64(t8[:]), 32, uint8(hashBytes))]
289 if ok && len(m.followBy) > 0 {
290 found := []byte(nil)
291 for k := range m.followBy {
292 v, ok := output[k]
293 if !ok {
294 continue
295 }
296 found = v.value
297 break
298 }
299 if found != nil {
300 tmp = tmp[:len(tmp)-stepBack]
301 printf("Step back: %q + %q\n", string(tmp), string(found))
302 continue
303 }
304 }
305 break
306 } else {
307 if i < printUntil {
308 printf("FOLLOW: none after %q\n", string(m.value))
309 }
310 }
311 break
312 }
313 sort.Slice(sortedFollow, func(i, j int) bool {
314 if sortedFollow[i].n == sortedFollow[j].n {
315 return sortedFollow[i].offset > sortedFollow[j].offset
316 }
317 return sortedFollow[i].n > sortedFollow[j].n
318 })
319 nh = sortedFollow[0].hash
320 stopAfter = sortedFollow[0].n < wantLen
321 if stopAfter && i < printUntil {
322 printf("FOLLOW: %d < %d after %q. Stopping after this.\n", sortedFollow[0].n, wantLen, string(m.value))
323 }
324 }
325 m, ok = output[nh]
326 if !ok {
327 break
328 }
329 if len(tmp) > 0 {
330 // Delete all hashes that are in the current string to avoid stuttering.
331 var toDel [16 + 8]byte
332 copy(toDel[:], tmp[len(tmp)-hashBytes:])
333 copy(toDel[hashBytes:], m.value)
334 for i := range toDel[:hashBytes*2] {
335 delete(output, hashLen(binary.LittleEndian.Uint64(toDel[i:]), 32, uint8(hashBytes)))
336 }
337 }
338 tmp = append(tmp, m.value...)
339 //delete(output, nh)
340 if stopAfter {
341 // Last entry was no significant.
342 break
343 }
344 }
345 if i < printUntil {
346 printf("ENTRY %d: %q (%d occurrences, cutoff %d)\n", i, string(tmp), e.n, wantLen)
347 }
348 // Delete substrings already added.
349 if len(tmp) > hashBytes {
350 for j := range tmp[:len(tmp)-hashBytes+1] {
351 var t8 [8]byte
352 copy(t8[:], tmp[j:])
353 if i < printUntil {
354 //printf("* POST DELETE %q\n", string(t8[:hashBytes]))
355 }
356 delete(output, hashLen(binary.LittleEndian.Uint64(t8[:]), 32, uint8(hashBytes)))
357 }
358 }
359 dst = append(dst, tmp)
360 added += len(tmp)
361 // Find offsets
362 // TODO: This can be better if done as a global search.
363 if len(firstOffsets) < 3 {
364 if len(tmp) > 16 {
365 tmp = tmp[:16]
366 }
367 offCnt := make(map[int]int, len(input))
368 // Find first offsets
369 for _, b := range input {
370 off := bytes.Index(b, tmp)
371 if off == -1 {
372 continue
373 }
374 offCnt[off]++
375 }
376 for _, off := range firstOffsets {
377 // Very unlikely, but we deleted it just in case
378 delete(offCnt, off-added)
379 }
380 maxCnt := 0
381 maxOffset := 0
382 for k, v := range offCnt {
383 if v == maxCnt && k > maxOffset {
384 // Prefer the longer offset on ties , since it is more expensive to encode
385 maxCnt = v
386 maxOffset = k
387 continue
388 }
389
390 if v > maxCnt {
391 maxCnt = v
392 maxOffset = k
393 }
394 }
395 if maxCnt > 1 {
396 firstOffsets = append(firstOffsets, maxOffset+added)
397 println(" - Offset:", len(firstOffsets), "at", maxOffset+added, "count:", maxCnt, "total added:", added, "src index", maxOffset)
398 }
399 }
400 }
401 out := bytes.NewBuffer(nil)
402 written := 0
403 for i, toWrite := range dst {
404 if len(toWrite)+written > wantLen {
405 toWrite = toWrite[:wantLen-written]
406 }
407 dst[i] = toWrite
408 written += len(toWrite)
409 if written >= wantLen {
410 dst = dst[:i+1]
411 break
412 }
413 }
414 // Write in reverse order.
415 for i := range dst {
416 toWrite := dst[len(dst)-i-1]
417 out.Write(toWrite)
418 }
419 if o.outFormat == formatRaw {
420 return out.Bytes(), nil
421 }
422
423 if o.outFormat == formatS2 {
424 dOff := 0
425 dBytes := out.Bytes()
426 if len(dBytes) > s2.MaxDictSize {
427 dBytes = dBytes[:s2.MaxDictSize]
428 }
429 for _, off := range firstOffsets {
430 myOff := len(dBytes) - off
431 if myOff < 0 || myOff > s2.MaxDictSrcOffset {
432 continue
433 }
434 dOff = myOff
435 }
436
437 dict := s2.MakeDictManual(dBytes, uint16(dOff))
438 if dict == nil {
439 return nil, fmt.Errorf("unable to create s2 dictionary")
440 }
441 return dict.Bytes(), nil
442 }
443
444 offsetsZstd := [3]int{1, 4, 8}
445 for i, off := range firstOffsets {
446 if i >= 3 || off == 0 || off >= out.Len() {
447 break
448 }
449 offsetsZstd[i] = off
450 }
451 println("\nCompressing. Offsets:", offsetsZstd)
452 return zstd.BuildDict(zstd.BuildDictOptions{
453 ID: o.ZstdDictID,
454 Contents: input,
455 History: out.Bytes(),
456 Offsets: offsetsZstd,
457 CompatV155: o.ZstdDictCompat,
458 Level: o.ZstdLevel,
459 DebugOut: o.Output,
460 })
461 }
462
463 const (
464 prime3bytes = 506832829
465 prime4bytes = 2654435761
466 prime5bytes = 889523592379
467 prime6bytes = 227718039650203
468 prime7bytes = 58295818150454627
469 prime8bytes = 0xcf1bbcdcb7a56463
470 )
471
472 // hashLen returns a hash of the lowest l bytes of u for a size size of h bytes.
473 // l must be >=4 and <=8. Any other value will return hash for 4 bytes.
474 // h should always be <32.
475 // Preferably h and l should be a constant.
476 // LENGTH 4 is passed straight through
477 func hashLen(u uint64, hashLog, mls uint8) uint32 {
478 switch mls {
479 case 5:
480 return hash5(u, hashLog)
481 case 6:
482 return hash6(u, hashLog)
483 case 7:
484 return hash7(u, hashLog)
485 case 8:
486 return hash8(u, hashLog)
487 default:
488 return uint32(u)
489 }
490 }
491
492 // hash3 returns the hash of the lower 3 bytes of u to fit in a hash table with h bits.
493 // Preferably h should be a constant and should always be <32.
494 func hash3(u uint32, h uint8) uint32 {
495 return ((u << (32 - 24)) * prime3bytes) >> ((32 - h) & 31)
496 }
497
498 // hash4 returns the hash of u to fit in a hash table with h bits.
499 // Preferably h should be a constant and should always be <32.
500 func hash4(u uint32, h uint8) uint32 {
501 return (u * prime4bytes) >> ((32 - h) & 31)
502 }
503
504 // hash4x64 returns the hash of the lowest 4 bytes of u to fit in a hash table with h bits.
505 // Preferably h should be a constant and should always be <32.
506 func hash4x64(u uint64, h uint8) uint32 {
507 return (uint32(u) * prime4bytes) >> ((32 - h) & 31)
508 }
509
510 // hash5 returns the hash of the lowest 5 bytes of u to fit in a hash table with h bits.
511 // Preferably h should be a constant and should always be <64.
512 func hash5(u uint64, h uint8) uint32 {
513 return uint32(((u << (64 - 40)) * prime5bytes) >> ((64 - h) & 63))
514 }
515
516 // hash6 returns the hash of the lowest 6 bytes of u to fit in a hash table with h bits.
517 // Preferably h should be a constant and should always be <64.
518 func hash6(u uint64, h uint8) uint32 {
519 return uint32(((u << (64 - 48)) * prime6bytes) >> ((64 - h) & 63))
520 }
521
522 // hash7 returns the hash of the lowest 7 bytes of u to fit in a hash table with h bits.
523 // Preferably h should be a constant and should always be <64.
524 func hash7(u uint64, h uint8) uint32 {
525 return uint32(((u << (64 - 56)) * prime7bytes) >> ((64 - h) & 63))
526 }
527
528 // hash8 returns the hash of u to fit in a hash table with h bits.
529 // Preferably h should be a constant and should always be <64.
530 func hash8(u uint64, h uint8) uint32 {
531 return uint32((u * prime8bytes) >> ((64 - h) & 63))
532 }