-
Notifications
You must be signed in to change notification settings - Fork 83
/
backward_references.rs
executable file
·1787 lines (1707 loc) · 67.1 KB
/
backward_references.rs
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
#![allow(dead_code)]
use super::command::{Command, ComputeDistanceCode, InitCommand, BrotliDistanceParams};
use super::hash_to_binary_tree::{H10, H10Buckets, H10DefaultParams, ZopfliNode};
use super::dictionary_hash::kStaticDictionaryHash;
use super::static_dict::{BROTLI_UNALIGNED_LOAD32, BROTLI_UNALIGNED_LOAD64, FindMatchLengthWithLimit};
use super::static_dict::BrotliDictionary;
use super::super::alloc;
use super::super::alloc::{SliceWrapper, SliceWrapperMut};
use super::util::{Log2FloorNonZero, brotli_max_size_t, floatX};
use core;
static kBrotliMinWindowBits: i32 = 10i32;
static kBrotliMaxWindowBits: i32 = 24i32;
pub static kInvalidMatch: u32 = 0xfffffffu32;
static kCutoffTransformsCount: u32 = 10u32;
static kCutoffTransforms: u64 = 0x71b520au64 << 32i32 | 0xda2d3200u32 as (u64);
pub static kHashMul32: u32 = 0x1e35a7bdu32;
pub static kHashMul64: u64 = 0x1e35a7bdu64 << 32i32 | 0x1e35a7bdu64;
pub static kHashMul64Long: u64 = 0x1fe35a7bu32 as (u64) << 32i32 | 0xd3579bd3u32 as (u64);
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[repr(C)]
pub enum BrotliEncoderMode {
BROTLI_MODE_GENERIC = 0,
BROTLI_MODE_TEXT = 1,
BROTLI_MODE_FONT = 2,
BROTLI_FORCE_LSB_PRIOR = 3,
BROTLI_FORCE_MSB_PRIOR = 4,
BROTLI_FORCE_UTF8_PRIOR = 5,
BROTLI_FORCE_SIGNED_PRIOR = 6,
}
#[derive(Clone,Copy, Debug)]
pub struct BrotliHasherParams {
// type of hasher to use (default: type 6, but others have tradeoffs of speed/memory)
pub type_: i32,
// number of the number of buckets to have in the hash table (defaults to quality - 1)
pub bucket_bits: i32,
// number of potential matches to hold per bucket (hash collisions)
pub block_bits: i32,
// number of bytes of a potential match to hash
pub hash_len: i32,
// number of previous distance matches to check for future matches (defaults to 16)
pub num_last_distances_to_check: i32,
// how much to weigh distance vs an extra byte of copy match when comparing possible copy srcs
pub literal_byte_score: i32,
}
#[derive(Clone, Debug)]
pub struct BrotliEncoderParams {
pub dist: BrotliDistanceParams,
// if this brotli file is generic, font or specifically text
pub mode: BrotliEncoderMode,
// quality param between 0 and 11 (11 is smallest but takes longest to encode)
pub quality: i32,
pub q9_5: bool,
// log of how big the ring buffer should be for copying prior data
pub lgwin: i32,
// log of how often metablocks should be serialized
pub lgblock: i32,
// how big the source file is (or 0 if no hint is provided)
pub size_hint: usize,
// avoid serializing out priors for literal sections in the favor of decode speed
pub disable_literal_context_modeling: i32,
pub hasher: BrotliHasherParams,
// produce an IR of the compression file
pub log_meta_block: bool,
// attempt to detect how many bytes before the current byte generates the best prediction of it
pub stride_detection_quality: u8, // 0 = off (stride 1 always) 1 = on per 16th of a file 2 = on per block type switch
// if nonzero, will search for high entropy strings and log them differently to the IR
pub high_entropy_detection_quality: u8, // search for high entropy literal strings and annotate them differently
// if nonzero it will search for the temporal locality and effectiveness of the priors
// for literals. The best adaptation and forgetfulness will be logged per metablock to the IR
pub cdf_adaptation_detection: u8,
// whether to search for whether the previous byte or the context_map are better predictors on a per-context-map basis
pub prior_bitmask_detection: u8,
// for prior bitmask detection: stride_low, stride_speed, cm_low, cm_speed
pub literal_adaptation:[(u16, u16); 4],
pub large_window: bool,
// avoid search for the best ndirect vs npostfix parameters for distance
pub avoid_distance_prefix_search: bool,
}
impl Default for BrotliEncoderParams {
fn default() -> BrotliEncoderParams {
super::encode::BrotliEncoderInitParams()
}
}
#[derive(Clone,Copy,Default)]
pub struct H9Opts{
pub literal_byte_score: u32,
}
pub enum HowPrepared {
ALREADY_PREPARED,
NEWLY_PREPARED,
}
pub struct Struct1 {
pub params: BrotliHasherParams,
pub is_prepared_: i32,
pub dict_num_lookups: usize,
pub dict_num_matches: usize,
}
fn LiteralSpreeLengthForSparseSearch(params: &BrotliEncoderParams) -> usize {
(if (*params).quality < 9 {
64i32
} else {
512i32
}) as (usize)
}
fn brotli_min_size_t(a: usize, b: usize) -> usize {
if a < b { a } else { b }
}
pub struct HasherSearchResult {
pub len: usize,
pub len_x_code: usize,
pub distance: usize,
pub score: usize,
}
pub trait AnyHasher {
fn Opts(&self) -> H9Opts;
fn GetHasherCommon(&mut self) -> &mut Struct1;
fn HashBytes(&self, data: &[u8]) -> usize;
fn HashTypeLength(&self) -> usize;
fn StoreLookahead(&self) -> usize;
fn PrepareDistanceCache(&self, distance_cache: &mut [i32]);
fn FindLongestMatch(&mut self,
dictionary: &BrotliDictionary,
dictionary_hash: &[u16],
data: &[u8],
ring_buffer_mask: usize,
distance_cache: &[i32],
cur_ix: usize,
max_length: usize,
max_backward: usize,
gap: usize,
max_distance: usize,
out: &mut HasherSearchResult)
-> bool;
fn Store(&mut self, data: &[u8], mask: usize, ix: usize);
fn StoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize);
fn Prepare(&mut self, one_shot: bool, input_size: usize, data: &[u8]) -> HowPrepared;
fn StitchToPreviousBlock(&mut self,
num_bytes: usize,
position: usize,
ringbuffer: &[u8],
ringbuffer_mask: usize);
}
pub fn StitchToPreviousBlockInternal<T: AnyHasher>(handle: &mut T,
num_bytes: usize,
position: usize,
ringbuffer: &[u8],
ringbuffer_mask: usize) {
if num_bytes >= handle.HashTypeLength().wrapping_sub(1) && (position >= 3) {
handle.Store(ringbuffer, ringbuffer_mask, position.wrapping_sub(3));
handle.Store(ringbuffer, ringbuffer_mask, position.wrapping_sub(2));
handle.Store(ringbuffer, ringbuffer_mask, position.wrapping_sub(1));
}
}
pub fn StoreLookaheadThenStore<T: AnyHasher>(hasher: &mut T, size: usize, dict: &[u8]) {
let overlap = hasher.StoreLookahead().wrapping_sub(1usize);
let mut i: usize = 0;
while i.wrapping_add(overlap) < size {
hasher.Store(dict, !(0usize), i);
i = i.wrapping_add(1 as (usize));
}
}
pub trait BasicHashComputer {
fn HashBytes(&self, data: &[u8]) -> u32;
fn BUCKET_BITS(&self) -> i32;
fn USE_DICTIONARY(&self) -> i32;
fn BUCKET_SWEEP(&self) -> i32;
}
pub struct BasicHasher<Buckets: SliceWrapperMut<u32> + SliceWrapper<u32> + BasicHashComputer> {
pub GetHasherCommon: Struct1,
pub buckets_: Buckets,
pub h9_opts: H9Opts,
}
pub struct H2Sub<AllocU32: alloc::Allocator<u32>> {
pub buckets_: AllocU32::AllocatedMemory, // 65537
}
impl<T: SliceWrapperMut<u32> + SliceWrapper<u32> + BasicHashComputer> AnyHasher for BasicHasher<T> {
#[inline(always)]
fn Opts(&self) -> H9Opts {
self.h9_opts
}
#[allow(unused_variables)]
fn PrepareDistanceCache(&self, distance_cache: &mut [i32]) {}
#[inline(always)]
fn HashTypeLength(&self) -> usize {
8
}
#[inline(always)]
fn StoreLookahead(&self) -> usize {
8
}
fn StitchToPreviousBlock(&mut self,
num_bytes: usize,
position: usize,
ringbuffer: &[u8],
ringbuffer_mask: usize) {
StitchToPreviousBlockInternal(self, num_bytes, position, ringbuffer, ringbuffer_mask);
}
#[inline(always)]
fn GetHasherCommon(&mut self) -> &mut Struct1 {
return &mut self.GetHasherCommon;
}
#[inline(always)]
fn HashBytes(&self, data: &[u8]) -> usize {
self.buckets_.HashBytes(data) as usize
}
fn Store(&mut self, data: &[u8], mask: usize, ix: usize) {
let (_, data_window) = data.split_at((ix & mask) as (usize));
let key: u32 = self.HashBytes(data_window) as u32;
let off: u32 = (ix >> 3i32).wrapping_rem(self.buckets_.BUCKET_SWEEP() as usize) as (u32);
self.buckets_.slice_mut()[key.wrapping_add(off) as (usize)] = ix as (u32);
}
fn StoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) {
let mut i: usize;
i = ix_start;
while i < ix_end {
{
self.Store(data, mask, i);
}
i = i.wrapping_add(1 as (usize));
}
}
fn Prepare(&mut self, one_shot: bool, input_size: usize, data: &[u8]) -> HowPrepared {
if self.GetHasherCommon.is_prepared_ != 0 {
return HowPrepared::ALREADY_PREPARED;
}
let partial_prepare_threshold = (4 << self.buckets_.BUCKET_BITS()) >> 7;
if one_shot && input_size <= partial_prepare_threshold {
for i in 0..input_size {
let key = self.HashBytes(&data[i..]) as usize;
let bs = self.buckets_.BUCKET_SWEEP() as usize;
for item in self.buckets_.slice_mut()[key..(key + bs)].iter_mut() {
*item = 0;
}
}
} else {
for item in self.buckets_.slice_mut().iter_mut() {
*item = 0;
}
}
self.GetHasherCommon.is_prepared_ = 1;
HowPrepared::NEWLY_PREPARED
}
fn FindLongestMatch(&mut self,
dictionary: &BrotliDictionary,
dictionary_hash: &[u16],
data: &[u8],
ring_buffer_mask: usize,
distance_cache: &[i32],
cur_ix: usize,
max_length: usize,
max_backward: usize,
gap: usize,
max_distance: usize,
out: &mut HasherSearchResult)
-> bool {
let opts = self.Opts();
let best_len_in: usize = (*out).len;
let cur_ix_masked: usize = cur_ix & ring_buffer_mask;
let key: u32 = self.HashBytes(&data[(cur_ix_masked as (usize))..]) as u32;
let mut compare_char: i32 = data[(cur_ix_masked.wrapping_add(best_len_in) as (usize))] as (i32);
let mut best_score: usize = (*out).score;
let mut best_len: usize = best_len_in;
let cached_backward: usize = distance_cache[(0usize)] as (usize);
let mut prev_ix: usize = cur_ix.wrapping_sub(cached_backward);
let mut is_match_found: i32 = 0i32;
(*out).len_x_code = 0usize;
if prev_ix < cur_ix {
prev_ix = prev_ix & ring_buffer_mask as (u32) as (usize);
if compare_char == data[(prev_ix.wrapping_add(best_len) as (usize))] as (i32) {
let len: usize = FindMatchLengthWithLimit(&data[(prev_ix as (usize))..],
&data[(cur_ix_masked as (usize))..],
max_length);
if len >= 4usize {
best_score = BackwardReferenceScoreUsingLastDistance(len, opts);
best_len = len;
(*out).len = len;
(*out).distance = cached_backward;
(*out).score = best_score;
compare_char = data[(cur_ix_masked.wrapping_add(best_len) as (usize))] as (i32);
if self.buckets_.BUCKET_SWEEP() == 1i32 {
(*self).buckets_.slice_mut()[key as (usize)] = cur_ix as (u32);
return true;
} else {
is_match_found = 1i32;
}
}
}
}
let BUCKET_SWEEP = self.buckets_.BUCKET_SWEEP();
if BUCKET_SWEEP == 1i32 {
let backward: usize;
let len: usize;
prev_ix = (*self).buckets_.slice()[key as (usize)] as (usize);
(*self).buckets_.slice_mut()[key as (usize)] = cur_ix as (u32);
backward = cur_ix.wrapping_sub(prev_ix);
prev_ix = prev_ix & ring_buffer_mask as (u32) as (usize);
if compare_char != data[(prev_ix.wrapping_add(best_len_in) as (usize))] as (i32) {
return false;
}
if backward == 0usize || backward > max_backward {
return false;
}
len = FindMatchLengthWithLimit(&data[(prev_ix as (usize))..],
&data[(cur_ix_masked as (usize))..],
max_length);
if len >= 4usize {
(*out).len = len;
(*out).distance = backward;
(*out).score = BackwardReferenceScore(len, backward, opts);
return true;
}
} else {
let (old_, mut bucket) = (*self).buckets_.slice_mut()[key as usize..].split_at_mut(1);
let mut i: i32;
prev_ix = old_[0] as (usize);
i = 0i32;
while i < BUCKET_SWEEP {
'continue3: loop {
{
let backward: usize = cur_ix.wrapping_sub(prev_ix);
let len: usize;
prev_ix = prev_ix & ring_buffer_mask as (u32) as (usize);
if compare_char != data[(prev_ix.wrapping_add(best_len) as (usize))] as (i32) {
{
break 'continue3;
}
}
if backward == 0usize || backward > max_backward {
{
break 'continue3;
}
}
len = FindMatchLengthWithLimit(&data[(prev_ix as (usize))..],
&data[(cur_ix_masked as (usize))..],
max_length);
if len >= 4usize {
let score: usize = BackwardReferenceScore(len, backward, opts);
if best_score < score {
best_score = score;
best_len = len;
(*out).len = best_len;
(*out).distance = backward;
(*out).score = score;
compare_char = data[(cur_ix_masked.wrapping_add(best_len) as (usize))] as (i32);
is_match_found = 1i32;
}
}
}
break;
}
i = i + 1;
{
let (_old, new_bucket) = core::mem::replace(&mut bucket, &mut []).split_at_mut(1);
prev_ix = _old[0] as usize;
bucket = new_bucket;
}
}
}
if self.buckets_.USE_DICTIONARY() != 0 && (is_match_found == 0) {
is_match_found = SearchInStaticDictionary(dictionary,
dictionary_hash,
self,
&data[(cur_ix_masked as (usize))..],
max_length,
max_backward.wrapping_add(gap),
max_distance,
out,
1i32);
}
(*self).buckets_.slice_mut()[(key as (usize)).wrapping_add((cur_ix >> 3)
.wrapping_rem(BUCKET_SWEEP as usize))] = cur_ix as (u32);
is_match_found != 0
}
}
impl<AllocU32: alloc::Allocator<u32>> BasicHashComputer for H2Sub<AllocU32> {
fn HashBytes(&self, data: &[u8]) -> u32 {
let h: u64 = (BROTLI_UNALIGNED_LOAD64(data) << 64i32 - 8i32 * 5i32).wrapping_mul(kHashMul64);
(h >> 64i32 - 16i32) as (u32)
}
fn BUCKET_BITS(&self) -> i32 {
16
}
fn BUCKET_SWEEP(&self) -> i32 {
1
}
fn USE_DICTIONARY(&self) -> i32 {
1
}
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapperMut<u32> for H2Sub<AllocU32> {
fn slice_mut(&mut self) -> &mut [u32] {
return self.buckets_.slice_mut();
}
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapper<u32> for H2Sub<AllocU32> {
fn slice(&self) -> &[u32] {
return self.buckets_.slice();
}
}
pub struct H3Sub<AllocU32: alloc::Allocator<u32>> {
pub buckets_: AllocU32::AllocatedMemory, // 65538
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapperMut<u32> for H3Sub<AllocU32> {
fn slice_mut(&mut self) -> &mut [u32] {
return self.buckets_.slice_mut();
}
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapper<u32> for H3Sub<AllocU32> {
fn slice(&self) -> &[u32] {
return self.buckets_.slice();
}
}
impl<AllocU32: alloc::Allocator<u32>> BasicHashComputer for H3Sub<AllocU32> {
fn BUCKET_BITS(&self) -> i32 {
16
}
fn BUCKET_SWEEP(&self) -> i32 {
2
}
fn USE_DICTIONARY(&self) -> i32 {
0
}
fn HashBytes(&self, data: &[u8]) -> u32 {
let h: u64 = (BROTLI_UNALIGNED_LOAD64(data) << 64i32 - 8i32 * 5i32).wrapping_mul(kHashMul64);
(h >> 64i32 - 16i32) as (u32)
}
}
pub struct H4Sub<AllocU32: alloc::Allocator<u32>> {
pub buckets_: AllocU32::AllocatedMemory, // 131076
}
impl<AllocU32: alloc::Allocator<u32>> BasicHashComputer for H4Sub<AllocU32> {
fn BUCKET_BITS(&self) -> i32 {
17
}
fn BUCKET_SWEEP(&self) -> i32 {
4
}
fn USE_DICTIONARY(&self) -> i32 {
1
}
fn HashBytes(&self, data: &[u8]) -> u32 {
let h: u64 = (BROTLI_UNALIGNED_LOAD64(data) << 64i32 - 8i32 * 5i32).wrapping_mul(kHashMul64);
(h >> 64i32 - 17i32) as (u32)
}
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapperMut<u32> for H4Sub<AllocU32> {
fn slice_mut(&mut self) -> &mut [u32] {
return self.buckets_.slice_mut();
}
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapper<u32> for H4Sub<AllocU32> {
fn slice(&self) -> &[u32] {
return self.buckets_.slice();
}
}
pub struct H54Sub<AllocU32: alloc::Allocator<u32>> {
pub buckets_: AllocU32::AllocatedMemory,
}
impl<AllocU32: alloc::Allocator<u32>> BasicHashComputer for H54Sub<AllocU32> {
fn BUCKET_BITS(&self) -> i32 {
20
}
fn BUCKET_SWEEP(&self) -> i32 {
4
}
fn USE_DICTIONARY(&self) -> i32 {
0
}
fn HashBytes(&self, data: &[u8]) -> u32 {
let h: u64 = (BROTLI_UNALIGNED_LOAD64(data) << 64i32 - 8i32 * 7i32).wrapping_mul(kHashMul64);
(h >> 64i32 - 20i32) as (u32)
}
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapperMut<u32> for H54Sub<AllocU32> {
fn slice_mut(&mut self) -> &mut [u32] {
return self.buckets_.slice_mut();
}
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapper<u32> for H54Sub<AllocU32> {
fn slice(&self) -> &[u32] {
return self.buckets_.slice();
}
}
pub const H9_BUCKET_BITS :usize = 15;
pub const H9_BLOCK_BITS :usize =8;
pub const H9_NUM_LAST_DISTANCES_TO_CHECK:usize = 16;
pub const H9_BLOCK_SIZE :usize= 1 << H9_BLOCK_BITS;
const H9_BLOCK_MASK :usize= (1 << H9_BLOCK_BITS) - 1;
impl H9Opts {
pub fn new(params:&BrotliHasherParams) -> H9Opts {
H9Opts {
literal_byte_score: if params.literal_byte_score != 0 { params.literal_byte_score as u32} else {540},
}
}
}
pub struct H9<AllocU16: alloc::Allocator<u16>,
AllocU32: alloc::Allocator<u32>> {
pub num_:AllocU16::AllocatedMemory,//[u16;1 << H9_BUCKET_BITS],
pub buckets_:AllocU32::AllocatedMemory,//[u32; H9_BLOCK_SIZE << H9_BUCKET_BITS],
pub dict_search_stats_:Struct1,
pub h9_opts: H9Opts,
}
fn adv_prepare_distance_cache(distance_cache: &mut [i32], num_distances: i32) {
if num_distances > 4i32 {
let last_distance: i32 = distance_cache[(0usize)];
distance_cache[(4usize)] = last_distance - 1i32;
distance_cache[(5usize)] = last_distance + 1i32;
distance_cache[(6usize)] = last_distance - 2i32;
distance_cache[(7usize)] = last_distance + 2i32;
distance_cache[(8usize)] = last_distance - 3i32;
distance_cache[(9usize)] = last_distance + 3i32;
if num_distances > 10i32 {
let next_last_distance: i32 = distance_cache[(1usize)];
distance_cache[(10usize)] = next_last_distance - 1i32;
distance_cache[(11usize)] = next_last_distance + 1i32;
distance_cache[(12usize)] = next_last_distance - 2i32;
distance_cache[(13usize)] = next_last_distance + 2i32;
distance_cache[(14usize)] = next_last_distance - 3i32;
distance_cache[(15usize)] = next_last_distance + 3i32;
}
}
}
pub const kDistanceCacheIndex : [u8;16] = [
0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
];
pub const kDistanceCacheOffset : [i8;16]= [
0i8,
0i8,
0i8,
0i8,
-1i8,
1i8,
-2i8,
2i8,
-3i8,
3i8,
-1i8,
1i8,
-2i8,
2i8,
-3i8,
3i8];
//const BROTLI_LITERAL_BYTE_SCORE: usize = 540;
const BROTLI_DISTANCE_BIT_PENALTY: usize = 120;
// Score must be positive after applying maximal penalty.
const BROTLI_SCORE_BASE : usize = (BROTLI_DISTANCE_BIT_PENALTY * 8 * 8/* sizeof usize*/);
const kDistanceShortCodeCost : [usize;16] = [
/* Repeat last */
BROTLI_SCORE_BASE + 60,
/* 2nd, 3rd, 4th last */
BROTLI_SCORE_BASE - 95,
BROTLI_SCORE_BASE - 117,
BROTLI_SCORE_BASE - 127,
/* Last with offset */
BROTLI_SCORE_BASE - 93,
BROTLI_SCORE_BASE - 93,
BROTLI_SCORE_BASE - 96,
BROTLI_SCORE_BASE - 96,
BROTLI_SCORE_BASE - 99,
BROTLI_SCORE_BASE - 99,
/* 2nd last with offset */
BROTLI_SCORE_BASE - 105,
BROTLI_SCORE_BASE - 105,
BROTLI_SCORE_BASE - 115,
BROTLI_SCORE_BASE - 115,
BROTLI_SCORE_BASE - 125,
BROTLI_SCORE_BASE - 125
];
fn BackwardReferenceScoreH9(copy_length: usize,
backward_reference_offset: usize,
h9_opts: H9Opts) -> usize {
(BROTLI_SCORE_BASE.wrapping_add((h9_opts.literal_byte_score as usize).wrapping_mul(copy_length)).wrapping_sub(
(BROTLI_DISTANCE_BIT_PENALTY as usize).wrapping_mul(Log2FloorNonZero(backward_reference_offset as u64) as usize))) >> 2
}
fn BackwardReferenceScoreUsingLastDistanceH9(
copy_length : usize, distance_short_code : usize,
h9_opts: H9Opts) -> usize {
((h9_opts.literal_byte_score as usize).wrapping_mul(copy_length).wrapping_add(
kDistanceShortCodeCost[distance_short_code])) >> 2
}
impl<AllocU16: alloc::Allocator<u16>,
AllocU32: alloc::Allocator<u32>> AnyHasher for H9<AllocU16, AllocU32> {
#[inline(always)]
fn Opts(&self) -> H9Opts {
self.h9_opts
}
#[inline(always)]
fn GetHasherCommon(&mut self) -> &mut Struct1 {
return &mut self.dict_search_stats_;
}
#[inline(always)]
fn HashBytes(&self, data: &[u8]) -> usize {
let h: u32 = BROTLI_UNALIGNED_LOAD32(data).wrapping_mul(kHashMul32);
let thirty_two : usize = 32;
(h >> (thirty_two.wrapping_sub(H9_BUCKET_BITS))) as usize
}
#[inline(always)]
fn HashTypeLength(&self) -> usize {
4
}
#[inline(always)]
fn StoreLookahead(&self) -> usize {
4
}
fn PrepareDistanceCache(&self, distance_cache: &mut [i32]) {
let num_distances = H9_NUM_LAST_DISTANCES_TO_CHECK as i32;
adv_prepare_distance_cache(distance_cache, num_distances);
}
fn FindLongestMatch(&mut self,
dictionary: &BrotliDictionary,
dictionary_hash: &[u16],
data: &[u8],
ring_buffer_mask: usize,
distance_cache: &[i32],
cur_ix: usize,
max_length: usize,
max_backward: usize,
gap: usize,
max_distance: usize,
out: &mut HasherSearchResult)
-> bool {
let best_len_in: usize = (*out).len;
let cur_ix_masked: usize = cur_ix & ring_buffer_mask;
let mut best_score: usize = (*out).score;
let mut best_len: usize = best_len_in;
let mut is_match_found: i32 = 0i32;
(*out).len_x_code = 0usize;
for i in 0..H9_NUM_LAST_DISTANCES_TO_CHECK {
let idx = kDistanceCacheIndex[i] as usize;
let backward = (distance_cache[idx] as usize).wrapping_add(kDistanceCacheOffset[i] as usize);
let mut prev_ix = cur_ix.wrapping_sub(backward);
if prev_ix >= cur_ix {
continue;
}
if backward > max_backward {
continue;
}
prev_ix &= ring_buffer_mask;
if cur_ix_masked.wrapping_add(best_len) > ring_buffer_mask ||
prev_ix.wrapping_add(best_len) > ring_buffer_mask ||
data[cur_ix_masked.wrapping_add(best_len)] != data[prev_ix.wrapping_add(best_len)] {
continue;
}
{
let len: usize = FindMatchLengthWithLimit(&data[(prev_ix as (usize))..],
&data[(cur_ix_masked as (usize))..],
max_length);
if len >= 3 || (len == 2 && i < 2) {
let score = BackwardReferenceScoreUsingLastDistanceH9(len, i, self.h9_opts);
if best_score < score {
best_score = score;
best_len = len;
out.len = best_len;
out.distance = backward;
out.score = best_score;
is_match_found = 1i32;
}
}
}
}
if max_length >= 4 && cur_ix_masked.wrapping_add(best_len) <= ring_buffer_mask {
let key = self.HashBytes(&data.split_at(cur_ix_masked).1);
let bucket = &mut self.buckets_.slice_mut().split_at_mut(key << H9_BLOCK_BITS).1.split_at_mut(H9_BLOCK_SIZE).0;
assert!(bucket.len() > H9_BLOCK_MASK);
assert_eq!(bucket.len(), H9_BLOCK_MASK + 1);
let self_num_key = &mut self.num_.slice_mut()[key];
let down = if *self_num_key > H9_BLOCK_SIZE as u16 {
(*self_num_key as usize) - H9_BLOCK_SIZE
} else {0usize};
let mut i: usize = *self_num_key as usize;
let mut prev_best_val = data[cur_ix_masked.wrapping_add(best_len)];
while i > down {
i -= 1;
let mut prev_ix = bucket[i & H9_BLOCK_MASK] as usize;
let backward = cur_ix.wrapping_sub(prev_ix) as usize;
if (backward > max_backward) {
break;
}
prev_ix &= ring_buffer_mask;
if (prev_ix.wrapping_add(best_len) > ring_buffer_mask ||
prev_best_val != data[prev_ix.wrapping_add(best_len) as usize]) {
continue;
}
{
let len = FindMatchLengthWithLimit(&data.split_at(prev_ix).1,
&data.split_at((cur_ix_masked as usize)).1,
max_length);
if (len >= 4) {
/* Comparing for >= 3 does not change the semantics, but just saves
for a few unnecessary binary logarithms in backward reference
score, since we are not interested in such short matches. */
let score = BackwardReferenceScoreH9(len, backward, self.h9_opts);
if (best_score < score) {
best_score = score;
best_len = len;
out.len = best_len;
out.distance = backward;
out.score = best_score;
is_match_found = 1;
if cur_ix_masked.wrapping_add(best_len) > ring_buffer_mask {
break
}
prev_best_val = data[cur_ix_masked.wrapping_add(best_len) as usize];
}
}
}
}
bucket[*self_num_key as usize & H9_BLOCK_MASK] = cur_ix as u32;
*self_num_key = self_num_key.wrapping_add(1);
}
if (is_match_found == 0) {
let (_, cur_data) = data.split_at(cur_ix_masked as usize);
is_match_found = SearchInStaticDictionary(dictionary,
dictionary_hash,
self,
cur_data,
max_length,
max_backward.wrapping_add(gap),
max_distance,
out,
0i32);
}
is_match_found != 0
}
fn Store(&mut self, data: &[u8], mask: usize, ix: usize) {
let (_, data_window) = data.split_at((ix & mask) as (usize));
let key: u32 = self.HashBytes(data_window) as u32;
let self_num_key = &mut self.num_.slice_mut()[key as usize];
let minor_ix: usize = (*self_num_key as usize & H9_BLOCK_MASK);
self.buckets_.slice_mut()[minor_ix.wrapping_add((key as usize) << H9_BLOCK_BITS)] = ix as u32;
*self_num_key = self_num_key.wrapping_add(1);
}
fn StoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) {
for i in ix_start..ix_end {
self.Store(data, mask, i);
}
}
fn Prepare(&mut self, _one_shot: bool, _input_size:usize, _data:&[u8]) ->HowPrepared {
if self.GetHasherCommon().is_prepared_ != 0 {
return HowPrepared::ALREADY_PREPARED;
}
for item in self.num_.slice_mut().iter_mut() {
*item =0;
}
self.GetHasherCommon().is_prepared_ = 1;
HowPrepared::NEWLY_PREPARED
}
fn StitchToPreviousBlock(&mut self,
num_bytes: usize,
position: usize,
ringbuffer: &[u8],
ringbuffer_mask: usize) {
StitchToPreviousBlockInternal(self,
num_bytes,
position,
ringbuffer,
ringbuffer_mask)
}
}
pub trait AdvHashSpecialization {
fn get_hash_mask(&self) -> u64;
fn set_hash_mask(&mut self, params_hash_len: i32);
fn get_k_hash_mul(&self) -> u64;
fn HashTypeLength(&self) -> usize;
fn StoreLookahead(&self) -> usize;
fn load_and_mix_word(&self, data: &[u8]) -> u64;
}
pub struct AdvHasher<Specialization: AdvHashSpecialization + Sized,
AllocU16: alloc::Allocator<u16>,
AllocU32: alloc::Allocator<u32>>
{
pub GetHasherCommon: Struct1,
pub bucket_size_: u64,
pub block_size_: u64,
pub specialization: Specialization, // contains hash_mask_
pub hash_shift_: i32,
pub block_mask_: u32,
pub num: AllocU16::AllocatedMemory,
pub buckets: AllocU32::AllocatedMemory,
pub h9_opts: H9Opts,
}
pub struct H5Sub {}
impl AdvHashSpecialization for H5Sub {
fn get_hash_mask(&self) -> u64 {
//return 0xffffffffffffffffu64;
return 0xffffffffu64; // make it 32 bit
}
fn get_k_hash_mul(&self) -> u64 {
return kHashMul32 as u64;
}
fn load_and_mix_word(&self, data: &[u8]) -> u64 {
return (BROTLI_UNALIGNED_LOAD32(data) as u64 * self.get_k_hash_mul()) & self.get_hash_mask();
}
#[allow(unused_variables)]
fn set_hash_mask(&mut self, params_hash_len: i32) {}
fn HashTypeLength(&self) -> usize {
4
}
fn StoreLookahead(&self) -> usize {
4
}
}
pub struct H6Sub {
pub hash_mask: u64,
}
impl AdvHashSpecialization for H6Sub {
fn get_hash_mask(&self) -> u64 {
self.hash_mask
}
fn set_hash_mask(&mut self, params_hash_len: i32) {
self.hash_mask = !(0u32 as (u64)) >> 64i32 - 8i32 * params_hash_len;
}
fn get_k_hash_mul(&self) -> u64 {
kHashMul64Long
}
fn load_and_mix_word(&self, data: &[u8]) -> u64 {
return (BROTLI_UNALIGNED_LOAD64(data) & self.get_hash_mask())
.wrapping_mul(self.get_k_hash_mul());
}
fn HashTypeLength(&self) -> usize {
8
}
fn StoreLookahead(&self) -> usize {
8
}
}
fn BackwardReferencePenaltyUsingLastDistance(distance_short_code: usize) -> usize {
(39usize).wrapping_add((0x1ca10i32 >> (distance_short_code & 0xeusize) & 0xei32) as (usize))
}
impl<Specialization: AdvHashSpecialization, AllocU16: alloc::Allocator<u16>, AllocU32: alloc::Allocator<u32>> AnyHasher
for AdvHasher<Specialization, AllocU16, AllocU32> {
fn Opts(&self) -> H9Opts {
self.h9_opts
}
fn PrepareDistanceCache(&self, distance_cache: &mut [i32]){
let num_distances = self.GetHasherCommon.params.num_last_distances_to_check;
adv_prepare_distance_cache(distance_cache, num_distances);
}
fn StitchToPreviousBlock(&mut self,
num_bytes: usize,
position: usize,
ringbuffer: &[u8],
ringbuffer_mask: usize) {
StitchToPreviousBlockInternal(self,
num_bytes,
position,
ringbuffer,
ringbuffer_mask);
}
fn Prepare(&mut self, one_shot: bool, input_size:usize, data:&[u8]) ->HowPrepared {
if self.GetHasherCommon.is_prepared_ != 0 {
return HowPrepared::ALREADY_PREPARED;
}
let partial_prepare_threshold = self.bucket_size_ as usize >> 6;
if one_shot && input_size <= partial_prepare_threshold {
for i in 0..input_size {
let key = self.HashBytes(&data[i..]);
self.num.slice_mut()[key] = 0;
}
} else {
for item in self.num.slice_mut()[..(self.bucket_size_ as usize)].iter_mut() {
*item =0;
}
}
self.GetHasherCommon.is_prepared_ = 1;
HowPrepared::NEWLY_PREPARED
}
fn GetHasherCommon(&mut self) -> &mut Struct1 {
&mut self.GetHasherCommon
}
fn HashTypeLength(&self) -> usize {
self.specialization.HashTypeLength()
}
fn StoreLookahead(&self) -> usize {
self.specialization.StoreLookahead()
}
fn HashBytes(&self, data: &[u8]) -> usize {
let shift = self.hash_shift_;
let h: u64 = self.specialization.load_and_mix_word(data);
(h >> shift) as (u32) as usize
}
fn Store(&mut self, data: &[u8], mask: usize, ix: usize) {
let (_, data_window) = data.split_at((ix & mask) as (usize));
let key: u32 = self.HashBytes(data_window) as u32;
let minor_ix: usize = (self.num.slice()[(key as (usize))] as (u32) & (*self).block_mask_) as (usize);
let offset: usize = minor_ix.wrapping_add((key << (self.GetHasherCommon).params.block_bits) as
(usize));
self.buckets.slice_mut()[offset] = ix as (u32);
{
let _lhs = &mut self.num.slice_mut()[(key as (usize))];
*_lhs = (*_lhs as (i32) + 1) as (u16);
}
}
fn StoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) {
for i in ix_start..ix_end {
self.Store(data, mask, i);
}
}
fn FindLongestMatch(&mut self,
dictionary: &BrotliDictionary,
dictionary_hash: &[u16],
data: &[u8],
ring_buffer_mask: usize,
distance_cache: &[i32],
cur_ix: usize,
max_length: usize,
max_backward: usize,
gap: usize,
max_distance: usize,
out: &mut HasherSearchResult)
-> bool {
let opts = self.Opts();
let cur_ix_masked: usize = cur_ix & ring_buffer_mask;
let mut is_match_found: i32 = 0i32;
let mut best_score: usize = (*out).score;
let mut best_len: usize = (*out).len;
let mut i: usize;
(*out).len = 0usize;
(*out).len_x_code = 0usize;
i = 0usize;
while i < self.GetHasherCommon.params.num_last_distances_to_check as (usize) {
'continue45: loop {
{
let backward: usize = distance_cache[(i as (usize))] as (usize);
let mut prev_ix: usize = cur_ix.wrapping_sub(backward);
if prev_ix >= cur_ix {
{
break 'continue45;
}
}
if backward > max_backward {
{
break 'continue45;
}
}
prev_ix = prev_ix & ring_buffer_mask;
if cur_ix_masked.wrapping_add(best_len) > ring_buffer_mask || prev_ix.wrapping_add(best_len) > ring_buffer_mask ||
data[(cur_ix_masked.wrapping_add(best_len) as (usize))] as (i32) !=
data[(prev_ix.wrapping_add(best_len) as (usize))] as (i32) {
{
break 'continue45;
}
}
{
let (_, prev_data) = data.split_at(prev_ix as usize);
let (_, cur_data) = data.split_at(cur_ix_masked as usize);
let len: usize = FindMatchLengthWithLimit(&prev_data,
&cur_data,