-
Notifications
You must be signed in to change notification settings - Fork 16
/
ROLZCodec.go
1560 lines (1270 loc) · 35.6 KB
/
ROLZCodec.go
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
/*
Copyright 2011-2024 Frederic Langlet
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
you may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package transform
import (
"encoding/binary"
"errors"
"fmt"
"math/bits"
"strings"
kanzi "github.com/flanglet/kanzi-go/v2"
"github.com/flanglet/kanzi-go/v2/bitstream"
"github.com/flanglet/kanzi-go/v2/entropy"
"github.com/flanglet/kanzi-go/v2/internal"
)
// Implementation of a Reduced Offset Lempel Ziv transform
// More information about ROLZ at http://ezcodesample.com/rolz/rolz_article.html
const (
_ROLZ_HASH_SIZE = 1 << 16
_ROLZ_MIN_MATCH3 = 3
_ROLZ_MIN_MATCH4 = 4
_ROLZ_MIN_MATCH7 = 7
_ROLZ_MAX_MATCH1 = _ROLZ_MIN_MATCH3 + 65535
_ROLZ_MAX_MATCH2 = _ROLZ_MIN_MATCH3 + 255
_ROLZ_LOG_POS_CHECKS1 = 4
_ROLZ_LOG_POS_CHECKS2 = 5
_ROLZ_CHUNK_SIZE = 16 * 1024 * 1024
_ROLZ_HASH_MASK = ^uint32(_ROLZ_CHUNK_SIZE - 1)
_ROLZ_MATCH_FLAG = 0
_ROLZ_LITERAL_FLAG = 1
_ROLZ_MATCH_CTX = 0
_ROLZ_LITERAL_CTX = 1
_ROLZ_HASH_SEED = 200002979
_ROLZ_MAX_BLOCK_SIZE = 1 << 30 // 1 GB
_ROLZ_MIN_BLOCK_SIZE = 64
_ROLZ_PSCALE = 0xFFFF
_ROLZ_TOP = uint64(0x00FFFFFFFFFFFFFF)
_MASK_0_56 = uint64(0x00FFFFFFFFFFFFFF)
_MASK_0_32 = uint64(0x00000000FFFFFFFF)
)
func getKey1(p []byte) uint32 {
return uint32(binary.LittleEndian.Uint16(p))
}
func getKey2(p []byte) uint32 {
return uint32((binary.LittleEndian.Uint64(p)*_ROLZ_HASH_SEED)>>40) & 0xFFFF
}
func rolzhash(p []byte) uint32 {
return ((binary.LittleEndian.Uint32(p) << 8) * _ROLZ_HASH_SEED) & _ROLZ_HASH_MASK
}
func emitCopy(buf []byte, dstIdx, ref, matchLen int) int {
for matchLen >= 8 {
buf[dstIdx] = buf[ref]
buf[dstIdx+1] = buf[ref+1]
buf[dstIdx+2] = buf[ref+2]
buf[dstIdx+3] = buf[ref+3]
buf[dstIdx+4] = buf[ref+4]
buf[dstIdx+5] = buf[ref+5]
buf[dstIdx+6] = buf[ref+6]
buf[dstIdx+7] = buf[ref+7]
dstIdx += 8
ref += 8
matchLen -= 8
}
for matchLen != 0 {
buf[dstIdx] = buf[ref]
dstIdx++
ref++
matchLen--
}
return dstIdx
}
// ROLZCodec Reduced Offset Lempel Ziv codec
type ROLZCodec struct {
delegate kanzi.ByteTransform
}
// NewROLZCodec creates a new instance of ROLZCodec providing
// he log of the number of matches to check for during encoding.
func NewROLZCodec(logPosChecks uint) (*ROLZCodec, error) {
this := &ROLZCodec{}
d, err := newROLZCodec1(logPosChecks)
this.delegate = d
return this, err
}
// NewROLZCodecWithFlag creates a new instance of ROLZCodec
// If the bool parameter is false, encode literals and matches using ANS.
// Otherwise encode literals and matches using CM and check more match
// positions.
func NewROLZCodecWithFlag(extra bool) (*ROLZCodec, error) {
this := &ROLZCodec{}
var err error
var d kanzi.ByteTransform
if extra {
d, err = newROLZCodec2(_ROLZ_LOG_POS_CHECKS2)
} else {
d, err = newROLZCodec1(_ROLZ_LOG_POS_CHECKS1)
}
this.delegate = d
return this, err
}
// NewROLZCodecWithCtx creates a new instance of ROLZCodec providing a
// context map. If the map contains a transform name set to "ROLZX"
// encode literals and matches using ANS. Otherwise encode literals
// and matches using CM and check more match positions.
func NewROLZCodecWithCtx(ctx *map[string]any) (*ROLZCodec, error) {
this := &ROLZCodec{}
var err error
var d kanzi.ByteTransform
if val, containsKey := (*ctx)["transform"]; containsKey {
transform := val.(string)
if strings.Contains(transform, "ROLZX") {
d, err = newROLZCodec2WithCtx(_ROLZ_LOG_POS_CHECKS2, ctx)
this.delegate = d
}
}
if this.delegate == nil && err == nil {
d, err = newROLZCodec1WithCtx(_ROLZ_LOG_POS_CHECKS1, ctx)
this.delegate = d
}
return this, err
}
// Forward applies the function to the src and writes the result
// to the destination. Returns number of bytes read, number of bytes
// written and possibly an error.
func (this *ROLZCodec) Forward(src, dst []byte) (uint, uint, error) {
if len(src) == 0 {
return 0, 0, nil
}
if len(src) < _ROLZ_MIN_BLOCK_SIZE {
return 0, 0, errors.New("ROLZ codec: Block too small, skip")
}
if &src[0] == &dst[0] {
return 0, 0, errors.New("ROLZ codec: Input and output buffers cannot be equal")
}
if len(src) > _ROLZ_MAX_BLOCK_SIZE {
return 0, 0, fmt.Errorf("The max ROLZ codec block size is %d, got %d", _ROLZ_MAX_BLOCK_SIZE, len(src))
}
return this.delegate.Forward(src, dst)
}
// Inverse applies the reverse function to the src and writes the result
// to the destination. Returns number of bytes read, number of bytes
// written and possibly an error.
func (this *ROLZCodec) Inverse(src, dst []byte) (uint, uint, error) {
if len(src) == 0 {
return 0, 0, nil
}
if &src[0] == &dst[0] {
return 0, 0, errors.New("ROLZ codec: Input and output buffers cannot be equal")
}
if len(src) > _ROLZ_MAX_BLOCK_SIZE {
return 0, 0, fmt.Errorf("The max ROLZ codec block size is %d, got %d", _ROLZ_MAX_BLOCK_SIZE, len(src))
}
return this.delegate.Inverse(src, dst)
}
// MaxEncodedLen returns the max size required for the encoding output buffer
func (this *ROLZCodec) MaxEncodedLen(srcLen int) int {
return this.delegate.MaxEncodedLen(srcLen)
}
// Use ANS to encode/decode literals and matches
type rolzCodec1 struct {
matches []uint32
counters []int32
logPosChecks uint
maskChecks int32
posChecks int32
minMatch int
ctx *map[string]any
}
func newROLZCodec1(logPosChecks uint) (*rolzCodec1, error) {
this := &rolzCodec1{}
if (logPosChecks < 2) || (logPosChecks > 8) {
return nil, fmt.Errorf("ROLZ codec: Invalid logPosChecks parameter: %d (must be in [2..8])", logPosChecks)
}
this.logPosChecks = logPosChecks
this.posChecks = 1 << logPosChecks
this.maskChecks = this.posChecks - 1
this.counters = make([]int32, 1<<16)
this.matches = make([]uint32, _ROLZ_HASH_SIZE<<logPosChecks)
return this, nil
}
func newROLZCodec1WithCtx(logPosChecks uint, ctx *map[string]any) (*rolzCodec1, error) {
this := &rolzCodec1{}
if (logPosChecks < 2) || (logPosChecks > 8) {
return nil, fmt.Errorf("ROLZ codec: Invalid logPosChecks parameter: %d (must be in [2..8])", logPosChecks)
}
this.logPosChecks = logPosChecks
this.posChecks = 1 << logPosChecks
this.maskChecks = this.posChecks - 1
this.counters = make([]int32, 1<<16)
this.matches = make([]uint32, _ROLZ_HASH_SIZE<<logPosChecks)
this.ctx = ctx
return this, nil
}
// findMatch returns match position index (logPosChecks bits) + length (8 bits) or -1
func (this *rolzCodec1) findMatch(buf []byte, pos int, hash32 uint32, counter int32, matches []uint32) (int, int) {
maxMatch := min(_ROLZ_MAX_MATCH1, len(buf)-pos)
if maxMatch < this.minMatch {
return -1, -1
}
if this.posChecks == 0 {
// Ahem terrible hack ...
// This impossible branch improves performance by a few percents
// (due to speculative memory fetch in the other branch probably)
return -1, -1
}
maxMatch -= 4
bestLen := 0
bestIdx := -1
curBuf := buf[pos:]
// Check all recorded positions
for i := counter; i > counter-this.posChecks; i-- {
ref := matches[i&this.maskChecks]
// Hash check may save a memory access ...
if ref&_ROLZ_HASH_MASK != hash32 {
continue
}
ref &= ^_ROLZ_HASH_MASK
refBuf := buf[ref:]
if refBuf[bestLen] != curBuf[bestLen] {
continue
}
n := 0
for n < maxMatch {
if diff := binary.LittleEndian.Uint32(refBuf[n:]) ^ binary.LittleEndian.Uint32(curBuf[n:]); diff != 0 {
n += (bits.TrailingZeros32(diff) >> 3)
break
}
n += 4
}
if n > bestLen {
bestIdx = int(i)
bestLen = n
if bestLen == maxMatch {
break
}
}
}
if bestLen < this.minMatch {
return -1, -1
}
return int(counter) - bestIdx, bestLen - this.minMatch
}
// Forward applies the function to the src and writes the result
// to the destination. Returns number of bytes read, number of bytes
// written and possibly an error.
func (this *rolzCodec1) Forward(src, dst []byte) (uint, uint, error) {
if n := this.MaxEncodedLen(len(src)); len(dst) < n {
return 0, 0, fmt.Errorf("ROLZ codec: Output buffer is too small - size: %d, required %d", len(dst), n)
}
srcEnd := len(src) - 4
binary.BigEndian.PutUint32(dst[0:], uint32(len(src)))
sizeChunk := len(src)
if sizeChunk > _ROLZ_CHUNK_SIZE {
sizeChunk = _ROLZ_CHUNK_SIZE
}
startChunk := 0
litBuf := make([]byte, this.MaxEncodedLen(sizeChunk))
lenBuf := make([]byte, sizeChunk/5)
mIdxBuf := make([]byte, sizeChunk/4)
tkBuf := make([]byte, sizeChunk/4)
var err error
for i := range this.counters {
this.counters[i] = 0
}
litOrder := uint(1)
if len(src) < 1<<17 {
litOrder = 0
}
flags := byte(litOrder)
this.minMatch = _ROLZ_MIN_MATCH3
delta := 2
if this.ctx != nil {
dt := internal.DT_UNDEFINED
if val, containsKey := (*this.ctx)["dataType"]; containsKey {
dt = val.(internal.DataType)
}
if dt == internal.DT_UNDEFINED {
var freqs0 [256]int
internal.ComputeHistogram(src, freqs0[:], true, false)
dt = internal.DetectSimpleType(len(src), freqs0[:])
if dt != internal.DT_UNDEFINED {
(*this.ctx)["dataType"] = dt
}
}
if dt == internal.DT_EXE {
delta = 3
flags |= 8
} else if dt == internal.DT_DNA {
delta = 8
this.minMatch = _ROLZ_MIN_MATCH7
flags |= 4
} else if dt == internal.DT_MULTIMEDIA {
delta = 8
this.minMatch = _ROLZ_MIN_MATCH4
flags |= 2
}
}
flags |= byte(this.logPosChecks << 4)
dst[4] = flags
srcIdx := 0
dstIdx := 5
// Main loop
for startChunk < srcEnd {
litIdx := 0
lenIdx := 0
mIdx := 0
tkIdx := 0
for i := range this.matches {
this.matches[i] = 0
}
endChunk := startChunk + sizeChunk
if endChunk >= srcEnd {
endChunk = srcEnd
sizeChunk = endChunk - startChunk
}
buf := src[startChunk:endChunk]
srcIdx = 0
n := min(srcEnd-startChunk, 8)
for j := 0; j < n; j++ {
litBuf[litIdx] = buf[srcIdx]
litIdx++
srcIdx++
}
firstLitIdx := srcIdx
srcInc := 0
// Next chunk
for srcIdx < sizeChunk {
var key uint32
if this.minMatch == _ROLZ_MIN_MATCH3 {
key = getKey1(buf[srcIdx-delta:])
} else {
key = getKey2(buf[srcIdx-delta:])
}
m := this.matches[key<<this.logPosChecks : (key+1)<<this.logPosChecks]
hash32 := rolzhash(buf[srcIdx : srcIdx+4])
matchIdx, matchLen := this.findMatch(buf, srcIdx, hash32, this.counters[key], m)
// Register current position
this.counters[key] = (this.counters[key] + 1) & this.maskChecks
m[this.counters[key]] = hash32 | uint32(srcIdx)
if matchIdx < 0 {
srcIdx++
srcIdx += (srcInc >> 6)
srcInc++
continue
}
{
// Check if better match at next position
if this.minMatch == _ROLZ_MIN_MATCH3 {
key = getKey1(buf[srcIdx+1-delta:])
} else {
key = getKey2(buf[srcIdx+1-delta:])
}
m = this.matches[key<<this.logPosChecks : (key+1)<<this.logPosChecks]
hash32 = rolzhash(buf[srcIdx+1 : srcIdx+5])
matchIdx2, matchLen2 := this.findMatch(buf, srcIdx+1, hash32, this.counters[key], m)
if (matchIdx2 >= 0) && (matchLen2 > matchLen) {
// New match is better
matchIdx = matchIdx2
matchLen = matchLen2
srcIdx++
// Register current position
this.counters[key] = (this.counters[key] + 1) & this.maskChecks
m[this.counters[key]] = hash32 | uint32(srcIdx)
}
}
// mode LLLLLMMM -> L lit length, M match length
litLen := srcIdx - firstLitIdx
var mode byte
if matchLen >= 7 {
mode = 7
lenIdx += emitLengthROLZ(lenBuf[lenIdx:], matchLen-7)
} else {
mode = byte(matchLen)
}
// Emit literals
if litLen > 0 {
if litLen >= 31 {
mode |= 0xF8
lenIdx += emitLengthROLZ(lenBuf[lenIdx:], litLen-31)
} else {
mode |= byte(litLen << 3)
}
copy(litBuf[litIdx:], buf[firstLitIdx:firstLitIdx+litLen])
litIdx += litLen
} else {
mode |= byte(litLen << 3)
}
tkBuf[tkIdx] = mode
tkIdx++
// Emit match index
mIdxBuf[mIdx] = byte(matchIdx)
mIdx++
srcIdx += (matchLen + this.minMatch)
firstLitIdx = srcIdx
srcInc = 0
}
// Emit last chunk literals
srcIdx = sizeChunk
litLen := srcIdx - firstLitIdx
if tkIdx != 0 {
// At least one match to emit
if litLen >= 31 {
tkBuf[tkIdx] = 0xF8
} else {
tkBuf[tkIdx] = byte(litLen << 3)
}
tkIdx++
}
// Emit literals
if litLen > 0 {
if litLen >= 31 {
lenIdx += emitLengthROLZ(lenBuf[lenIdx:], litLen-31)
}
copy(litBuf[litIdx:], buf[firstLitIdx:firstLitIdx+litLen])
litIdx += litLen
}
os := internal.NewBufferStream(make([]byte, 0, sizeChunk/4))
// Scope to deallocate resources early
{
// Encode literal, length and match index buffers
var obs kanzi.OutputBitStream
if obs, err = bitstream.NewDefaultOutputBitStream(os, 65536); err != nil {
break
}
obs.WriteBits(uint64(litIdx), 32)
obs.WriteBits(uint64(tkIdx), 32)
obs.WriteBits(uint64(lenIdx), 32)
obs.WriteBits(uint64(mIdx), 32)
var litEnc *entropy.ANSRangeEncoder
if litEnc, err = entropy.NewANSRangeEncoder(obs, litOrder); err != nil {
goto End
}
if _, err = litEnc.Write(litBuf[0:litIdx]); err != nil {
goto End
}
litEnc.Dispose()
var mEnc *entropy.ANSRangeEncoder
if mEnc, err = entropy.NewANSRangeEncoder(obs, 0, 32768); err != nil {
goto End
}
if _, err = mEnc.Write(tkBuf[0:tkIdx]); err != nil {
goto End
}
if _, err = mEnc.Write(lenBuf[0:lenIdx]); err != nil {
goto End
}
if _, err = mEnc.Write(mIdxBuf[0:mIdx]); err != nil {
goto End
}
mEnc.Dispose()
obs.Close()
}
// Copy bitstream array to output
bufSize := os.Len()
if dstIdx+bufSize > len(dst) {
err = errors.New("ROLZ codec: Destination buffer too small")
break
}
if _, err = os.Read(dst[dstIdx : dstIdx+bufSize]); err != nil {
break
}
dstIdx += bufSize
startChunk = endChunk
}
End:
if err == nil {
if dstIdx+4 > len(dst) {
err = errors.New("ROLZ codec: Destination buffer too small")
} else {
// Emit last literals
srcIdx += (startChunk - sizeChunk)
dst[dstIdx] = src[srcIdx]
dst[dstIdx+1] = src[srcIdx+1]
dst[dstIdx+2] = src[srcIdx+2]
dst[dstIdx+3] = src[srcIdx+3]
srcIdx += 4
dstIdx += 4
if srcIdx != len(src) {
err = errors.New("ROLZ codec: Destination buffer too small")
} else if dstIdx >= len(src) {
err = errors.New("ROLZ codec: No compression")
}
}
}
return uint(srcIdx), uint(dstIdx), err
}
// Inverse applies the reverse function to the src and writes the result
// to the destination. Returns number of bytes read, number of bytes
// written and possibly an error.
func (this *rolzCodec1) Inverse(src, dst []byte) (uint, uint, error) {
dstEnd := int(binary.BigEndian.Uint32(src[0:])) - 4
if dstEnd <= 0 || dstEnd > len(dst) {
return 0, 0, errors.New("ROLZ codec: Invalid input data")
}
startChunk := 0
srcIdx := 5
dstIdx := 0
sizeChunk := min(len(dst), _ROLZ_CHUNK_SIZE)
litBuf := make([]byte, sizeChunk)
lenBuf := make([]byte, sizeChunk/5)
mIdxBuf := make([]byte, sizeChunk/4)
tkBuf := make([]byte, sizeChunk/4)
var err error
for i := range this.counters {
this.counters[i] = 0
}
flags := src[4]
litOrder := uint(flags & 1)
delta := 2
this.logPosChecks = uint(flags >> 4)
this.minMatch = _ROLZ_MIN_MATCH3
bsVersion := uint(3)
if this.ctx != nil {
if val, containsKey := (*this.ctx)["bsVersion"]; containsKey {
bsVersion = val.(uint)
}
}
if bsVersion >= 4 {
if flags&0x0E == 2 {
this.minMatch = _ROLZ_MIN_MATCH4
delta = 8
} else if flags&0x0E == 4 {
this.minMatch = _ROLZ_MIN_MATCH7
delta = 8
} else if flags&0x0E == 8 {
delta = 3
}
} else if bsVersion >= 3 {
if flags&6 == 2 {
this.minMatch = _ROLZ_MIN_MATCH4
} else if flags&6 == 4 {
this.minMatch = _ROLZ_MIN_MATCH7
}
}
// Main loop
for startChunk < dstEnd {
mIdx := 0
lenIdx := 0
litIdx := 0
tkIdx := 0
for i := range this.matches {
this.matches[i] = 0
}
endChunk := startChunk + sizeChunk
if endChunk > dstEnd {
endChunk = dstEnd
}
sizeChunk = endChunk - startChunk
buf := dst[startChunk:endChunk]
onlyLiterals := false
// Scope to deallocate resources early
{
// Decode literal, match length and match index buffers
is := internal.NewBufferStream(src[srcIdx:])
var ibs kanzi.InputBitStream
if ibs, err = bitstream.NewDefaultInputBitStream(is, 65536); err != nil {
goto End
}
litLen := int(ibs.ReadBits(32))
tkLen := int(ibs.ReadBits(32))
mLenLen := int(ibs.ReadBits(32))
mIdxLen := int(ibs.ReadBits(32))
if litLen < 0 || litLen > sizeChunk {
err = fmt.Errorf("ROLZ codec: Invalid length for literals: got %d, must be less than or equal to %d", litLen, sizeChunk)
goto End
}
if tkLen < 0 || tkLen > sizeChunk {
err = fmt.Errorf("ROLZ codec: Invalid length for tokens: got %d, must be less than or equal to %d", tkLen, sizeChunk)
goto End
}
if mLenLen < 0 || mLenLen > sizeChunk {
err = fmt.Errorf("ROLZ codec: Invalid length for matches: got %d, must be less than or equal to %d", mLenLen, sizeChunk)
goto End
}
if mIdxLen < 0 || mIdxLen > sizeChunk {
err = fmt.Errorf("ROLZ codec: Invalid length for match indexes: got %d, must be less than or equal to %d", mIdxLen, sizeChunk)
goto End
}
var litDec *entropy.ANSRangeDecoder
if litDec, err = entropy.NewANSRangeDecoderWithCtx(ibs, this.ctx, litOrder); err != nil {
goto End
}
if _, err = litDec.Read(litBuf[0:litLen]); err != nil {
goto End
}
litDec.Dispose()
var mDec *entropy.ANSRangeDecoder
if mDec, err = entropy.NewANSRangeDecoderWithCtx(ibs, this.ctx, 0, 32768); err != nil {
goto End
}
if _, err = mDec.Read(tkBuf[0:tkLen]); err != nil {
goto End
}
if _, err = mDec.Read(lenBuf[0:mLenLen]); err != nil {
goto End
}
if _, err = mDec.Read(mIdxBuf[0:mIdxLen]); err != nil {
goto End
}
mDec.Dispose()
onlyLiterals = tkLen == 0
srcIdx += int((ibs.Read() + 7) >> 3)
ibs.Close()
}
if onlyLiterals == true {
// Shortcut when no match
copy(buf[dstIdx:], litBuf[0:sizeChunk])
startChunk = endChunk
dstIdx += sizeChunk
continue
}
dstIdx = 0
mm := 8
if bsVersion < 3 {
mm = 2
}
if startChunk >= dstEnd {
mm = dstEnd - startChunk
}
for j := 0; j < mm; j++ {
buf[dstIdx] = litBuf[litIdx]
dstIdx++
litIdx++
}
// Next chunk
for dstIdx < sizeChunk {
// mode LLLLLMMM -> L lit length, M match length
mode := tkBuf[tkIdx]
tkIdx++
matchLen := int(mode & 0x07)
if matchLen == 7 {
ml, deltaIdx := readLengthROLZ(lenBuf[lenIdx : lenIdx+4])
lenIdx += deltaIdx
matchLen = ml + 7
}
var litLen int
if mode < 0xF8 {
litLen = int(mode >> 3)
} else {
ll, deltaIdx := readLengthROLZ(lenBuf[lenIdx : lenIdx+4])
lenIdx += deltaIdx
litLen = ll + 31
}
if litLen > 0 {
srcInc := 0
d := buf[dstIdx-delta:]
copy(d[delta:], litBuf[litIdx:litIdx+litLen])
if this.minMatch == _ROLZ_MIN_MATCH3 {
for n := 0; n < litLen; n++ {
key := getKey1(d[n:])
m := this.matches[key<<this.logPosChecks:]
c := (this.counters[key] + 1) & this.maskChecks
m[c] = uint32(dstIdx + n)
this.counters[key] = c
n += (srcInc >> 6)
srcInc++
}
} else {
for n := 0; n < litLen; n++ {
key := getKey2(d[n:])
m := this.matches[key<<this.logPosChecks:]
c := (this.counters[key] + 1) & this.maskChecks
m[c] = uint32(dstIdx + n)
this.counters[key] = c
n += (srcInc >> 6)
srcInc++
}
}
litIdx += litLen
dstIdx += litLen
if dstIdx >= sizeChunk {
// Last chunk literals not followed by match
if dstIdx == sizeChunk {
break
}
err = errors.New("ROLZ codec: Invalid input data")
goto End
}
}
// Sanity check
if dstIdx+matchLen+this.minMatch > dstEnd {
err = errors.New("ROLZ codec: Invalid input data")
goto End
}
matchIdx := int32(mIdxBuf[mIdx] & 0xFF)
mIdx++
var key uint32
if this.minMatch == _ROLZ_MIN_MATCH3 {
key = getKey1(buf[dstIdx-delta:])
} else {
key = getKey2(buf[dstIdx-delta:])
}
m := this.matches[key<<this.logPosChecks : (key+1)<<this.logPosChecks]
ref := int(m[(this.counters[key]-matchIdx)&this.maskChecks])
savedIdx := uint32(dstIdx)
dstIdx = emitCopy(buf, dstIdx, ref, matchLen+this.minMatch)
this.counters[key] = (this.counters[key] + 1) & this.maskChecks
m[this.counters[key]] = savedIdx
}
startChunk = endChunk
}
End:
if err == nil {
// Emit last literals
dstIdx += (startChunk - sizeChunk)
dst[dstIdx] = src[srcIdx]
dst[dstIdx+1] = src[srcIdx+1]
dst[dstIdx+2] = src[srcIdx+2]
dst[dstIdx+3] = src[srcIdx+3]
srcIdx += 4
dstIdx += 4
if srcIdx != len(src) {
err = errors.New("ROLZ codec: Invalid input data")
}
}
return uint(srcIdx), uint(dstIdx), err
}
// MaxEncodedLen returns the max size required for the encoding output buffer
func (this *rolzCodec1) MaxEncodedLen(srcLen int) int {
if srcLen <= 512 {
return srcLen + 64
}
return srcLen
}
func emitLengthROLZ(block []byte, litLen int) int {
idx := 0
if litLen >= 1<<7 {
if litLen >= 1<<14 {
if litLen >= 1<<21 {
block[idx] = byte(0x80 | (litLen >> 21))
idx++
}
block[idx] = byte(0x80 | (litLen >> 14))
idx++
}
block[idx] = byte(0x80 | (litLen >> 7))
idx++
}
block[idx] = byte(litLen & 0x7F)
return idx + 1
}
// return litLen, idx
func readLengthROLZ(lenBuf []byte) (int, int) {
next := lenBuf[0]
idx := 1
litLen := int(next & 0x7F)
if next >= 128 {
next = lenBuf[idx]
idx++
litLen = (litLen << 7) | int(next&0x7F)
if next >= 128 {
next = lenBuf[idx]
idx++
litLen = (litLen << 7) | int(next&0x7F)
if next >= 128 {
next = lenBuf[idx]
idx++
litLen = (litLen << 7) | int(next&0x7F)
}
}
}
return litLen, idx
}
// Use CM (ROLZEncoder/ROLZDecoder) to encode/decode literals and matches
// Code loosely based on 'balz' by Ilya Muravyov
type rolzCodec2 struct {
matches []uint32
counters []int32
logPosChecks uint
maskChecks int32
posChecks int32
minMatch int
ctx *map[string]any
}
func newROLZCodec2(logPosChecks uint) (*rolzCodec2, error) {
this := &rolzCodec2{}
if (logPosChecks < 2) || (logPosChecks > 8) {
return nil, fmt.Errorf("ROLZX codec: Invalid logPosChecks parameter: %v (must be in [2..8])", logPosChecks)
}
this.logPosChecks = logPosChecks
this.posChecks = 1 << logPosChecks
this.maskChecks = this.posChecks - 1
this.counters = make([]int32, 1<<16)
this.matches = make([]uint32, _ROLZ_HASH_SIZE<<logPosChecks)
return this, nil
}
func newROLZCodec2WithCtx(logPosChecks uint, ctx *map[string]any) (*rolzCodec2, error) {
this := &rolzCodec2{}
if (logPosChecks < 2) || (logPosChecks > 8) {
return nil, fmt.Errorf("ROLZX codec: Invalid logPosChecks parameter: %d (must be in [2..8])", logPosChecks)
}
this.logPosChecks = logPosChecks
this.posChecks = 1 << logPosChecks
this.maskChecks = this.posChecks - 1
this.counters = make([]int32, 1<<16)
this.matches = make([]uint32, _ROLZ_HASH_SIZE<<logPosChecks)
this.ctx = ctx
return this, nil
}
// findMatch returns match position index and length or -1
func (this *rolzCodec2) findMatch(buf []byte, pos int, key uint32) (int, int) {
maxMatch := min(_ROLZ_MAX_MATCH2, len(buf)-pos)
if maxMatch < this.minMatch {
return -1, -1
}