-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimal_parse.go
More file actions
1453 lines (1346 loc) · 49.6 KB
/
Copy pathoptimal_parse.go
File metadata and controls
1453 lines (1346 loc) · 49.6 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package skanda
import "math/bits"
type optimalMatchState struct {
optimalFinder *levelOptimalMatchFinder
binaryFinder *binaryMatchFinder
steps []optimalMatchStep
backtrackScratch []optimalMatchStep
matchBuffer matchBuffer
matchScratch []lzMatch
}
type optimalParseState struct {
cost int
prev int
prevPath int
matchLen int
distance int
litRun int
repOffsets [3]int
}
type optimalMatchStep struct {
pos int
length int
distance int
}
type optimalParseResult struct {
steps []optimalMatchStep
consumed int
acceleration int
}
type optimalBlockParseResult struct {
steps []optimalMatchStep
acceleration int
}
type optimalCostModel struct {
enabled bool
literalMode int
literal [4][256]int
token [256]int
distance [256]int
length [256]int
}
type optimalEntropyPlan struct {
enabled bool
literalMode int
literal [4]float64
token float64
distance float64
length float64
}
func useBufferedMatches(opts compressorLevelOptions) bool {
return opts.parser != compressorParserOptimal1 && opts.parserIterations > 1 && opts.decSpeedBias < 0.99
}
func precomputeOptimalMatchSource(src []byte, blockStart, blockEnd int, opts compressorLevelOptions, iterations int, noHuffmanCosts bool) optimalMatchSource {
if iterations <= 1 || !useBufferedMatches(opts) || noHuffmanCosts {
return nil
}
finder := optimalBinaryMatchFinder(blockStart, blockEnd, opts)
if opts.matchState != nil {
return opts.matchState.resetMatchBuffer(src, blockStart, blockEnd, len(src)-lastBytes, opts, finder)
}
return newMatchBuffer(src, blockStart, blockEnd, len(src)-lastBytes, opts, finder)
}
func newOptimalMatchState(size int, opts compressorLevelOptions) *optimalMatchState {
opts = normalizeCompressorLevelOptions(opts)
switch opts.parser {
case compressorParserOptimal1:
finder := newLevelOptimalMatchFinder(opts)
return &optimalMatchState{optimalFinder: &finder}
case compressorParserOptimal2, compressorParserOptimal3:
return &optimalMatchState{binaryFinder: newBinaryMatchFinder(0, max(1, size), opts)}
default:
return nil
}
}
func (state *optimalMatchState) release() {
if state == nil {
return
}
if state.optimalFinder != nil {
state.optimalFinder.release()
state.optimalFinder = nil
}
if state.binaryFinder != nil {
state.binaryFinder.release()
state.binaryFinder = nil
}
if state.steps != nil {
releaseOptimalMatchSteps(state.steps)
state.steps = nil
}
if state.backtrackScratch != nil {
releaseOptimalMatchSteps(state.backtrackScratch)
state.backtrackScratch = nil
}
state.matchBuffer = matchBuffer{}
state.matchScratch = nil
}
func (state *optimalMatchState) resetForEncode() {
if state == nil {
return
}
if state.optimalFinder != nil {
state.optimalFinder.reset()
}
if state.binaryFinder != nil {
state.binaryFinder.reset()
}
if state.steps != nil {
state.steps = state.steps[:0]
}
if state.backtrackScratch != nil {
state.backtrackScratch = state.backtrackScratch[:0]
}
state.matchBuffer.counts = state.matchBuffer.counts[:0]
state.matchBuffer.matches = state.matchBuffer.matches[:0]
state.matchScratch = state.matchScratch[:0]
}
func (state *optimalMatchState) resetSteps(sizeHint int) []optimalMatchStep {
if state == nil {
return make([]optimalMatchStep, 0, sizeHint)
}
if cap(state.steps) < sizeHint {
if state.steps != nil {
releaseOptimalMatchSteps(state.steps)
}
state.steps = acquireOptimalMatchSteps(sizeHint)
}
return state.steps[:0]
}
func (state *optimalMatchState) keepSteps(steps []optimalMatchStep) {
if state != nil {
state.steps = steps
}
}
func (state *optimalMatchState) resetMatchBuffer(src []byte, blockStart, blockEnd, compressionLimit int, opts compressorLevelOptions, finder *binaryMatchFinder) *matchBuffer {
return fillMatchBuffer(src, blockStart, blockEnd, compressionLimit, opts, finder, &state.matchBuffer, &state.matchScratch)
}
func optimalMatchStepSizeHint(blockSize int) int {
if blockSize <= 0 {
return 0
}
hint := blockSize / 16
if hint < 16 {
return 16
}
if hint > 1<<maxPooledOptimalMatchStepLog {
return 1 << maxPooledOptimalMatchStepLog
}
return hint
}
func useHuffmanCostModel(opts compressorLevelOptions) bool {
return opts.decSpeedBias < 0.99 && (opts.parser == compressorParserOptimal1 || opts.parser == compressorParserOptimal2 || opts.parser == compressorParserOptimal3)
}
func useNoHuffmanParserCosts(opts compressorLevelOptions, model *optimalCostModel) bool {
if opts.decSpeedBias >= 0.99 {
return true
}
return model != nil && model.enabled && model.allStreamsRaw()
}
func optimalEntropyPlanFromModel(opts compressorLevelOptions, model *optimalCostModel) optimalEntropyPlan {
plan := optimalEntropyPlan{
token: opts.decSpeedBias,
distance: opts.decSpeedBias,
length: opts.decSpeedBias,
}
for stream := range plan.literal {
plan.literal[stream] = opts.decSpeedBias
}
if !useHuffmanCostModel(opts) || model == nil || !model.enabled {
return plan
}
plan.enabled = true
plan.literalMode = model.literalMode
streamCount := 1
if model.literalMode&streamLiteralsPosMask3 != 0 {
streamCount = 4
}
for stream := 0; stream < streamCount; stream++ {
plan.literal[stream] = forcedEntropyBias(&model.literal[stream])
}
plan.token = forcedEntropyBias(&model.token)
plan.distance = forcedEntropyBias(&model.distance)
plan.length = forcedEntropyBias(&model.length)
return plan
}
func forcedEntropyBias(costs *[256]int) float64 {
if allCostsRaw(costs) {
return 1
}
return 0
}
func (plan optimalEntropyPlan) literalBias(stream int, fallback float64) float64 {
if !plan.enabled || stream < 0 || stream >= len(plan.literal) {
return fallback
}
return plan.literal[stream]
}
func (plan optimalEntropyPlan) streamBias(bias, fallback float64) float64 {
if !plan.enabled {
return fallback
}
return bias
}
func optimalParserIterations(opts compressorLevelOptions, model *optimalCostModel) int {
if !useHuffmanCostModel(opts) || opts.parser < compressorParserOptimal2 || model == nil || !model.enabled || model.allStreamsRaw() {
return 1
}
if opts.parserIterations < 1 {
return 1
}
if opts.level >= 10 && opts.decSpeedBias <= 0.1 && opts.parserIterations > 2 {
return 2
}
return opts.parserIterations
}
func optimalParserIterationOptions(opts compressorLevelOptions, iteration, iterations int) compressorLevelOptions {
if iteration != 0 || iterations <= 1 || opts.parser < compressorParserOptimal2 {
return opts
}
opts.maxArrivals = max(opts.maxArrivals/4, 1)
opts.niceLength = max(opts.niceLength/8, 32)
return opts
}
func (model *optimalCostModel) allStreamsRaw() bool {
if model == nil || !model.enabled {
return true
}
streamCount := 1
if model.literalMode&streamLiteralsPosMask3 != 0 {
streamCount = 4
}
for stream := 0; stream < streamCount; stream++ {
if !allCostsRaw(&model.literal[stream]) {
return false
}
}
return allCostsRaw(&model.token) && allCostsRaw(&model.distance) && allCostsRaw(&model.length)
}
func allCostsRaw(costs *[256]int) bool {
for _, cost := range costs {
if cost != 8 {
return false
}
}
return true
}
func parseOptimalBlock(src []byte, blockStart, blockEnd int, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool) []optimalMatchStep {
return parseOptimalBlockInternal(src, blockStart, blockEnd, startRepOffsets, advancedDistance, opts, model, noHuffmanCosts, nil, false)
}
func parseOptimalBlockWithPrecomputedSource(src []byte, blockStart, blockEnd int, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool, precomputedSource optimalMatchSource) []optimalMatchStep {
return parseOptimalBlockInternal(src, blockStart, blockEnd, startRepOffsets, advancedDistance, opts, model, noHuffmanCosts, precomputedSource, true)
}
func parseOptimalBlockWithPrecomputedSourceAndAcceleration(src []byte, blockStart, blockEnd int, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool, precomputedSource optimalMatchSource, acceleration int) optimalBlockParseResult {
return parseOptimalBlockInternalDetailed(src, blockStart, blockEnd, startRepOffsets, advancedDistance, opts, model, noHuffmanCosts, precomputedSource, true, acceleration)
}
func parseOptimalBlockInternal(src []byte, blockStart, blockEnd int, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool, precomputedSource optimalMatchSource, usePrecomputedSource bool) []optimalMatchStep {
return parseOptimalBlockInternalDetailed(src, blockStart, blockEnd, startRepOffsets, advancedDistance, opts, model, noHuffmanCosts, precomputedSource, usePrecomputedSource, optimalAccelerationBase).steps
}
func parseOptimalBlockInternalDetailed(src []byte, blockStart, blockEnd int, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool, precomputedSource optimalMatchSource, usePrecomputedSource bool, acceleration int) optimalBlockParseResult {
pos := blockStart
if blockStart == 0 && pos < blockEnd {
pos++
}
if acceleration <= 0 {
acceleration = optimalAccelerationBase
}
steps := opts.matchState.resetSteps(optimalMatchStepSizeHint(blockEnd - blockStart))
var matchSource optimalMatchSource
var finder *levelOptimalMatchFinder
if opts.parser == compressorParserOptimal1 {
if opts.matchState != nil && opts.matchState.optimalFinder != nil {
finder = opts.matchState.optimalFinder
} else {
localFinder := newLevelOptimalMatchFinder(opts)
finder = &localFinder
}
} else {
if usePrecomputedSource {
matchSource = precomputedSource
if matchSource == nil {
matchSource = optimalBinaryMatchFinder(blockStart, blockEnd, opts)
}
} else if useBufferedMatches(opts) && !noHuffmanCosts {
matchSource = precomputeOptimalMatchSource(src, blockStart, blockEnd, opts, opts.parserIterations, noHuffmanCosts)
} else {
matchSource = optimalBinaryMatchFinder(blockStart, blockEnd, opts)
}
}
repOffsets := startRepOffsets
litStart := pos
for pos < blockEnd {
if acceleration >= optimalAccelerationLimit {
step := optimalGreedyFallbackStep(src, pos, litStart, blockStart, blockEnd, finder, matchSource, opts)
if step.length > 0 {
steps = append(steps, step)
repOffsets = updateOptimalRepOffsets(repOffsets, step.distance, advancedDistance)
pos = step.pos + step.length
litStart = pos
acceleration = optimalAccelerationBase
} else {
skip := acceleration >> optimalAccelerationThreshold
if skip < 1 {
skip = 1
}
pos += skip
if pos > blockEnd {
pos = blockEnd
}
acceleration++
}
continue
}
chunkSize := optimalParseChunkSize(opts)
parseEnd := pos + min(chunkSize, blockEnd-pos)
result := optimalParseResult{consumed: parseEnd, acceleration: acceleration}
if opts.parser == compressorParserOptimal1 {
result = optimalParseDetailedWithAcceleration(src, pos, parseEnd, blockEnd, finder, repOffsets, advancedDistance, opts, model, noHuffmanCosts, acceleration)
} else {
result = multiArrivalOptimalParseDetailedWithAcceleration(src, pos, parseEnd, blockEnd, matchSource, repOffsets, advancedDistance, opts, model, noHuffmanCosts, acceleration)
}
acceleration = result.acceleration
for _, step := range result.steps {
if step.pos < pos || step.pos+step.length > blockEnd {
continue
}
steps = append(steps, step)
repOffsets = updateOptimalRepOffsets(repOffsets, step.distance, advancedDistance)
pos = step.pos + step.length
litStart = pos
}
if result.consumed > pos {
pos = result.consumed
}
}
opts.matchState.keepSteps(steps)
return optimalBlockParseResult{steps: steps, acceleration: acceleration}
}
func optimalParseChunkSize(opts compressorLevelOptions) int {
chunkSize := opts.optimalBlockSize
if opts.parser >= compressorParserOptimal2 {
chunkSize--
}
if chunkSize < 1 {
return 1
}
return chunkSize
}
func optimalGreedyFallbackStep(src []byte, pos, litStart, blockStart, blockEnd int, finder *levelOptimalMatchFinder, matchSource optimalMatchSource, opts compressorLevelOptions) optimalMatchStep {
if opts.parser == compressorParserOptimal1 {
if finder == nil {
return optimalMatchStep{}
}
matches := finder.findMatchesAndUpdate(src, pos, blockEnd, 4)
if len(matches) == 0 {
return optimalMatchStep{}
}
match := matches[len(matches)-1]
distance := pos - match.pos
matchPos, length := extendOptimalMatchLeft(src, 0, pos, distance, match.length, pos-litStart)
return optimalMatchStep{pos: matchPos, length: length, distance: distance}
}
if matchSource == nil {
return optimalMatchStep{}
}
minLength := 4
if _, ok := matchSource.(*matchBuffer); ok {
minLength = 3
}
var matches []lzMatch
matches = matchSource.findLZMatchesAndUpdate(src, pos, 0, len(src)-lastBytes, blockEnd, minLength, opts, matches)
if len(matches) == 0 {
return optimalMatchStep{}
}
match := matches[len(matches)-1]
matchPos, length := extendOptimalMatchLeft(src, 0, pos, match.distance, match.length, pos-litStart)
if matchPos < blockStart {
return optimalMatchStep{}
}
return optimalMatchStep{pos: matchPos, length: length, distance: match.distance}
}
func optimalBinaryMatchFinder(blockStart, blockEnd int, opts compressorLevelOptions) *binaryMatchFinder {
if opts.matchState != nil && opts.matchState.binaryFinder != nil {
return opts.matchState.binaryFinder
}
return newBinaryMatchFinder(blockStart, blockEnd, opts)
}
func optimalParse(src []byte, start, end, blockEnd int, finder *levelOptimalMatchFinder, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool) []optimalMatchStep {
return optimalParseDetailed(src, start, end, blockEnd, finder, startRepOffsets, advancedDistance, opts, model, noHuffmanCosts).steps
}
func optimalParseDetailed(src []byte, start, end, blockEnd int, finder *levelOptimalMatchFinder, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool) optimalParseResult {
return optimalParseDetailedWithAcceleration(src, start, end, blockEnd, finder, startRepOffsets, advancedDistance, opts, model, noHuffmanCosts, optimalAccelerationBase)
}
func optimalParseDetailedWithAcceleration(src []byte, start, end, blockEnd int, finder *levelOptimalMatchFinder, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool, acceleration int) optimalParseResult {
if start >= end {
return optimalParseResult{consumed: start, acceleration: acceleration}
}
if acceleration <= 0 {
acceleration = optimalAccelerationBase
}
stateEnd := min(blockEnd, end+opts.niceLength)
const maxInt = int(^uint(0) >> 1)
var states []optimalParseState
if finder != nil {
states = finder.parseStates(stateEnd - start + 1)
} else {
states = acquireOptimalParseStates(stateEnd - start + 1)
defer releaseOptimalParseStates(states)
}
var stepScratch *[]optimalMatchStep
if finder != nil {
stepScratch = &finder.stepScratch
}
for i := range states {
states[i].cost = maxInt
}
states[0] = optimalParseState{
cost: optimal1InitialCost,
prev: -1,
repOffsets: startRepOffsets,
}
positionSkip := 0
matchDistanceLimit := maxMatchDistance(opts)
repCount := 1
if advancedDistance {
repCount = 3
}
terminalRepeatLength := opts.niceLength / 2
for pos := start; pos < end; pos++ {
index := pos - start
current := states[index]
if current.cost == maxInt {
finder.updatePosition(src, pos, blockEnd)
continue
}
if positionSkip > 0 || current.cost >= states[index+1].cost {
finder.updatePosition(src, pos, blockEnd)
positionSkip--
continue
}
literalCost := current.cost + optimalLiteralCost(src, pos, current.litRun, current.repOffsets, model, noHuffmanCosts)
if literalCost < states[index+1].cost {
next := current
next.cost = literalCost
next.prev = index
next.matchLen = 0
next.distance = 0
next.litRun = current.litRun + 1
states[index+1] = next
}
normalLastLength := 1
for rep := 0; rep < repCount; rep++ {
distance := current.repOffsets[rep]
if distance <= 0 || distance > matchDistanceLimit || pos+2 > blockEnd {
continue
}
prev := pos - distance
if prev < 0 {
continue
}
length := commonMatchLengthUnchecked(src, pos, prev, blockEnd)
if length < 2 {
continue
}
if length >= terminalRepeatLength {
finder.updatePosition(src, pos, blockEnd)
updateOptimalFinderTerminalOverlap(finder, src, pos, distance, length, blockEnd, opts)
steps := backtrackOptimalSteps(states, start, index, stepScratch)
steps = append(steps, optimalMatchStep{pos: pos, length: length, distance: distance})
return optimalParseResult{steps: steps, consumed: pos + length, acceleration: acceleration}
}
limit := min(length, stateEnd-pos)
relaxOptimalMatchWithDistancePenalty(states, index, limit, distance, current, advancedDistance, model, noHuffmanCosts, false)
normalLastLength = noHuffmanStoredMatchLength(length, noHuffmanCosts) + 1
positionSkip = 1
if length >= 3 {
acceleration = optimalAccelerationBase
}
break
}
matches := finder.findMatchesAndUpdate(src, pos, blockEnd, normalLastLength)
if len(matches) == 0 {
acceleration++
if acceleration >= optimalAccelerationLimit {
return finishOptimalParseResult(states, start, index+1, opts.niceLength, 0, acceleration, stepScratch)
}
continue
}
if len(matches) > 0 {
longest := matches[len(matches)-1]
if longest.length >= opts.niceLength {
distance := pos - longest.pos
matchPos, matchLength := extendOptimalMatchLeft(src, 0, pos, distance, longest.length, current.litRun)
matchIndex := matchPos - start
if matchIndex >= 0 && matchIndex < len(states) && states[matchIndex].cost != maxInt && distance > 0 {
updateOptimalFinderTerminalOverlap(finder, src, matchPos, distance, matchLength, blockEnd, opts)
steps := backtrackOptimalSteps(states, start, matchIndex, stepScratch)
steps = append(steps, optimalMatchStep{pos: matchPos, length: matchLength, distance: distance})
return optimalParseResult{steps: steps, consumed: matchPos + matchLength, acceleration: acceleration}
}
}
if longest.length >= 4 {
acceleration = optimalAccelerationBase
}
}
for i := len(matches) - 1; i >= 0; i-- {
match := matches[i]
distance := pos - match.pos
matchPos, matchLength := extendOptimalMatchLeft(src, 0, pos, distance, match.length, current.litRun)
matchIndex := matchPos - start
if matchIndex < 0 || matchIndex >= len(states) || states[matchIndex].cost == maxInt {
continue
}
matchState := states[matchIndex]
limit := min(matchLength, stateEnd-matchPos)
if limit < 3 || distance <= 0 {
continue
}
length, nextIndex, cost, improves := optimalMatchCandidate(states, matchIndex, limit, distance, matchState, advancedDistance, model, noHuffmanCosts, true)
if nextIndex < 0 || nextIndex >= len(states) {
continue
}
if !improves {
break
}
setOptimalMatchState(states, matchIndex, nextIndex, length, distance, matchState, advancedDistance, cost)
}
}
return finishOptimalParseResult(states, start, end-start, opts.niceLength, end, acceleration, stepScratch)
}
func finishOptimalParseResult(states []optimalParseState, start, best, niceLength, consumed, acceleration int, stepScratch *[]optimalMatchStep) optimalParseResult {
const maxInt = int(^uint(0) >> 1)
if best >= len(states) {
best = len(states) - 1
}
if best < 0 {
best = 0
}
bestCost := states[best].cost
for offset := 1; offset < niceLength && best+offset < len(states); offset++ {
candidate := best + offset
if states[candidate].cost <= bestCost {
best = candidate
bestCost = states[candidate].cost
}
}
for best > 0 && states[best].cost == maxInt {
best--
}
if consumed == 0 {
consumed = start + best
}
if best == 0 {
return optimalParseResult{consumed: consumed, acceleration: acceleration}
}
return optimalParseResult{steps: backtrackOptimalSteps(states, start, best, stepScratch), consumed: consumed, acceleration: acceleration}
}
func updateOptimalFinderTerminalOverlap(finder *levelOptimalMatchFinder, src []byte, pos, distance, length, blockEnd int, opts compressorLevelOptions) {
updateEnd := pos + min(min(distance, length), opts.niceLength)
if updateEnd > blockEnd {
updateEnd = blockEnd
}
for updatePos := pos + 1; updatePos < updateEnd; updatePos++ {
finder.updatePosition(src, updatePos, blockEnd)
}
}
func backtrackOptimalSteps(states []optimalParseState, start, best int, stepScratch *[]optimalMatchStep) []optimalMatchStep {
var steps []optimalMatchStep
if stepScratch != nil {
steps = (*stepScratch)[:0]
} else {
steps = make([]optimalMatchStep, 0, 16)
}
for index := best; index > 0; {
state := states[index]
if state.prev < 0 {
break
}
if state.matchLen > 0 {
steps = append(steps, optimalMatchStep{
pos: start + state.prev,
length: state.matchLen,
distance: state.distance,
})
}
index = state.prev
}
if len(steps) == 0 {
if stepScratch != nil {
if cap(steps) < 1 {
steps = make([]optimalMatchStep, 0, 1)
}
*stepScratch = steps
}
return steps
}
for left, right := 0, len(steps)-1; left < right; left, right = left+1, right-1 {
steps[left], steps[right] = steps[right], steps[left]
}
if stepScratch != nil {
*stepScratch = steps
}
return steps
}
func extendOptimalMatchLeft(src []byte, inputStart, pos, distance, length, literalRun int) (int, int) {
back := pos - distance
literalRunStart := pos - literalRun
for back > inputStart && pos > literalRunStart && pos-1 >= 0 && back-1 >= 0 && src[pos-1] == src[back-1] {
pos--
back--
length++
}
return pos, length
}
func multiArrivalOptimalParse(src []byte, start, end, blockEnd int, matchSource optimalMatchSource, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool) []optimalMatchStep {
return multiArrivalOptimalParseDetailed(src, start, end, blockEnd, matchSource, startRepOffsets, advancedDistance, opts, model, noHuffmanCosts).steps
}
func multiArrivalOptimalParseDetailed(src []byte, start, end, blockEnd int, matchSource optimalMatchSource, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool) optimalParseResult {
return multiArrivalOptimalParseDetailedWithAcceleration(src, start, end, blockEnd, matchSource, startRepOffsets, advancedDistance, opts, model, noHuffmanCosts, optimalAccelerationBase)
}
func multiArrivalOptimalParseDetailedWithAcceleration(src []byte, start, end, blockEnd int, matchSource optimalMatchSource, startRepOffsets [3]int, advancedDistance bool, opts compressorLevelOptions, model *optimalCostModel, noHuffmanCosts bool, acceleration int) optimalParseResult {
if start >= end {
return optimalParseResult{consumed: start, acceleration: acceleration}
}
if acceleration <= 0 {
acceleration = optimalAccelerationBase
}
stateEnd := min(blockEnd, end+opts.niceLength)
maxArrivals := opts.maxArrivals
if maxArrivals <= 0 {
maxArrivals = 1
}
if maxArrivals > 16 {
maxArrivals = 16
}
const maxInt = int(^uint(0) >> 1)
stateCount := (stateEnd - start + 1) * maxArrivals
states := acquireOptimalParseStates(stateCount)
defer releaseOptimalParseStates(states)
for i := range states {
states[i].cost = maxInt
}
states[0] = optimalParseState{
cost: multiArrivalInitialCost,
prev: -1,
prevPath: -1,
repOffsets: startRepOffsets,
}
var matches []lzMatch
var stepScratch *[]optimalMatchStep
if opts.matchState != nil {
stepScratch = &opts.matchState.backtrackScratch
}
matchDistanceLimit := maxMatchDistance(opts)
for pos := start; pos < end; pos++ {
index := pos - start
nextBase := (index + 1) * maxArrivals
if states[index*maxArrivals].cost == maxInt {
updateOptimalMatchSourcePosition(matchSource, src, pos, opts)
continue
}
nextExpectedLength := 2
for path := 0; path < maxArrivals; path++ {
current := states[index*maxArrivals+path]
if current.cost == maxInt {
break
}
if multiArrivalCostPruned(current.cost, states[nextBase].cost, optimalCostScale*maxArrivals) {
break
}
literalCost := current.cost + optimalLiteralCost(src, pos, current.litRun, current.repOffsets, model, noHuffmanCosts)
insertOptimalArrival(states, maxArrivals, index+1, index, path, 0, 0, literalCost, current.repOffsets, current.litRun+1)
repCount := 1
if advancedDistance {
repCount = 3
}
for rep := 0; rep < repCount; rep++ {
distance := current.repOffsets[rep]
if distance <= 0 || distance > matchDistanceLimit || pos-distance < 0 || pos+2 > blockEnd {
continue
}
length := commonMatchLengthUnchecked(src, pos, pos-distance, blockEnd)
if length < nextExpectedLength {
continue
}
if length >= opts.niceLength/2 {
updateOptimalMatchSourceTerminalOverlap(matchSource, src, pos, distance, length, opts)
steps := backtrackMultiArrivalSteps(states, maxArrivals, start, index, path, stepScratch)
steps = append(steps, optimalMatchStep{pos: pos, length: length, distance: distance})
if stepScratch != nil {
*stepScratch = steps
}
return optimalParseResult{steps: steps, consumed: pos + length, acceleration: acceleration}
}
limit := min(length, stateEnd-pos)
relaxMultiArrivalRepMatches(states, maxArrivals, index, path, limit, nextExpectedLength, distance, current, advancedDistance, model, noHuffmanCosts)
nextExpectedLength = limit
if length >= 3 {
acceleration = optimalAccelerationBase
}
}
}
if multiArrivalCostPruned(states[index*maxArrivals].cost, states[nextBase].cost, optimalCostScale*(maxArrivals/8)) {
updateOptimalMatchSourcePosition(matchSource, src, pos, opts)
continue
}
matches = matches[:0]
if matchSource != nil {
matches = matchSource.findLZMatchesAndUpdate(src, pos, 0, len(src)-lastBytes, blockEnd, nextExpectedLength, opts, matches)
}
if len(matches) == 0 {
if opts.parser < compressorParserOptimal3 {
acceleration++
if acceleration >= optimalAccelerationLimit {
return finishMultiArrivalParseResult(states, maxArrivals, start, index+1, opts.niceLength, 0, acceleration, stepScratch)
}
}
continue
}
if len(matches) > 0 {
longest := matches[len(matches)-1]
if longest.length >= opts.niceLength {
updateOptimalMatchSourceTerminalOverlap(matchSource, src, pos, longest.distance, longest.length, opts)
steps := backtrackMultiArrivalSteps(states, maxArrivals, start, index, 0, stepScratch)
steps = append(steps, optimalMatchStep{pos: pos, length: longest.length, distance: longest.distance})
if stepScratch != nil {
*stepScratch = steps
}
return optimalParseResult{steps: steps, consumed: pos + longest.length, acceleration: acceleration}
}
if longest.length >= 4 {
acceleration = optimalAccelerationBase
}
}
pathMax := min(maxArrivals, 2)
for path := 0; path < pathMax; path++ {
current := states[index*maxArrivals+path]
if current.cost == maxInt {
break
}
if multiArrivalCostPruned(current.cost, states[nextBase].cost, optimalCostScale*maxArrivals) {
break
}
nextMatchReductionLimit := nextExpectedLength
for _, match := range matches {
distance := match.distance
limit := min(match.length, stateEnd-pos)
if distance <= 0 || distance == current.repOffsets[0] || limit < nextExpectedLength {
continue
}
relaxMultiArrivalNormalMatches(states, maxArrivals, index, path, limit, nextMatchReductionLimit, distance, current, advancedDistance, model, noHuffmanCosts)
nextMatchReductionLimit = limit
}
}
}
return finishMultiArrivalParseResult(states, maxArrivals, start, end-start, opts.niceLength, end, acceleration, stepScratch)
}
func finishMultiArrivalParseResult(states []optimalParseState, maxArrivals, start, bestIndex, niceLength, consumed, acceleration int, stepScratch *[]optimalMatchStep) optimalParseResult {
const maxInt = int(^uint(0) >> 1)
limit := len(states) / maxArrivals
if bestIndex >= limit {
bestIndex = limit - 1
}
if bestIndex < 0 {
bestIndex = 0
}
bestPath := 0
bestCost := states[bestIndex*maxArrivals].cost
for offset := 1; offset < niceLength && bestIndex+offset < limit; offset++ {
candidate := bestIndex + offset
if cost := states[candidate*maxArrivals].cost; cost <= bestCost {
bestIndex = candidate
bestCost = cost
}
}
if consumed == 0 {
consumed = start + bestIndex
}
if bestCost == maxInt {
return optimalParseResult{consumed: consumed, acceleration: acceleration}
}
return optimalParseResult{steps: backtrackMultiArrivalSteps(states, maxArrivals, start, bestIndex, bestPath, stepScratch), consumed: consumed, acceleration: acceleration}
}
func updateOptimalMatchSourceTerminalOverlap(matchSource optimalMatchSource, src []byte, pos, distance, length int, opts compressorLevelOptions) {
finder, ok := matchSource.(*binaryMatchFinder)
if !ok {
return
}
updateEnd := pos + min(min(distance, length), opts.niceLength)
blockEnd := len(src) - lastBytes
if updateEnd > blockEnd {
updateEnd = blockEnd
}
for updatePos := pos + 1; updatePos < updateEnd; updatePos++ {
finder.updatePosition(src, updatePos, 0, blockEnd, opts)
}
}
func backtrackMultiArrivalSteps(states []optimalParseState, maxArrivals, start, index, path int, stepScratch *[]optimalMatchStep) []optimalMatchStep {
originalIndex := index
originalPath := path
count := 0
for index > 0 {
state := states[index*maxArrivals+path]
if state.prev < 0 {
break
}
if state.matchLen > 0 {
count++
}
index, path = state.prev, state.prevPath
if path < 0 {
break
}
}
if count == 0 {
return nil
}
var steps []optimalMatchStep
if stepScratch != nil {
if cap(*stepScratch) < count {
releaseOptimalMatchSteps(*stepScratch)
*stepScratch = acquireOptimalMatchSteps(count)
}
steps = (*stepScratch)[:count]
} else {
steps = make([]optimalMatchStep, count)
}
write := count - 1
index = originalIndex
path = originalPath
for index > 0 {
state := states[index*maxArrivals+path]
if state.prev < 0 {
break
}
if state.matchLen > 0 {
steps[write] = optimalMatchStep{
pos: start + state.prev,
length: state.matchLen,
distance: state.distance,
}
write--
}
index, path = state.prev, state.prevPath
if path < 0 {
break
}
}
if stepScratch != nil {
*stepScratch = steps
}
return steps
}
func multiArrivalCostPruned(currentCost, nextCost, slack int) bool {
const maxInt = int(^uint(0) >> 1)
return currentCost != maxInt && nextCost != maxInt && currentCost >= slack && currentCost-slack >= nextCost
}
func updateOptimalMatchSourcePosition(matchSource optimalMatchSource, src []byte, pos int, opts compressorLevelOptions) {
if finder, ok := matchSource.(*binaryMatchFinder); ok {
finder.updatePosition(src, pos, 0, len(src)-lastBytes, opts)
}
}
func relaxMultiArrivalRepMatches(states []optimalParseState, maxArrivals, index, path, maxLength, nextExpectedLength, distance int, current optimalParseState, advancedDistance bool, model *optimalCostModel, noHuffmanCosts bool) {
if maxLength < 2 {
return
}
lower := nextExpectedLength
if noHuffmanCosts {
lower = maxLength
} else if maxLength-lower > 15 {
lower = maxLength - 15
}
for length := maxLength; length >= lower; length-- {
relaxMultiArrivalRepMatch(states, maxArrivals, index, path, length, distance, current, advancedDistance, model, noHuffmanCosts)
}
}
func relaxMultiArrivalNormalMatches(states []optimalParseState, maxArrivals, index, path, maxLength, nextMatchReductionLimit, distance int, current optimalParseState, advancedDistance bool, model *optimalCostModel, noHuffmanCosts bool) {
if maxLength < 3 {
return
}
lower := nextMatchReductionLimit
if maxLength != nextMatchReductionLimit {
lower = nextMatchReductionLimit + 1
}
if noHuffmanCosts {
lower = maxLength
} else if maxLength-lower > 15 {
lower = maxLength - 15
}
for length := maxLength; length >= lower; length-- {
relaxMultiArrivalMatch(states, maxArrivals, index, path, length, distance, current, advancedDistance, model, noHuffmanCosts)
}
}
func relaxMultiArrivalMatch(states []optimalParseState, maxArrivals, index, path, length, distance int, current optimalParseState, advancedDistance bool, model *optimalCostModel, noHuffmanCosts bool) {
relaxMultiArrivalMatchWithDistancePenalty(states, maxArrivals, index, path, length, distance, current, advancedDistance, model, noHuffmanCosts, true)
}
func relaxMultiArrivalRepMatch(states []optimalParseState, maxArrivals, index, path, length, distance int, current optimalParseState, advancedDistance bool, model *optimalCostModel, noHuffmanCosts bool) {
relaxMultiArrivalMatchWithDistancePenalty(states, maxArrivals, index, path, length, distance, current, advancedDistance, model, noHuffmanCosts, false)
}
func relaxMultiArrivalMatchWithDistancePenalty(states []optimalParseState, maxArrivals, index, path, length, distance int, current optimalParseState, advancedDistance bool, model *optimalCostModel, noHuffmanCosts bool, longDistanceSpeedPenalty bool) {
length = noHuffmanStoredMatchLength(length, noHuffmanCosts)
nextIndex := index + length
if nextIndex >= len(states)/maxArrivals {
return
}
cost := current.cost + optimalMatchCostWithDistancePenalty(length, distance, current.litRun, current.repOffsets, advancedDistance, model, noHuffmanCosts, longDistanceSpeedPenalty)
repOffsets := updateOptimalRepOffsets(current.repOffsets, distance, advancedDistance)
insertOptimalArrival(states, maxArrivals, nextIndex, index, path, length, distance, cost, repOffsets, 0)
}
func insertOptimalArrival(states []optimalParseState, maxArrivals, index, prev, prevPath, matchLen, distance, cost int, repOffsets [3]int, litRun int) {
base := index * maxArrivals
limit := base + maxArrivals
for slot := base; slot < limit; slot++ {
if states[slot].cost <= cost && states[slot].repOffsets[0] == repOffsets[0] {
return
}
if cost >= states[slot].cost {
continue
}
copy(states[slot+1:limit], states[slot:limit-1])
states[slot] = optimalParseState{
cost: cost,
prev: prev,
prevPath: prevPath,
matchLen: matchLen,
distance: distance,
litRun: litRun,
repOffsets: repOffsets,
}
return