-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathsearch_table.go
More file actions
472 lines (434 loc) · 15.9 KB
/
Copy pathsearch_table.go
File metadata and controls
472 lines (434 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
package minlz
import (
"encoding/binary"
"fmt"
"slices"
)
const (
searchTableTypeNoPrefix = 1
searchTableTypeBytePrefix = 2
searchTableTypeMaskPrefix = 3
searchTableTypeLongPrefix = 4
searchTableMinLog2 = 8 // 256 entries = 32 bytes
searchTableMaxLog2 = 23 // matches maxBlockLog
defaultMaxPopPct = 70
defaultMaxReducedPopPct = 25
)
// Hash primes from SPEC_SEARCH.md
const (
prime2bytes uint32 = 40503
prime3bytes uint32 = 506832829
prime4bytes uint32 = 2654435761
prime5bytes uint64 = 889523592379
prime6bytes uint64 = 227718039650203
prime7bytes uint64 = 58295818150454627
prime8bytes uint64 = 0xcf1bbcdcb7a56463
)
// SearchTableConfig configures search table generation for a Writer.
// Use NewSearchTableConfig to create, then chain With* methods to customize.
type SearchTableConfig struct {
matchLen uint8
tableType uint8
baseTableSize uint8 // log2, computed at writer init from block size
extras uint8 // type 4 only: E+1 hashes per prefix occurrence; matchLen+extras ≤ 16
prefixBytes [8]byte
prefixMask [32]byte
longPrefix []byte
maxPopPct int
maxReducedPopPct int
maxReducedPopPctSet bool // true once WithMaxReducedPopulation has been called
compression *compressedOpts // nil = emit 0x45 only
}
// String returns a one-line, human-readable summary of the search table
// configuration. Useful for logging the contents of an 0x44 chunk.
func (c SearchTableConfig) String() string {
var prefix string
switch c.tableType {
case searchTableTypeNoPrefix:
prefix = "no-prefix"
case searchTableTypeBytePrefix:
// Compact the prefixBytes array — duplicates are encoder-internal padding.
seen := make(map[byte]struct{}, 8)
var unique []byte
for _, b := range c.prefixBytes {
if _, ok := seen[b]; ok {
continue
}
seen[b] = struct{}{}
unique = append(unique, b)
}
prefix = fmt.Sprintf("byte-prefix=%q", string(unique))
case searchTableTypeMaskPrefix:
n := 0
for i := range 256 {
if c.prefixMask[i>>3]&(1<<(i&7)) != 0 {
n++
}
}
prefix = fmt.Sprintf("mask-prefix (%d bytes)", n)
case searchTableTypeLongPrefix:
if c.extras > 0 {
prefix = fmt.Sprintf("long-prefix=%q extras=%d", string(c.longPrefix), c.extras)
} else {
prefix = fmt.Sprintf("long-prefix=%q", string(c.longPrefix))
}
default:
prefix = fmt.Sprintf("type=%d", c.tableType)
}
return fmt.Sprintf("matchLen=%d baseTableSize=%d (%d entries) %s",
c.matchLen, c.baseTableSize, 1<<c.baseTableSize, prefix)
}
// NewSearchTableConfig creates a search table config.
// Defaults: matchLen=6, no prefix (type 1), auto table size, 70% max
// population, 25% max reduced population (auto-tightened to 10% when a prefix
// is configured), compression on.
func NewSearchTableConfig() SearchTableConfig {
return SearchTableConfig{
matchLen: 6,
tableType: searchTableTypeNoPrefix,
maxPopPct: defaultMaxPopPct,
maxReducedPopPct: defaultMaxReducedPopPct,
compression: &compressedOpts{
enabled: true,
skipPctTimes100: cstDefaultSkipPctTimes100,
},
}
}
// WithMatchLen sets the match length (1-8).
// Shorter values use less of the search pattern but are more likely to collide.
// Default is 6.
func (c SearchTableConfig) WithMatchLen(n int) SearchTableConfig {
if n < 0 || n > 255 {
n = 255 // out of uint8 range: let validate() reject instead of silently wrapping
}
c.matchLen = uint8(n)
return c
}
// WithBytePrefix sets prefix byte values. With 1-8 unique values, table type 2
// is used. With more than 8, it automatically switches to a bitmask (type 3).
func (c SearchTableConfig) WithBytePrefix(prefixes ...byte) SearchTableConfig {
if len(prefixes) > 8 {
var mask [32]byte
for _, p := range prefixes {
mask[p>>3] |= 1 << (p & 7)
}
return c.WithMaskPrefix(mask)
}
c.tableType = searchTableTypeBytePrefix
for i := range c.prefixBytes {
if i < len(prefixes) {
c.prefixBytes[i] = prefixes[i]
} else if len(prefixes) > 0 {
c.prefixBytes[i] = prefixes[len(prefixes)-1]
}
}
return c
}
// WithMaskPrefix sets a 256-bit bitmask of prefix bytes (table type 3).
func (c SearchTableConfig) WithMaskPrefix(mask [32]byte) SearchTableConfig {
c.tableType = searchTableTypeMaskPrefix
c.prefixMask = mask
return c
}
// WithLongPrefix sets a long prefix (1-256 bytes, table type 4).
func (c SearchTableConfig) WithLongPrefix(prefix []byte) SearchTableConfig {
c.tableType = searchTableTypeLongPrefix
c.longPrefix = slices.Clone(prefix)
return c
}
// WithExtras sets the number of extra hashes emitted after each long-prefix
// occurrence. With extras=E, table type 4 writes E+1 consecutive overlapping
// matchLen-byte windows per indexed position; the searcher checks the same
// E+1 windows per pattern occurrence. matchLen+extras must not exceed 16.
//
// Extras only applies to type 4 (long prefix). Setting extras > 0 on any other
// table type produces a validation error.
func (c SearchTableConfig) WithExtras(n int) SearchTableConfig {
if n < 0 || n > 255 {
n = 255 // out of uint8 range: let validate() reject instead of silently wrapping
}
c.extras = uint8(n)
return c
}
// WithMaxPopulation sets the max population percentage (0-100).
// Tables with more bits set are skipped entirely.
func (c SearchTableConfig) WithMaxPopulation(pct int) SearchTableConfig {
c.maxPopPct = pct
return c
}
// WithMaxReducedPopulation sets the max population percentage (0-100) for the
// reduced table. Reductions stop before exceeding this threshold.
//
// Default is 25%, automatically tightened to 10% when a prefix is configured
// (byte/mask/long). Calling this method disables that auto-tightening — the
// supplied value is used regardless of prefix.
func (c SearchTableConfig) WithMaxReducedPopulation(pct int) SearchTableConfig {
c.maxReducedPopPct = pct
c.maxReducedPopPctSet = true
return c
}
// WithCompression enables huff0 compression of per-block search tables and
// optionally tunes it. Compression is on by default — call this only to pass
// non-default options.
//
// Search indexes that can only be marginally compressed are stored uncompressed.
//
// With no options, defaults are: 10.0% popcount band, no stats hook,
// non-forced (emit compressed only when smaller).
func (c SearchTableConfig) WithCompression(opts ...CompressedSearchOption) SearchTableConfig {
co := &compressedOpts{
enabled: true,
skipPctTimes100: cstDefaultSkipPctTimes100,
}
for _, o := range opts {
o(co)
}
c.compression = co
return c
}
// WithoutCompression disables the per-block search-table compression that is
// on by default. The stream will emit only 0x45 chunks; readers that don't
// implement 0x46 can read it.
func (c SearchTableConfig) WithoutCompression() SearchTableConfig {
c.compression = nil
return c
}
// resolveDefaults applies context-dependent defaults that were not set
// explicitly by the caller. Currently: tightens maxReducedPopPct to 10 when a
// prefix is configured and WithMaxReducedPopulation was not called.
// Must be called once the tableType is final.
func (c *SearchTableConfig) resolveDefaults() {
if !c.maxReducedPopPctSet && c.tableType != searchTableTypeNoPrefix {
c.maxReducedPopPct = 10
}
}
func (c *SearchTableConfig) validate() error {
if c.matchLen < 1 || c.matchLen > 8 {
return fmt.Errorf("minlz: search table matchLen must be 1-8, got %d", c.matchLen)
}
switch c.tableType {
case searchTableTypeNoPrefix, searchTableTypeBytePrefix, searchTableTypeMaskPrefix, searchTableTypeLongPrefix:
default:
return fmt.Errorf("minlz: unknown search table type %d", c.tableType)
}
if c.tableType == searchTableTypeLongPrefix && (len(c.longPrefix) < 1 || len(c.longPrefix) > 256) {
return fmt.Errorf("minlz: long prefix length must be 1-256, got %d", len(c.longPrefix))
}
if c.extras != 0 {
if c.tableType != searchTableTypeLongPrefix {
return fmt.Errorf("minlz: extras only valid for long-prefix tables (type 4)")
}
if int(c.matchLen)+int(c.extras) > 16 {
return fmt.Errorf("minlz: matchLen+extras must be <= 16, got matchLen=%d extras=%d", c.matchLen, c.extras)
}
}
return nil
}
// searchTablePayloadSize returns the 0x45 payload size for the given table length.
func (c *SearchTableConfig) searchTablePayloadSize(tableLen int) int {
// 3 (type+matchLen+baseSize) + prefixSize + 1 (reductions) + 4 (crc) + table
return 3 + c.prefixSize() + 1 + 4 + tableLen
}
// maxChunkSize returns the maximum 0x45 chunk size (header + payload) for this config.
// Max table = 2^(baseTableSize-3) bytes (0 reductions).
func (c *SearchTableConfig) maxChunkSize() int {
return 4 + c.searchTablePayloadSize(1<<(c.baseTableSize-3))
}
// overlapBytes returns the number of bytes the search-table encoder needs
// from the start of the next block to safely index positions near the end
// of the current block. An occurrence is indexed in the block where its prefix
// starts (SPEC_SEARCH.md 2.1), so the encoder reads the window(s) — and, for a
// long prefix that starts in this block but straddles into the next, the rest
// of the prefix — from the overlap: matchLen+extras bytes, plus len(prefix)-1
// for a long prefix.
func (c *SearchTableConfig) overlapBytes() int {
n := int(c.matchLen) + int(c.extras)
if c.tableType == searchTableTypeLongPrefix {
n += len(c.longPrefix) - 1
}
return max(0, n)
}
func (c *SearchTableConfig) prefixSize() int {
switch c.tableType {
case searchTableTypeBytePrefix:
return 8
case searchTableTypeMaskPrefix:
return 32
case searchTableTypeLongPrefix:
// length byte + extras byte + prefix bytes
return 2 + len(c.longPrefix)
}
return 0
}
// HashValue returns a table index for the lowest matchLen bytes of val.
// tableSize is the number of output bits (8-23). matchLen must be 1-8.
func hashValue(val uint64, tableSize, matchLen uint8) uint32 {
switch matchLen {
case 1:
return uint32(val & 0xff)
case 2:
if tableSize >= 16 {
return uint32(val & 0xffff)
}
return (uint32(val<<16) * prime2bytes) >> (32 - tableSize)
case 3:
return (uint32(val<<8) * prime3bytes) >> (32 - tableSize)
case 4:
return (uint32(val) * prime4bytes) >> (32 - tableSize)
case 5:
return uint32(((val << (64 - 40)) * prime5bytes) >> (64 - uint64(tableSize)))
case 6:
return uint32(((val << (64 - 48)) * prime6bytes) >> (64 - uint64(tableSize)))
case 7:
return uint32(((val << (64 - 56)) * prime7bytes) >> (64 - uint64(tableSize)))
case 8:
return uint32((val * prime8bytes) >> (64 - uint64(tableSize)))
}
return 0
}
// Per-matchLen hash helpers for branchless inner loops.
func hashValue1(v uint64) uint32 { return uint32(v & 0xff) }
func hashValue2(v uint64, ts uint8) uint32 { return (uint32(v<<16) * prime2bytes) >> (32 - ts) }
func hashValue3(v uint64, ts uint8) uint32 { return (uint32(v<<8) * prime3bytes) >> (32 - ts) }
func hashValue4(v uint64, ts uint8) uint32 { return (uint32(v) * prime4bytes) >> (32 - ts) }
func hashValue5(v uint64, ts uint8) uint32 {
return uint32(((v << 24) * prime5bytes) >> (64 - uint64(ts)))
}
func hashValue6(v uint64, ts uint8) uint32 {
return uint32(((v << 16) * prime6bytes) >> (64 - uint64(ts)))
}
func hashValue7(v uint64, ts uint8) uint32 {
return uint32(((v << 8) * prime7bytes) >> (64 - uint64(ts)))
}
func hashValue8(v uint64, ts uint8) uint32 { return uint32((v * prime8bytes) >> (64 - uint64(ts))) }
// hashValue2Full handles the special case where tableSize >= 16 for matchLen 2.
func hashValue2Full(v uint64) uint32 { return uint32(v & 0xffff) }
func (c *SearchTableConfig) appendPrefix(dst []byte) []byte {
switch c.tableType {
case searchTableTypeBytePrefix:
return append(dst, c.prefixBytes[:]...)
case searchTableTypeMaskPrefix:
return append(dst, c.prefixMask[:]...)
case searchTableTypeLongPrefix:
dst = append(dst, uint8(len(c.longPrefix)-1), c.extras)
return append(dst, c.longPrefix...)
}
return dst
}
func (c *SearchTableConfig) appendConfig(dst []byte) []byte {
dst = append(dst, c.tableType, c.matchLen, c.baseTableSize)
return c.appendPrefix(dst)
}
func appendChunkHeader(dst []byte, chunkType byte, payloadSize int) []byte {
return append(dst, chunkType, uint8(payloadSize), uint8(payloadSize>>8), uint8(payloadSize>>16))
}
// marshalSearchInfoChunk produces a complete 0x44 chunk.
func (c *SearchTableConfig) marshalSearchInfoChunk() []byte {
dst := appendChunkHeader(nil, chunkTypeSearchInfo, 3+c.prefixSize())
return c.appendConfig(dst)
}
// appendSearchTableChunk appends a complete 0x45 chunk to dst.
func appendSearchTableChunk(dst []byte, cfg *SearchTableConfig, reductions uint8, table []byte) []byte {
dst = appendSearchTableHeader(dst, cfg, reductions, table)
return append(dst, table...)
}
// appendSearchTableHeader appends everything in the 0x45 chunk before the table bytes:
// chunk header, config, reductions, and CRC of table.
func appendSearchTableHeader(dst []byte, cfg *SearchTableConfig, reductions uint8, table []byte) []byte {
dst = appendChunkHeader(dst, chunkTypeSearchTable, cfg.searchTablePayloadSize(len(table)))
dst = cfg.appendConfig(dst)
dst = append(dst, reductions)
return binary.LittleEndian.AppendUint32(dst, crc(table))
}
// parseSearchInfo parses the payload (after chunk header) of a 0x44 chunk.
func parseSearchInfo(payload []byte) (SearchTableConfig, error) {
if len(payload) < 3 {
return SearchTableConfig{}, fmt.Errorf("minlz: search info chunk too short")
}
cfg := SearchTableConfig{
tableType: payload[0],
matchLen: payload[1],
baseTableSize: payload[2],
maxPopPct: defaultMaxPopPct,
maxReducedPopPct: defaultMaxReducedPopPct,
}
payload = payload[3:]
switch cfg.tableType {
case searchTableTypeNoPrefix:
case searchTableTypeBytePrefix:
if len(payload) < 8 {
return cfg, fmt.Errorf("minlz: search info byte prefix too short")
}
copy(cfg.prefixBytes[:], payload[:8])
case searchTableTypeMaskPrefix:
if len(payload) < 32 {
return cfg, fmt.Errorf("minlz: search info mask prefix too short")
}
copy(cfg.prefixMask[:], payload[:32])
case searchTableTypeLongPrefix:
if len(payload) < 2 {
return cfg, fmt.Errorf("minlz: search info long prefix too short")
}
pLen := int(payload[0]) + 1
cfg.extras = payload[1]
if int(cfg.matchLen)+int(cfg.extras) > 16 {
return cfg, fmt.Errorf("minlz: matchLen+extras must be <= 16, got matchLen=%d extras=%d", cfg.matchLen, cfg.extras)
}
if len(payload) < 2+pLen {
return cfg, fmt.Errorf("minlz: search info long prefix data too short")
}
cfg.longPrefix = slices.Clone(payload[2 : 2+pLen])
default:
return cfg, fmt.Errorf("minlz: unknown search table type %d", cfg.tableType)
}
return cfg, nil
}
// parseSearchTable parses the payload (after chunk header) of a 0x45 chunk.
func parseSearchTable(payload []byte, ignoreCRC bool) (cfg SearchTableConfig, reductions uint8, table []byte, err error) {
cfg, err = parseSearchInfo(payload)
if err != nil {
return
}
off := 3 + cfg.prefixSize()
if off >= len(payload) {
err = fmt.Errorf("minlz: search table chunk too short for reductions")
return
}
reductions = payload[off]
table = payload[off+1:]
expectedSize := 1 << (cfg.baseTableSize - reductions - 3)
if len(table) < expectedSize+4 {
err = fmt.Errorf("minlz: search table data too short: got %d, want %d", len(table), expectedSize+4)
return
}
// Read stored CRC
crc32 := binary.LittleEndian.Uint32(table)
table = table[4:]
table = table[:expectedSize]
if !ignoreCRC && crc32 != crc(table) {
err = fmt.Errorf("minlz: search table CRC mismatch")
}
return
}
// tableAllZero reports whether the bitmap has no bits set. For a prefix table
// that means no prefix occurrence starts in the block (an empty table reduces
// to the 32-byte minimum, so this scan is cheap).
func tableAllZero(table []byte) bool {
for _, b := range table {
if b != 0 {
return false
}
}
return true
}
// readLE64Pad reads up to 8 bytes from b as a little-endian uint64, zero-padding if short.
func readLE64Pad(b []byte) uint64 {
if len(b) >= 8 {
return binary.LittleEndian.Uint64(b)
}
var v uint64
for i := range b {
v |= uint64(b[i]) << (i * 8)
}
return v
}