-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
2259 lines (2067 loc) · 78.6 KB
/
mod.rs
File metadata and controls
2259 lines (2067 loc) · 78.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
pub mod bitstream;
mod huffman_comp;
mod matchfinder;
use self::bitstream::Bitstream;
use self::huffman_comp::make_huffman_code;
use self::matchfinder::{BtMatchFinder, HtMatchFinder, MatchFinder, MatchFinderTrait};
use crate::common::*;
use rayon::prelude::*;
use std::cmp::min;
use std::io;
use std::mem::MaybeUninit;
use std::sync::OnceLock;
const LENGTH_WRITE_TABLE: [u32; 260] = [
3, 3, 3, 3, 16777220, 33554437, 50331654, 67108871, 83886088, 100663305, 117440522, 134283275,
134283275, 151060493, 151060493, 167837711, 167837711, 184614929, 184614929, 201457683,
201457683, 201457683, 201457683, 218234903, 218234903, 218234903, 218234903, 235012123,
235012123, 235012123, 235012123, 251789343, 251789343, 251789343, 251789343, 268632099,
268632099, 268632099, 268632099, 268632099, 268632099, 268632099, 268632099, 285409323,
285409323, 285409323, 285409323, 285409323, 285409323, 285409323, 285409323, 302186547,
302186547, 302186547, 302186547, 302186547, 302186547, 302186547, 302186547, 318963771,
318963771, 318963771, 318963771, 318963771, 318963771, 318963771, 318963771, 335806531,
335806531, 335806531, 335806531, 335806531, 335806531, 335806531, 335806531, 335806531,
335806531, 335806531, 335806531, 335806531, 335806531, 335806531, 335806531, 352583763,
352583763, 352583763, 352583763, 352583763, 352583763, 352583763, 352583763, 352583763,
352583763, 352583763, 352583763, 352583763, 352583763, 352583763, 352583763, 369360995,
369360995, 369360995, 369360995, 369360995, 369360995, 369360995, 369360995, 369360995,
369360995, 369360995, 369360995, 369360995, 369360995, 369360995, 369360995, 386138227,
386138227, 386138227, 386138227, 386138227, 386138227, 386138227, 386138227, 386138227,
386138227, 386138227, 386138227, 386138227, 386138227, 386138227, 386138227, 402980995,
402980995, 402980995, 402980995, 402980995, 402980995, 402980995, 402980995, 402980995,
402980995, 402980995, 402980995, 402980995, 402980995, 402980995, 402980995, 402980995,
402980995, 402980995, 402980995, 402980995, 402980995, 402980995, 402980995, 402980995,
402980995, 402980995, 402980995, 402980995, 402980995, 402980995, 402980995, 419758243,
419758243, 419758243, 419758243, 419758243, 419758243, 419758243, 419758243, 419758243,
419758243, 419758243, 419758243, 419758243, 419758243, 419758243, 419758243, 419758243,
419758243, 419758243, 419758243, 419758243, 419758243, 419758243, 419758243, 419758243,
419758243, 419758243, 419758243, 419758243, 419758243, 419758243, 419758243, 436535491,
436535491, 436535491, 436535491, 436535491, 436535491, 436535491, 436535491, 436535491,
436535491, 436535491, 436535491, 436535491, 436535491, 436535491, 436535491, 436535491,
436535491, 436535491, 436535491, 436535491, 436535491, 436535491, 436535491, 436535491,
436535491, 436535491, 436535491, 436535491, 436535491, 436535491, 436535491, 453312739,
453312739, 453312739, 453312739, 453312739, 453312739, 453312739, 453312739, 453312739,
453312739, 453312739, 453312739, 453312739, 453312739, 453312739, 453312739, 453312739,
453312739, 453312739, 453312739, 453312739, 453312739, 453312739, 453312739, 453312739,
453312739, 453312739, 453312739, 453312739, 453312739, 453312739, 469762306, 3,
];
const LENGTH_EXTRA_BITS_TABLE: [u8; 29] = [
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
];
const OFFSET_BASE_TABLE: [u32; 30] = [
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
];
const OFFSET_EXTRA_BITS_TABLE: [u8; 30] = [
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13,
13,
];
// Precomputed table for get_offset_slot.
// For offsets <= 256, table[offset] gives the slot.
// For offsets > 256, table[256 + ((offset - 1) >> 7)] gives the slot.
// This reduces the table size from 32KB to 512 bytes, improving cache locality.
const OFFSET_SLOT_TABLE_512: [u8; 512] = {
let mut table = [0; 512];
// Fill 0..=256 (used for direct lookup)
let mut offset: usize = 1;
while offset <= 256 {
let slot = if offset <= 2 {
offset - 1
} else {
let off = (offset - 1) as u32;
let l = 31 - off.leading_zeros();
((2 * l) + ((off >> (l - 1)) & 1)) as usize
};
table[offset] = slot as u8;
offset += 1;
}
// Fill 257..511 (used for (offset - 1) >> 7)
// Index i corresponds to k = i - 256.
// k = (offset - 1) >> 7.
let mut k: u32 = 0;
while k < 256 {
// We only access this part for offset > 256, which implies k >= 2.
if k >= 2 {
// Pick a representative offset value. k << 7 works because the slot
// depends only on the MSB and the bit below it, which are preserved
// in k for k >= 2.
let off = k << 7;
let l = 31 - off.leading_zeros();
let slot = ((2 * l) + ((off >> (l - 1)) & 1)) as usize;
table[(256 + k) as usize] = slot as u8;
}
k += 1;
}
table
};
const OFF_IDX_TABLE: [u8; 32] = [
0, 0, 0, 0, 0, 0, 0, 0, // 0-7: offset < 256
1, 1, 1, 1, // 8-11: offset < 4096
2, 2, 2, // 12-14: offset < 32768
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 15-31: offset >= 32768
];
// Mapping from offset slot to observation index.
// Slots 0-15 (offsets 1-256) -> 0
// Slots 16-23 (offsets 257-4096) -> 1
// Slots 24-29 (offsets 4097-32768) -> 2
// Note: Offset 32768 (Slot 29) is effectively mapped to Type 2,
// whereas OFF_IDX_TABLE maps it to Type 3. This minor deviation is acceptable.
const SLOT_TO_OBS_IDX: [u8; 32] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0-15
1, 1, 1, 1, 1, 1, 1, 1, // 16-23
2, 2, 2, 2, 2, 2, // 24-29
0, 0, // 30-31
];
pub const MAX_LITLEN_CODEWORD_LEN: usize = 14;
pub const MAX_OFFSET_CODEWORD_LEN: usize = 15;
pub const MAX_PRE_CODEWORD_LEN: usize = 7;
fn gen_codewords_from_lens(lens: &[u8], codewords: &mut [u32], max_len: usize) {
let mut len_counts = [0u32; 16];
for &l in lens {
if l > 0 {
len_counts[l as usize] += 1;
}
}
let mut next_code = [0u32; 16];
let mut code = 0u32;
for len in 1..=max_len {
code = (code + len_counts[len - 1]) << 1;
next_code[len] = code;
}
for i in 0..lens.len() {
if lens[i] > 0 {
let c = next_code[lens[i] as usize];
next_code[lens[i] as usize] += 1;
codewords[i] = (c as u16).reverse_bits() as u32 >> (16 - lens[i]);
}
}
}
struct StaticTables {
litlen_lens: [u8; DEFLATE_NUM_LITLEN_SYMS],
offset_lens: [u8; DEFLATE_NUM_OFFSET_SYMS],
litlen_table: [u64; DEFLATE_NUM_LITLEN_SYMS],
offset_table: [u64; DEFLATE_NUM_OFFSET_SYMS],
match_len_table: [u64; DEFLATE_MAX_MATCH_LEN + 1],
}
fn compute_static_tables() -> StaticTables {
let mut litlen_lens = [0u8; DEFLATE_NUM_LITLEN_SYMS];
let mut offset_lens = [0u8; DEFLATE_NUM_OFFSET_SYMS];
let mut litlen_codewords = [0u32; DEFLATE_NUM_LITLEN_SYMS];
let mut offset_codewords = [0u32; DEFLATE_NUM_OFFSET_SYMS];
let mut litlen_table = [0u64; DEFLATE_NUM_LITLEN_SYMS];
let mut offset_table = [0u64; DEFLATE_NUM_OFFSET_SYMS];
let mut match_len_table = [0u64; DEFLATE_MAX_MATCH_LEN + 1];
let mut i = 0;
while i < 144 {
litlen_lens[i] = 8;
i += 1;
}
while i < 256 {
litlen_lens[i] = 9;
i += 1;
}
while i < 280 {
litlen_lens[i] = 7;
i += 1;
}
while i < 288 {
litlen_lens[i] = 8;
i += 1;
}
for i in 0..32 {
offset_lens[i] = 5;
}
gen_codewords_from_lens(&litlen_lens, &mut litlen_codewords, 9);
gen_codewords_from_lens(&offset_lens, &mut offset_codewords, 5);
for i in 0..DEFLATE_NUM_LITLEN_SYMS {
litlen_table[i] = (litlen_codewords[i] as u64) | ((litlen_lens[i] as u64) << 32);
}
for i in 0..DEFLATE_NUM_OFFSET_SYMS {
let mut entry = (offset_codewords[i] as u64) | ((offset_lens[i] as u64) << 32);
if i < 30 {
// SAFETY: Arrays are static consts of size 30.
entry |= (unsafe { *OFFSET_EXTRA_BITS_TABLE.get_unchecked(i) } as u64) << 40;
entry |= (unsafe { *OFFSET_BASE_TABLE.get_unchecked(i) } as u64) << 48;
}
offset_table[i] = entry;
}
for len in 3..=DEFLATE_MAX_MATCH_LEN {
let len_info = unsafe { *LENGTH_WRITE_TABLE.get_unchecked(len) };
let slot = (len_info >> 24) as usize;
let extra = (len_info >> 16) as u8;
let base = len_info as u16;
let huff_entry = unsafe { *litlen_table.get_unchecked(257 + slot) };
let code = huff_entry as u16;
let huff_len = (huff_entry >> 32) as u8;
match_len_table[len] = (code as u64)
| ((huff_len as u64) << 16)
| ((extra as u64) << 24)
| ((base as u64) << 32);
}
StaticTables {
litlen_lens,
offset_lens,
litlen_table,
offset_table,
match_len_table,
}
}
#[derive(Debug, PartialEq, Eq)]
#[must_use = "Compression result must be checked to ensure data integrity"]
pub enum CompressResult {
Success,
InsufficientSpace,
}
#[derive(Clone, Copy)]
struct Sequence {
litrunlen: u32,
length: u16,
offset: u16,
}
impl Sequence {
#[inline(always)]
fn new(litrunlen: u32, len: u16, offset: u16, off_slot: u8) -> Self {
Self {
litrunlen,
length: len | ((off_slot as u16) << 9),
offset,
}
}
#[inline(always)]
fn len(&self) -> u16 {
self.length & 0x1FF
}
#[inline(always)]
fn off_slot(&self) -> usize {
(self.length >> 9) as usize
}
}
#[derive(Clone, Copy)]
struct DPNode {
cost: u32,
length: u16,
offset: u16,
}
const NUM_LITERAL_OBSERVATION_TYPES: usize = 8;
const NUM_MATCH_OBSERVATION_TYPES: usize = 2;
const NUM_OFFSET_OBSERVATION_TYPES: usize = 4;
const NUM_OBSERVATION_TYPES: usize =
NUM_LITERAL_OBSERVATION_TYPES + NUM_MATCH_OBSERVATION_TYPES + NUM_OFFSET_OBSERVATION_TYPES;
const NUM_OBSERVATIONS_PER_BLOCK_CHECK: u32 = 2048;
struct BlockSplitStats {
new_observations: [u32; NUM_OBSERVATION_TYPES],
observations: [u32; NUM_OBSERVATION_TYPES],
num_new_observations: u32,
num_observations: u32,
}
impl BlockSplitStats {
fn new() -> Self {
Self {
new_observations: [0; NUM_OBSERVATION_TYPES],
observations: [0; NUM_OBSERVATION_TYPES],
num_new_observations: 0,
num_observations: 0,
}
}
fn reset(&mut self) {
self.new_observations.fill(0);
self.observations.fill(0);
self.num_new_observations = 0;
self.num_observations = 0;
}
#[inline(always)]
fn observe_literal(&mut self, lit: u8) {
unsafe {
*self.new_observations.get_unchecked_mut((lit >> 5) as usize) += 1;
}
self.num_new_observations += 1;
}
#[inline(always)]
fn observe_match(&mut self, length: usize, offset: usize) {
let len_idx = NUM_LITERAL_OBSERVATION_TYPES + if length >= 8 { 1 } else { 0 };
unsafe {
*self.new_observations.get_unchecked_mut(len_idx) += 1;
}
// Optimization: Use table lookup to avoid branch mispredictions.
// offset is always >= 1, so bsr32 is safe.
debug_assert!(offset >= 1);
let off_idx_base = unsafe { *OFF_IDX_TABLE.get_unchecked(bsr32(offset as u32) as usize) };
let off_idx =
NUM_LITERAL_OBSERVATION_TYPES + NUM_MATCH_OBSERVATION_TYPES + off_idx_base as usize;
unsafe {
*self.new_observations.get_unchecked_mut(off_idx) += 1;
}
self.num_new_observations += 2;
}
#[inline(always)]
fn observe_match_with_slot(&mut self, length: usize, off_slot: usize) {
let len_idx = NUM_LITERAL_OBSERVATION_TYPES + if length >= 8 { 1 } else { 0 };
unsafe {
*self.new_observations.get_unchecked_mut(len_idx) += 1;
}
let off_idx_base = unsafe { *SLOT_TO_OBS_IDX.get_unchecked(off_slot) };
let off_idx =
NUM_LITERAL_OBSERVATION_TYPES + NUM_MATCH_OBSERVATION_TYPES + off_idx_base as usize;
unsafe {
*self.new_observations.get_unchecked_mut(off_idx) += 1;
}
self.num_new_observations += 2;
}
fn merge_new_observations(&mut self) {
for i in 0..NUM_OBSERVATION_TYPES {
unsafe {
*self.observations.get_unchecked_mut(i) += *self.new_observations.get_unchecked(i);
}
}
self.num_observations += self.num_new_observations;
self.new_observations.fill(0);
self.num_new_observations = 0;
}
fn do_end_block_check(&self, block_length: usize) -> bool {
if self.num_observations == 0 {
return false;
}
let mut old_bits = 0;
let mut new_bits = 0;
let log2_num_obs = bsr32(self.num_observations);
let log2_num_new_obs = bsr32(self.num_new_observations);
for i in 0..NUM_OBSERVATION_TYPES {
unsafe {
let new_obs = *self.new_observations.get_unchecked(i);
if new_obs > 0 {
let log2_obs = bsr32(*self.observations.get_unchecked(i) + 1);
let cost_old = log2_num_obs.saturating_sub(log2_obs);
old_bits += new_obs * cost_old;
let log2_new_obs = bsr32(new_obs + 1);
let cost_new = log2_num_new_obs.saturating_sub(log2_new_obs);
new_bits += new_obs * cost_new;
}
}
}
(old_bits as i32 - new_bits as i32) > (block_length as i32 / 16)
}
#[inline(always)]
fn should_end_block(&mut self, block_length: usize, input_remaining: usize) -> bool {
// Optimization: Fast path for the common case where we are far from any block limit.
// This avoids checking `input_remaining` (which requires a subtraction) and other
// conditions in the hottest path (executed for every literal/match).
if self.num_new_observations < NUM_OBSERVATIONS_PER_BLOCK_CHECK
&& block_length < SOFT_MAX_BLOCK_LENGTH
{
return false;
}
if input_remaining <= MIN_BLOCK_LENGTH {
return false;
}
if block_length >= SOFT_MAX_BLOCK_LENGTH {
return true;
}
// If we reach here, we know `block_length < SOFT_MAX_BLOCK_LENGTH`.
// Combined with the failure of the fast path check above, this implies that
// `self.num_new_observations >= NUM_OBSERVATIONS_PER_BLOCK_CHECK`.
// So we can proceed directly to the block split check without re-verifying the count.
if block_length >= MIN_BLOCK_LENGTH {
if self.do_end_block_check(block_length) {
return true;
}
self.merge_new_observations();
}
false
}
}
enum MatchFinderEnum {
Chain(MatchFinder),
Table(HtMatchFinder),
Bt(BtMatchFinder),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum FlushMode {
None,
Sync,
Finish,
}
pub struct Compressor {
pub compression_level: usize,
pub max_search_depth: usize,
pub nice_match_length: usize,
pub litlen_freqs: [u32; DEFLATE_NUM_LITLEN_SYMS],
pub offset_freqs: [u32; DEFLATE_NUM_OFFSET_SYMS],
pub litlen_codewords: [u32; DEFLATE_NUM_LITLEN_SYMS],
pub litlen_lens: [u8; DEFLATE_NUM_LITLEN_SYMS],
pub offset_codewords: [u32; DEFLATE_NUM_OFFSET_SYMS],
pub offset_lens: [u8; DEFLATE_NUM_OFFSET_SYMS],
pub litlen_table: [u64; DEFLATE_NUM_LITLEN_SYMS],
pub offset_table: [u64; DEFLATE_NUM_OFFSET_SYMS],
pub match_len_table: [u64; DEFLATE_MAX_MATCH_LEN + 1],
pub literal_costs: [u32; 256],
pub length_costs: [u32; DEFLATE_MAX_MATCH_LEN + 1],
pub offset_slot_costs: [u32; 32],
mf: Option<MatchFinderEnum>,
sequences: Vec<Sequence>,
dp_costs: Vec<u32>,
dp_path: Vec<u32>,
split_stats: BlockSplitStats,
matches: Vec<(u16, u16)>,
}
impl Compressor {
pub fn new(level: usize) -> Self {
let mut c = Self {
compression_level: level,
max_search_depth: 0,
nice_match_length: 0,
litlen_freqs: [0; DEFLATE_NUM_LITLEN_SYMS],
offset_freqs: [0; DEFLATE_NUM_OFFSET_SYMS],
litlen_codewords: [0; DEFLATE_NUM_LITLEN_SYMS],
litlen_lens: [0; DEFLATE_NUM_LITLEN_SYMS],
offset_codewords: [0; DEFLATE_NUM_OFFSET_SYMS],
offset_lens: [0; DEFLATE_NUM_OFFSET_SYMS],
litlen_table: [0; DEFLATE_NUM_LITLEN_SYMS],
offset_table: [0; DEFLATE_NUM_OFFSET_SYMS],
match_len_table: [0; DEFLATE_MAX_MATCH_LEN + 1],
literal_costs: [0; 256],
length_costs: [0; DEFLATE_MAX_MATCH_LEN + 1],
offset_slot_costs: [0; 32],
mf: Some(if level == 1 {
MatchFinderEnum::Table(HtMatchFinder::new())
} else if level >= 10 {
MatchFinderEnum::Bt(BtMatchFinder::new())
} else {
MatchFinderEnum::Chain(MatchFinder::new())
}),
sequences: if level == 0 {
Vec::new()
} else {
Vec::with_capacity(50000)
},
dp_costs: if level >= 10 {
Vec::with_capacity(300000)
} else {
Vec::new()
},
dp_path: if level >= 10 {
Vec::with_capacity(300000)
} else {
Vec::new()
},
split_stats: BlockSplitStats::new(),
matches: if level >= 10 {
Vec::with_capacity(32)
} else {
Vec::new()
},
};
c.init_params();
c
}
fn update_huffman_tables(&mut self) {
for i in 0..DEFLATE_NUM_LITLEN_SYMS {
self.litlen_table[i] =
(self.litlen_codewords[i] as u64) | ((self.litlen_lens[i] as u64) << 32);
}
for i in 0..DEFLATE_NUM_OFFSET_SYMS {
let mut entry =
(self.offset_codewords[i] as u64) | ((self.offset_lens[i] as u64) << 32);
if i < 30 {
// SAFETY: Arrays are static consts of size 30.
entry |= (unsafe { *OFFSET_EXTRA_BITS_TABLE.get_unchecked(i) } as u64) << 40;
entry |= (unsafe { *OFFSET_BASE_TABLE.get_unchecked(i) } as u64) << 48;
}
self.offset_table[i] = entry;
}
for len in 3..=DEFLATE_MAX_MATCH_LEN {
let len_info = unsafe { *LENGTH_WRITE_TABLE.get_unchecked(len) };
let slot = (len_info >> 24) as usize;
let extra = (len_info >> 16) as u8;
let base = len_info as u16;
let huff_entry = unsafe { *self.litlen_table.get_unchecked(257 + slot) };
let code = huff_entry as u16;
let huff_len = (huff_entry >> 32) as u8;
self.match_len_table[len] = (code as u64)
| ((huff_len as u64) << 16)
| ((extra as u64) << 24)
| ((base as u64) << 32);
}
}
fn init_params(&mut self) {
match self.compression_level {
0 => {
self.max_search_depth = 0;
self.nice_match_length = 0;
}
1 => {
self.max_search_depth = 2;
self.nice_match_length = 32;
}
2 => {
self.max_search_depth = 6;
self.nice_match_length = 10;
}
3 => {
self.max_search_depth = 12;
self.nice_match_length = 14;
}
4 => {
self.max_search_depth = 16;
self.nice_match_length = 30;
}
5 => {
self.max_search_depth = 16;
self.nice_match_length = 30;
}
6 => {
self.max_search_depth = 35;
self.nice_match_length = 65;
}
7 => {
self.max_search_depth = 100;
self.nice_match_length = 130;
}
8 => {
self.max_search_depth = 300;
self.nice_match_length = 258;
}
9 => {
self.max_search_depth = 600;
self.nice_match_length = 258;
}
10 => {
self.max_search_depth = 35;
self.nice_match_length = 75;
}
11 => {
self.max_search_depth = 100;
self.nice_match_length = 150;
}
12 => {
self.max_search_depth = 300;
self.nice_match_length = 258;
}
_ => {
self.max_search_depth = 300;
self.nice_match_length = 258;
}
}
}
fn compress_loop<T: MatchFinderTrait>(
&mut self,
mf: &mut T,
input: &[u8],
bs: &mut Bitstream,
flush_mode: FlushMode,
) -> (CompressResult, usize, u32) {
let mut in_idx = 0;
mf.prepare(input.len());
while in_idx < input.len() {
let processed = if self.compression_level >= 10 {
self.compress_near_optimal_block(
mf,
input,
in_idx,
bs,
flush_mode == FlushMode::Finish,
)
} else {
let lazy_depth = if self.compression_level >= 8 {
2
} else if self.compression_level >= 5 {
1
} else {
0
};
self.compress_greedy_block(
mf,
input,
in_idx,
bs,
lazy_depth,
flush_mode == FlushMode::Finish,
)
};
if processed == 0 {
mf.advance(input.len());
return (CompressResult::InsufficientSpace, 0, 0);
}
in_idx += processed;
}
if in_idx == 0 && flush_mode == FlushMode::Finish {
let start_out = bs.out_idx;
if self.compression_level >= 10 {
self.compress_near_optimal_block(mf, input, 0, bs, true);
} else {
self.compress_greedy_block(mf, input, 0, bs, 0, true);
}
if bs.out_idx == start_out {
mf.advance(input.len());
return (CompressResult::InsufficientSpace, 0, 0);
}
}
if flush_mode == FlushMode::Sync {
if !bs.write_bits(0, 3) {
mf.advance(input.len());
return (CompressResult::InsufficientSpace, 0, 0);
}
let (res, _) = bs.flush();
if !res {
mf.advance(input.len());
return (CompressResult::InsufficientSpace, 0, 0);
}
if bs.out_idx + 4 > bs.output.len() {
mf.advance(input.len());
return (CompressResult::InsufficientSpace, 0, 0);
}
bs.output[bs.out_idx].write(0);
bs.output[bs.out_idx + 1].write(0);
bs.output[bs.out_idx + 2].write(0xFF);
bs.output[bs.out_idx + 3].write(0xFF);
bs.out_idx += 4;
}
let (res, valid_bits) = bs.flush();
if !res {
mf.advance(input.len());
return (CompressResult::InsufficientSpace, 0, 0);
}
mf.advance(input.len());
(CompressResult::Success, bs.out_idx, valid_bits)
}
pub fn compress(
&mut self,
input: &[u8],
output: &mut [MaybeUninit<u8>],
flush_mode: FlushMode,
) -> (CompressResult, usize, u32) {
if input.len() > 256 * 1024 {
let chunk_size = 256 * 1024;
let chunks: Vec<&[u8]> = input.chunks(chunk_size).collect();
let compressed_chunks_res: Vec<io::Result<Vec<u8>>> = chunks
.par_iter()
.enumerate()
.map_init(
|| {
(
Compressor::new(self.compression_level),
Vec::with_capacity(chunk_size + chunk_size / 2),
)
},
|(compressor, buf), (i, chunk)| {
let is_last = i == chunks.len() - 1;
let mode = if is_last { flush_mode } else { FlushMode::Sync };
let bound = Self::deflate_compress_bound(chunk.len());
if buf.capacity() < bound {
buf.reserve(bound - buf.len());
}
unsafe {
buf.set_len(bound);
}
let buf_uninit = unsafe {
std::slice::from_raw_parts_mut(
buf.as_mut_ptr() as *mut MaybeUninit<u8>,
buf.len(),
)
};
let (res, size, _) = compressor.compress(chunk, buf_uninit, mode);
if res == CompressResult::Success {
unsafe {
buf.set_len(size);
}
if size < buf.capacity() / 2 {
Ok(buf.to_vec())
} else {
Ok(std::mem::replace(
buf,
Vec::with_capacity(chunk_size + chunk_size / 2),
))
}
} else {
Err(io::Error::new(io::ErrorKind::Other, "Compression failed"))
}
},
)
.collect();
let mut out_idx = 0;
for res in compressed_chunks_res {
match res {
Ok(data) => {
if out_idx + data.len() > output.len() {
return (CompressResult::InsufficientSpace, 0, 0);
}
unsafe {
std::ptr::copy_nonoverlapping(
data.as_ptr(),
output.as_mut_ptr().add(out_idx) as *mut u8,
data.len(),
);
}
out_idx += data.len();
}
Err(_) => return (CompressResult::InsufficientSpace, 0, 0),
}
}
return (CompressResult::Success, out_idx, 0);
}
if self.compression_level == 0 {
return self.compress_uncompressed(input, output, flush_mode);
}
let mut bs = Bitstream::new(output);
let mut mf_enum = self.mf.take().unwrap();
let res = match &mut mf_enum {
MatchFinderEnum::Chain(mf) => self.compress_loop(mf, input, &mut bs, flush_mode),
MatchFinderEnum::Table(mf) => self.compress_loop(mf, input, &mut bs, flush_mode),
MatchFinderEnum::Bt(mf) => self.compress_loop(mf, input, &mut bs, flush_mode),
};
self.mf = Some(mf_enum);
res
}
fn compress_to_size_loop<T: MatchFinderTrait>(
&mut self,
mf: &mut T,
input: &[u8],
_final_block: bool,
) -> usize {
let mut in_idx = 0;
let mut total_bits = 0;
mf.prepare(input.len());
while in_idx < input.len() {
let (processed, bits) = if self.compression_level < 2 {
self.calculate_block_size_fast(mf, input, in_idx)
} else if self.compression_level >= 10 {
self.calculate_block_size_near_optimal(mf, input, in_idx)
} else {
self.calculate_block_size_greedy_lazy(mf, input, in_idx)
};
in_idx += processed;
total_bits += bits;
}
mf.advance(input.len());
(total_bits + 7) / 8
}
fn calculate_block_size_fast<T: MatchFinderTrait>(
&mut self,
mf: &mut T,
input: &[u8],
in_idx: usize,
) -> (usize, usize) {
let processed = self.accumulate_greedy_frequencies(mf, input, in_idx, 0);
self.load_static_huffman_codes();
let bits = 3 + self.calculate_block_data_size();
(processed, bits)
}
fn calculate_block_size_greedy_lazy<T: MatchFinderTrait>(
&mut self,
mf: &mut T,
input: &[u8],
in_idx: usize,
) -> (usize, usize) {
let lazy_depth = if self.compression_level >= 8 {
2
} else if self.compression_level >= 5 {
1
} else {
0
};
let processed = self.decide_greedy_sequences(mf, input, in_idx, lazy_depth);
make_huffman_code(
DEFLATE_NUM_LITLEN_SYMS,
MAX_LITLEN_CODEWORD_LEN,
&self.litlen_freqs,
&mut self.litlen_lens,
&mut self.litlen_codewords,
);
make_huffman_code(
DEFLATE_NUM_OFFSET_SYMS,
MAX_OFFSET_CODEWORD_LEN,
&self.offset_freqs,
&mut self.offset_lens,
&mut self.offset_codewords,
);
let bits = 3 + self.calculate_dynamic_header_size() + self.calculate_block_data_size();
(processed, bits)
}
fn calculate_block_size_near_optimal<T: MatchFinderTrait>(
&mut self,
mf: &mut T,
input: &[u8],
in_idx: usize,
) -> (usize, usize) {
self.split_stats.reset();
let mut p = in_idx;
while p < input.len() {
let block_len = p - in_idx;
if self
.split_stats
.should_end_block(block_len, input.len() - p)
{
break;
}
let (len, offset) =
mf.find_match(input, p, self.max_search_depth, self.nice_match_length);
if len >= 3 {
self.split_stats.observe_match(len, offset);
p += len;
for i in 1..len {
mf.skip_match(
input,
p - len + i,
self.max_search_depth,
self.nice_match_length,
);
}
} else {
self.split_stats.observe_literal(input[p]);
p += 1;
}
}
let processed = p - in_idx;
let block_input = &input[in_idx..in_idx + processed];
self.sequences.clear();
let mut cur_in_idx = 0;
self.litlen_freqs.fill(0);
self.offset_freqs.fill(0);
mf.reset();
while cur_in_idx < block_input.len() {
let (len, offset) = mf.find_match(
block_input,
cur_in_idx,
self.max_search_depth,
self.nice_match_length,
);
if len >= 3 {
self.sequences.push(Sequence {
litrunlen: 0,
length: len as u16,
offset: offset as u16,
});
self.litlen_freqs[257 + self.get_length_slot(len)] += 1;
self.offset_freqs[self.get_offset_slot(offset)] += 1;
mf.skip_positions(
block_input,
cur_in_idx + 1,
len - 1,
self.max_search_depth,
self.nice_match_length,
);
cur_in_idx += len;
} else {
self.litlen_freqs[block_input[cur_in_idx] as usize] += 1;
cur_in_idx += 1;
}
}
self.litlen_freqs[256] += 1;
make_huffman_code(
DEFLATE_NUM_LITLEN_SYMS,
MAX_LITLEN_CODEWORD_LEN,
&self.litlen_freqs,
&mut self.litlen_lens,
&mut self.litlen_codewords,
);
make_huffman_code(
DEFLATE_NUM_OFFSET_SYMS,
MAX_OFFSET_CODEWORD_LEN,
&self.offset_freqs,
&mut self.offset_lens,
&mut self.offset_codewords,
);
self.update_costs();
self.dp_costs.clear();
self.dp_costs.resize(processed + 1, 0x3FFFFFFF);
self.dp_costs[0] = 0;
self.dp_path.clear();
if self.dp_path.capacity() < processed + 1 {
self.dp_path.reserve(processed + 1 - self.dp_path.len());
}
unsafe {
self.dp_path.set_len(processed + 1);
}
mf.reset();
let mut pos = 0;
while pos < processed {
let cur_cost = self.dp_costs[pos];
if cur_cost >= 0x3FFFFFFF {
pos += 1;
continue;
}
let lit_cost = self.litlen_lens[block_input[pos] as usize] as u32;
if cur_cost + lit_cost < self.dp_costs[pos + 1] {
self.dp_costs[pos + 1] = cur_cost + lit_cost;
self.dp_path[pos + 1] = (1 as u32) | (0 as u32) << 16;
}
mf.find_matches(
block_input,
pos,
self.max_search_depth,
self.nice_match_length,
&mut self.matches,
);
let mut best_len = 0;
for &(len, offset) in &self.matches {
let len = len as usize;
if pos + len > processed {
continue;
}
if len > best_len {
best_len = len;
}
let cost = self.get_match_cost(len, offset as usize);
if cur_cost + cost < self.dp_costs[pos + len] {