-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathlib.rs
2309 lines (1914 loc) · 73.3 KB
/
lib.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
#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications)]
//! brotli-rs provides Read adapter implementations the Brotli compression scheme.
//!
//! This allows a consumer to wrap a Brotli-compressed Stream into a Decompressor,
//! using the familiar methods provided by the Read trait for processing
//! the uncompressed stream.
/// bitreader wraps a Read to provide bit-oriented read access to a stream.
mod bitreader;
mod huffman;
/// ringbuffer provides a data structure RingBuffer that uses a single, fixed-size buffer as if it were connected end-to-end.
/// This structure lends itself easily to buffering data streams.
mod ringbuffer;
mod dictionary;
use ::dictionary::{ BROTLI_DICTIONARY_OFFSETS_BY_LENGTH, BROTLI_DICTIONARY_SIZE_BITS_BY_LENGTH, BROTLI_DICTIONARY };
mod lookuptable;
use ::lookuptable::{ LUT_0, LUT_1, LUT_2 };
mod transformation;
use ::transformation::transformation;
use ::bitreader::{ BitReader, BitReaderError };
use ::huffman::tree::Tree;
use ::ringbuffer::RingBuffer;
use std::collections::VecDeque;
use std::cmp;
use std::error::Error;
use std::fmt;
use std::fmt::{ Display, Formatter };
use std::io;
use std::io::Read;
// #[derive(Debug, Clone, PartialEq)]
// enum LogLevel {
// None,
// Debug,
// }
// const LOG_LEVEL: LogLevel = LogLevel::None;
// fn debug(msg: &str) {
// if LOG_LEVEL == LogLevel::Debug {
// println!("{}", msg);
// }
// }
type WBits = u8;
type CodeLengths = Vec<usize>;
type HuffmanCodes = Tree;
type IsLast = bool;
type IsLastEmpty = bool;
type MNibbles = u8;
type MSkipBytes = u8;
type MSkipLen = u32;
type MLen = u32;
type IsUncompressed = bool;
type Literal = u8;
type Literals = Vec<Literal>;
type MLenLiterals = Literals;
type InsertLiterals = Literals;
type NBltypes = u8;
type BLen = u32;
type BlockSwitch = (NBltypes, BLen);
type NPostfix = u8;
type NDirect = u8;
type ContextMode = u16;
type ContextModes = Vec<ContextMode>;
type ContextMap = Vec<u8>;
type NTrees = u8;
type NSym = u8;
type Symbol = u16;
type Symbols = Vec<Symbol>;
type TreeSelect = bool;
type InsertAndCopyLength = Symbol;
type InsertLength = u32;
type CopyLength = u32;
type InsertLengthAndCopyLength = (InsertLength, CopyLength);
type DistanceCode = u32;
type Distance = u32;
type HSkip = u8;
#[derive(Debug, Clone, PartialEq)]
enum PrefixCodeKind {
Simple,
Complex(HSkip),
}
#[derive(Debug, Clone, PartialEq)]
struct PrefixCodeSimple {
n_sym: Option<NSym>,
symbols: Option<Symbols>,
tree_select: Option<TreeSelect>,
}
#[derive(Debug, Clone, PartialEq)]
enum PrefixCode {
Simple(PrefixCodeSimple),
Complex,
}
impl PrefixCode {
fn new_simple(n_sym: Option<NSym>, symbols: Option<Symbols>, tree_select:Option<TreeSelect>) -> PrefixCode {
PrefixCode::Simple(PrefixCodeSimple {
n_sym: n_sym,
symbols: symbols,
tree_select: tree_select,
})
}
}
#[derive(Debug, Clone, PartialEq)]
struct Header {
wbits: Option<WBits>,
wbits_codes: Option<HuffmanCodes>,
window_size: Option<usize>,
bltype_codes: Option<HuffmanCodes>,
}
impl Header {
fn new() -> Header {
Header{
wbits: None,
wbits_codes: None,
bltype_codes: None,
window_size: None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
struct MetaBlock {
header: MetaBlockHeader,
count_output: usize,
context_modes_literals: Option<ContextModes>,
prefix_tree_block_types_literals: Option<HuffmanCodes>,
prefix_tree_block_counts_literals: Option<HuffmanCodes>,
prefix_tree_block_types_insert_and_copy_lengths: Option<HuffmanCodes>,
prefix_tree_block_counts_insert_and_copy_lengths: Option<HuffmanCodes>,
prefix_tree_block_types_distances: Option<HuffmanCodes>,
prefix_tree_block_counts_distances: Option<HuffmanCodes>,
prefix_trees_literals: Option<Vec<HuffmanCodes>>,
prefix_trees_insert_and_copy_lengths: Option<Vec<HuffmanCodes>>,
prefix_trees_distances: Option<Vec<HuffmanCodes>>,
btype_l: NBltypes,
btype_l_prev: NBltypes,
blen_l: Option<BLen>,
btype_i: NBltypes,
btype_i_prev: NBltypes,
blen_i: Option<BLen>,
btype_d: NBltypes,
btype_d_prev: NBltypes,
blen_d: Option<BLen>,
insert_and_copy_length: Option<Symbol>,
insert_length: Option<InsertLength>,
copy_length: Option<CopyLength>,
distance_code: Option<DistanceCode>,
distance: Option<Distance>,
}
impl MetaBlock {
fn new() -> MetaBlock {
MetaBlock{
header: MetaBlockHeader::new(),
count_output: 0,
btype_l: 0,
btype_l_prev: 1,
blen_l: None,
btype_i: 0,
btype_i_prev: 1,
blen_i: None,
btype_d: 0,
btype_d_prev: 1,
blen_d: None,
context_modes_literals: None,
prefix_tree_block_types_literals: None,
prefix_tree_block_counts_literals: None,
prefix_tree_block_types_insert_and_copy_lengths: None,
prefix_tree_block_counts_insert_and_copy_lengths: None,
prefix_tree_block_types_distances: None,
prefix_tree_block_counts_distances: None,
prefix_trees_literals: None,
prefix_trees_insert_and_copy_lengths: None,
prefix_trees_distances: None,
insert_and_copy_length: None,
insert_length: None,
copy_length: None,
distance_code: None,
distance: None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
struct MetaBlockHeader {
is_last: Option<IsLast>,
is_last_empty: Option<IsLastEmpty>,
m_nibbles: Option<MNibbles>,
m_skip_bytes: Option<MSkipBytes>,
m_skip_len: Option<MSkipLen>,
m_len: Option<MLen>,
is_uncompressed: Option<IsUncompressed>,
n_bltypes_l: Option<NBltypes>,
n_bltypes_i: Option<NBltypes>,
n_bltypes_d: Option<NBltypes>,
n_postfix: Option<NPostfix>,
n_direct: Option<NDirect>,
n_trees_l: Option<NTrees>,
n_trees_d: Option<NTrees>,
c_map_d: Option<ContextMap>,
c_map_l: Option<ContextMap>,
prefix_code_block_types_literals: Option<PrefixCode>,
prefix_code_block_counts_literals: Option<PrefixCode>,
prefix_code_block_types_insert_and_copy_lengths: Option<PrefixCode>,
prefix_code_block_counts_insert_and_copy_lengths: Option<PrefixCode>,
prefix_code_block_types_distances: Option<PrefixCode>,
prefix_code_block_counts_distances: Option<PrefixCode>,
prefix_codes_literals: Option<Vec<PrefixCode>>,
prefix_codes_insert_and_copy_lengths: Option<Vec<PrefixCode>>,
prefix_codes_distances: Option<Vec<PrefixCode>>,
}
impl MetaBlockHeader {
fn new() -> MetaBlockHeader {
MetaBlockHeader{
is_last: None,
is_last_empty: None,
m_nibbles: None,
m_skip_bytes: None,
m_skip_len: None,
m_len: None,
is_uncompressed: None,
n_bltypes_l: None,
n_bltypes_i: None,
n_bltypes_d: None,
n_postfix: None,
n_direct: None,
n_trees_l: None,
n_trees_d: None,
c_map_d: None,
c_map_l: None,
prefix_code_block_types_literals: None,
prefix_code_block_counts_literals: None,
prefix_code_block_types_insert_and_copy_lengths: None,
prefix_code_block_counts_insert_and_copy_lengths: None,
prefix_code_block_types_distances: None,
prefix_code_block_counts_distances: None,
prefix_codes_literals: None,
prefix_codes_insert_and_copy_lengths: None,
prefix_codes_distances: None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
enum State {
StreamBegin,
HeaderBegin,
WBitsCodes(HuffmanCodes),
WBits(WBits),
HeaderEnd,
HeaderMetaBlockBegin,
IsLast(IsLast),
IsLastEmpty(IsLastEmpty),
MNibbles(MNibbles),
MSkipBytes(MSkipBytes),
MSkipLen(MSkipLen),
MLen(MLen),
IsUncompressed(IsUncompressed),
MLenLiterals(MLenLiterals),
BltypeCodes(HuffmanCodes),
NBltypesL(NBltypes),
PrefixCodeBlockTypesLiterals((PrefixCode, HuffmanCodes)),
PrefixCodeBlockCountsLiterals((PrefixCode, HuffmanCodes)),
FirstBlockCountLiterals(BLen),
NBltypesI(NBltypes),
PrefixCodeBlockTypesInsertAndCopyLengths((PrefixCode, HuffmanCodes)),
PrefixCodeBlockCountsInsertAndCopyLengths((PrefixCode, HuffmanCodes)),
FirstBlockCountInsertAndCopyLengths(BLen),
NBltypesD(NBltypes),
PrefixCodeBlockTypesDistances((PrefixCode, HuffmanCodes)),
PrefixCodeBlockCountsDistances((PrefixCode, HuffmanCodes)),
FirstBlockCountDistances(BLen),
NPostfix(NPostfix),
NDirect(NDirect),
ContextModesLiterals(ContextModes),
NTreesL(NTrees),
NTreesD(NTrees),
ContextMapDistances(ContextMap),
ContextMapLiterals(ContextMap),
PrefixCodesLiterals(Vec<(PrefixCode, HuffmanCodes)>),
PrefixCodesInsertAndCopyLengths(Vec<(PrefixCode, HuffmanCodes)>),
PrefixCodesDistances(Vec<(PrefixCode, HuffmanCodes)>),
DataMetaBlockBegin,
InsertAndCopyLength(InsertAndCopyLength),
InsertLengthAndCopyLength(InsertLengthAndCopyLength),
InsertLiterals(Literals),
DistanceCode(DistanceCode),
Distance(Distance),
CopyLiterals(Literals),
DataMetaBlockEnd,
MetaBlockEnd,
StreamEnd,
}
#[derive(Debug, Clone, PartialEq)]
enum DecompressorError {
UnexpectedEOF,
NonZeroFillBit,
NonZeroReservedBit,
NonZeroTrailerBit,
NonZeroTrailerNibble,
ExpectedEndOfStream,
InvalidMSkipLen,
ParseErrorInsertAndCopyLength,
ParseErrorInsertLiterals,
ParseErrorContextMap,
ParseErrorDistanceCode,
ExceededExpectedBytes,
ParseErrorComplexPrefixCodeLengths,
RingBufferError,
RunLengthExceededSizeOfContextMap,
InvalidTransformId,
InvalidLengthInStaticDictionary,
CodeLengthsChecksum,
}
impl Display for DecompressorError {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
fmt.write_str(self.description())
}
}
impl Error for DecompressorError {
fn description(&self) -> &str {
match *self {
DecompressorError::UnexpectedEOF => "Encountered unexpected EOF",
DecompressorError::NonZeroFillBit => "Enocuntered non-zero fill bit",
DecompressorError::NonZeroReservedBit => "Enocuntered non-zero reserved bit",
DecompressorError::NonZeroTrailerBit => "Enocuntered non-zero bit trailing the stream",
DecompressorError::NonZeroTrailerNibble => "Enocuntered non-zero nibble trailing",
DecompressorError::ExpectedEndOfStream => "Expected end-of-stream, but stream did not end",
DecompressorError::InvalidMSkipLen => "Most significant byte of MSKIPLEN was zero",
DecompressorError::ParseErrorInsertAndCopyLength => "Error parsing Insert And Copy Length",
DecompressorError::ParseErrorInsertLiterals => "Error parsing Insert Literals",
DecompressorError::ParseErrorDistanceCode => "Error parsing DistanceCode",
DecompressorError::ExceededExpectedBytes => "More uncompressed bytes than expected in meta-block",
DecompressorError::ParseErrorContextMap => "Error parsing context map",
DecompressorError::ParseErrorComplexPrefixCodeLengths => "Error parsing code lengths for complex prefix code",
DecompressorError::RingBufferError => "Error accessing distance ring buffer",
DecompressorError::RunLengthExceededSizeOfContextMap => "Run length excceeded declared length of context map",
DecompressorError::InvalidTransformId => "Encountered invalid transform id in reference to static dictionary",
DecompressorError::InvalidLengthInStaticDictionary => "Encountered invalid length in reference to static dictionary",
DecompressorError::CodeLengthsChecksum => "Code length check sum did not add up to 32 in complex prefix code",
}
}
}
/// Wraps an input stream and provides methods for decompressing.
///
/// # Examples
/// ```
/// use std::io::{ Read, stdout, Write };
/// use brotli::Decompressor;
///
/// let brotli_stream = std::fs::File::open("data/64x.compressed").unwrap();
///
/// let mut decompressed = &mut Vec::new();
/// let _ = Decompressor::new(brotli_stream).read_to_end(&mut decompressed);
///
/// let mut expected = &mut Vec::new();
/// let _ = std::fs::File::open("data/64x").unwrap().read_to_end(&mut expected);
///
/// assert_eq!(expected, decompressed);
///
/// stdout().write_all(decompressed).ok();
#[derive(Debug)]
pub struct Decompressor<R: Read> {
in_stream: BitReader<R>,
header: Header,
buf: VecDeque<Literal>,
output_window: Option<RingBuffer<Literal>>,
state: State,
meta_block: MetaBlock,
count_output: usize,
/// ring buffer for last 2 literals, gets set
/// at the beginning of the stream, and then
/// lives until the end
literal_buf: RingBuffer<Literal>,
/// ring buffer for last 4 distances, gets set
/// at the beginning of the stream, and then
/// lives until the end
distance_buf: RingBuffer<Distance>,
}
impl<R: Read> Decompressor<R> {
/// Creates Decompressor from Read.
pub fn new(r: R) -> Decompressor<R> {
Decompressor{
in_stream: BitReader::new(r),
header: Header::new(),
buf: VecDeque::new(),
output_window: None,
state: State::StreamBegin,
meta_block: MetaBlock::new(),
count_output: 0,
literal_buf: RingBuffer::from_vec(vec![0, 0]),
distance_buf: RingBuffer::from_vec(vec![4, 11, 15, 16]),
}
}
fn create_wbits_codes() -> Result<State, DecompressorError> {
let bit_patterns = vec![
vec![true, false, false, false, false, true, false],
vec![true, false, false, false, true, true, false],
vec![true, false, false, false, false, false, true],
vec![true, false, false, false, true, false, true],
vec![true, false, false, false, false, true, true],
vec![true, false, false, false, true, true, true],
vec![false],
vec![true, false, false, false, false, false, false],
vec![true, true, false, false],
vec![true, false, true, false],
vec![true, true, true, false],
vec![true, false, false, true],
vec![true, true, false, true],
vec![true, false, true, true],
vec![true, true, true, true],
];
let symbols = vec![10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
let mut codes = Tree::with_max_depth(7);
for i in 0..bit_patterns.len() {
codes.insert(&bit_patterns[i], symbols[i]);
}
Ok(State::WBitsCodes(codes))
}
fn parse_wbits(&mut self) -> Result<State, DecompressorError> {
match self.header.wbits_codes.as_ref().unwrap().lookup_symbol(&mut self.in_stream) {
Ok(Some(symbol)) => Ok(State::WBits(symbol as WBits)),
Ok(None) => Err(DecompressorError::UnexpectedEOF),
Err(_) => return Err(DecompressorError::UnexpectedEOF),
}
}
fn parse_is_last(&mut self) -> Result<State, DecompressorError> {
match self.in_stream.read_bit() {
Ok(bit) => Ok(State::IsLast(bit)),
Err(_) => Err(DecompressorError::UnexpectedEOF),
}
}
fn parse_is_last_empty(&mut self) -> Result<State, DecompressorError> {
match self.in_stream.read_bit() {
Ok(bit) => Ok(State::IsLastEmpty(bit)),
Err(_) => Err(DecompressorError::UnexpectedEOF),
}
}
fn parse_m_nibbles(&mut self) -> Result<State, DecompressorError> {
match self.in_stream.read_u8_from_n_bits(2) {
Ok(3) => Ok(State::MNibbles(0)),
Ok(my_u8) => Ok(State::MNibbles(my_u8 + 4)),
Err(_) => Err(DecompressorError::UnexpectedEOF),
}
}
fn parse_m_skip_bytes(&mut self) -> Result<State, DecompressorError> {
match self.in_stream.read_u8_from_n_bits(2) {
Ok(my_u8) => Ok(State::MSkipBytes(my_u8)),
Err(_) => Err(DecompressorError::UnexpectedEOF),
}
}
fn parse_m_skip_len(&mut self) -> Result<State, DecompressorError> {
let bytes = match self.in_stream.read_fixed_length_string(self.meta_block.header.m_skip_bytes.unwrap() as usize) {
Ok(bytes) => bytes,
Err(_) => return Err(DecompressorError::UnexpectedEOF),
};
let l = bytes.len();
if l > 1 && bytes[l - 1] == 0 {
return Err(DecompressorError::InvalidMSkipLen);
}
Ok(State::MSkipLen({
let mut m_skip_len: MSkipLen = 0;
for (i, byte) in bytes.iter().enumerate() {
m_skip_len = m_skip_len | ((*byte as MSkipLen) << i);
}
m_skip_len + 1
}))
}
fn parse_m_len(&mut self) -> Result<State, DecompressorError> {
let m_nibbles = self.meta_block.header.m_nibbles.unwrap() as usize;
let m_len = match self.in_stream.read_u32_from_n_nibbles(m_nibbles) {
Ok(m_len) => m_len,
Err(_) => return Err(DecompressorError::UnexpectedEOF),
};
if m_nibbles > 4 && (m_len >> ((m_nibbles - 1) * 4) == 0) {
Err(DecompressorError::NonZeroTrailerNibble)
} else {
Ok(State::MLen(m_len + 1))
}
}
fn parse_is_uncompressed(&mut self) -> Result<State, DecompressorError> {
match self.in_stream.read_bit() {
Ok(bit) => Ok(State::IsUncompressed(bit)),
Err(_) => Err(DecompressorError::UnexpectedEOF),
}
}
fn parse_mlen_literals(&mut self) -> Result<State, DecompressorError> {
let bytes = match self.in_stream.read_fixed_length_string(self.meta_block.header.m_len.unwrap() as usize) {
Ok(bytes) => bytes,
Err(_) => return Err(DecompressorError::UnexpectedEOF),
};
Ok(State::MLenLiterals(bytes))
}
fn create_block_type_codes() -> Result<State, DecompressorError> {
let bit_patterns = vec![
vec![false],
vec![true, false, false, false],
vec![true, true, false, false],
vec![true, false, true, false],
vec![true, true, true, false],
vec![true, false, false, true],
vec![true, true, false, true],
vec![true, false, true, true],
vec![true, true, true, true],
];
let symbols = vec![1, 2, 3, 5, 9, 17, 33, 65, 129];
let mut codes = Tree::with_max_depth(4);
for i in 0..bit_patterns.len() {
codes.insert(&bit_patterns[i], symbols[i]);
}
Ok(State::BltypeCodes(codes))
}
fn parse_n_bltypes(&mut self) -> Result<NBltypes, DecompressorError> {
let (value, extra_bits) = match self.header.bltype_codes.as_ref().unwrap().lookup_symbol(&mut self.in_stream) {
Ok(Some(symbol @ 1...2)) => (symbol, 0),
Ok(Some(symbol @ 3)) => (symbol, 1),
Ok(Some(symbol @ 5)) => (symbol, 2),
Ok(Some(symbol @ 9)) => (symbol, 3),
Ok(Some(symbol @ 17)) => (symbol, 4),
Ok(Some(symbol @ 33)) => (symbol, 5),
Ok(Some(symbol @ 65)) => (symbol, 6),
Ok(Some(symbol @ 129)) => (symbol, 7),
Ok(Some(_)) => unreachable!(),
Ok(None) => return Err(DecompressorError::UnexpectedEOF),
Err(_) => return Err(DecompressorError::UnexpectedEOF),
};
if extra_bits > 0 {
match self.in_stream.read_u8_from_n_bits(extra_bits) {
Ok(extra) => Ok(value as NBltypes + extra),
Err(_) => Err(DecompressorError::UnexpectedEOF),
}
} else {
Ok(value as NBltypes)
}
}
fn parse_n_bltypes_l(&mut self) -> Result<State, DecompressorError> {
match self.parse_n_bltypes() {
Ok(value) => Ok(State::NBltypesL(value)),
Err(e) => Err(e)
}
}
fn parse_n_bltypes_i(&mut self) -> Result<State, DecompressorError> {
match self.parse_n_bltypes() {
Ok(value) => Ok(State::NBltypesI(value)),
Err(e) => Err(e)
}
}
fn parse_n_bltypes_d(&mut self) -> Result<State, DecompressorError> {
match self.parse_n_bltypes() {
Ok(value) => Ok(State::NBltypesD(value)),
Err(e) => Err(e)
}
}
fn parse_n_postfix(&mut self) -> Result<State, DecompressorError> {
match self.in_stream.read_u8_from_n_bits(2) {
Ok(my_u8) => Ok(State::NPostfix(my_u8)),
Err(_) => Err(DecompressorError::UnexpectedEOF),
}
}
fn parse_n_direct(&mut self) -> Result<State, DecompressorError> {
match self.in_stream.read_u8_from_n_bits(4) {
Ok(my_u8) => Ok(State::NDirect(my_u8 << self.meta_block.header.n_postfix.unwrap())),
Err(_) => Err(DecompressorError::UnexpectedEOF),
}
}
fn parse_context_modes_literals(&mut self) -> Result<State, DecompressorError> {
let mut context_modes = vec![0; self.meta_block.header.n_bltypes_l.unwrap() as usize];
for mut mode in &mut context_modes {
match self.in_stream.read_u8_from_n_bits(2) {
Ok(my_u8) => *mode = my_u8 as ContextMode,
Err(_) => return Err(DecompressorError::UnexpectedEOF),
}
}
Ok(State::ContextModesLiterals(context_modes))
}
fn parse_n_trees_l(&mut self) -> Result<State, DecompressorError> {
match self.parse_n_bltypes() {
Ok(value) => Ok(State::NTreesL(value)),
Err(e) => Err(e)
}
}
fn parse_n_trees_d(&mut self) -> Result<State, DecompressorError> {
match self.parse_n_bltypes() {
Ok(value) => Ok(State::NTreesD(value)),
Err(e) => Err(e)
}
}
fn parse_prefix_code_kind(&mut self) -> Result<PrefixCodeKind, DecompressorError> {
match self.in_stream.read_u8_from_n_bits(2) {
Ok(1) => Ok(PrefixCodeKind::Simple),
Ok(h_skip) => Ok(PrefixCodeKind::Complex(h_skip)),
Err(_) => Err(DecompressorError::UnexpectedEOF),
}
}
fn parse_simple_prefix_code(&mut self, alphabet_size: usize) -> Result<(PrefixCode, HuffmanCodes), DecompressorError> {
let bit_width = 16 - (alphabet_size as u16 - 1).leading_zeros() as usize;
// debug(&format!("Bit Width = {:?}", bit_width));
let n_sym = match self.in_stream.read_u8_from_n_bits(2) {
Ok(my_u8) => (my_u8 + 1) as usize,
Err(_) => return Err(DecompressorError::UnexpectedEOF),
};
// debug(&format!("NSYM = {:?}", n_sym));
let mut symbols = vec![0; n_sym];
for symbol in &mut symbols {
*symbol = match self.in_stream.read_u16_from_n_bits(bit_width) {
Ok(my_u8) => my_u8,
Err(_) => return Err(DecompressorError::UnexpectedEOF),
}
}
// debug(&format!("Symbols = {:?}", symbols));
let tree_select = match n_sym {
4 => match self.in_stream.read_bit() {
Ok(v) => Some(v),
Err(_) => return Err(DecompressorError::UnexpectedEOF),
},
_ => None,
};
let code_lengths = match (n_sym, tree_select) {
(1, None) => vec![0],
(2, None) => {
symbols.sort();
vec![1, 1]
},
(3, None) => {
symbols[1..3].sort();
vec![1, 2, 2]
},
(4, Some(false)) => {
symbols.sort();
vec![2, 2, 2, 2]
},
(4, Some(true)) => {
symbols[2..4].sort();
vec![1, 2, 3, 3]
},
_ => unreachable!(),
};
// debug(&format!("Sorted Symbols = {:?}", symbols));
// debug(&format!("Code Lengths = {:?}", code_lengths));
Ok((PrefixCode::new_simple(Some(n_sym as u8), Some(symbols.clone()), tree_select),
huffman::codes_from_lengths_and_symbols(&code_lengths, &symbols)))
}
fn parse_complex_prefix_code(&mut self, h_skip: u8, alphabet_size: usize)
-> Result<(PrefixCode, HuffmanCodes), DecompressorError> {
let mut symbols = vec![1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15];
let bit_lengths_code = {
let bit_lengths_patterns = vec![
vec![false, false],
vec![true, true, true, false],
vec![true, true, false],
vec![false, true],
vec![true, false],
vec![true, true, true, true],
];
let symbols = vec![0, 1, 2, 3, 4, 5];
let mut codes = Tree::with_max_depth(4);
for i in 0..bit_lengths_patterns.len() {
codes.insert(&bit_lengths_patterns[i], symbols[i]);
}
codes
};
let mut code_lengths = vec![0; symbols.len()];
let mut sum = 0usize;
for i in (h_skip as usize)..symbols.len() {
code_lengths[i] = match bit_lengths_code.lookup_symbol(&mut self.in_stream) {
Ok(Some(code_length)) => code_length as usize,
Ok(None) => return Err(DecompressorError::ParseErrorComplexPrefixCodeLengths),
Err(_) => return Err(DecompressorError::UnexpectedEOF),
};
if code_lengths[i] > 0 {
sum += 32 >> code_lengths[i];
// debug(&format!("code length = {:?}", code_lengths[i]));
// debug(&format!("32 >> code length = {:?}", 32 >> code_lengths[i]));
// debug(&format!("sum = {:?}", sum));
if sum == 32 {
break;
}
if sum > 32 {
return Err(DecompressorError::CodeLengthsChecksum)
}
}
}
// debug(&format!("Code Lengths = {:?}", code_lengths));
// debug(&format!("Symbols = {:?}", symbols));
code_lengths = vec![code_lengths[4], code_lengths[0], code_lengths[1], code_lengths[2], code_lengths[3], code_lengths[5], code_lengths[7], code_lengths[9], code_lengths[10], code_lengths[11], code_lengths[12], code_lengths[13], code_lengths[14], code_lengths[15], code_lengths[16], code_lengths[17], code_lengths[8], code_lengths[6]];
symbols = (0..18).collect::<Vec<_>>();
// debug(&format!("Code Lengths = {:?}", code_lengths));
// debug(&format!("Symbols = {:?}", symbols));
let lone_symbol = {
if sum < 32 {
let mut i = 0;
while code_lengths[i] == 0 {
i += 1;
}
Some(symbols[i])
} else {
None
}
};
// debug(&format!("Code Lengths = {:?}", code_lengths));
// debug(&format!("Symbols = {:?}", symbols));
let prefix_code_code_lengths = huffman::codes_from_lengths_and_symbols(&code_lengths, &symbols);
// debug(&format!("Prefix Code CodeLengths = {:?}", prefix_code_code_lengths));
let mut actual_code_lengths = Vec::new();
let mut sum = 0usize;
let mut last_symbol = None;
let mut last_repeat = None;
let mut last_non_zero_codelength = 8;
loop {
let code_length_code = if lone_symbol == None {
match prefix_code_code_lengths.lookup_symbol(&mut self.in_stream) {
Ok(symbol) => symbol,
Err(_) => return Err(DecompressorError::UnexpectedEOF),
}
} else { lone_symbol };
// debug(&format!("lone_symbol = {:?}", lone_symbol));
// debug(&format!("code length code = {:?}", code_length_code));
match code_length_code {
Some(new_code_length @ 0...15) => {
actual_code_lengths.push(new_code_length as usize);
last_symbol = Some(new_code_length);
last_repeat = None;
if new_code_length > 0 {
last_non_zero_codelength = new_code_length;
sum += 32768 >> new_code_length;
// debug(&format!("32768 >> code length == {:?}, sum == {:?}", 32768 >> new_code_length, sum));
if sum == 32768 {
break;
}
}
},
Some(16) => {
let extra_bits = match self.in_stream.read_u8_from_n_bits(2) {
Ok(my_u8) => my_u8 as usize,
Err(_) => return Err(DecompressorError::UnexpectedEOF),
};
last_repeat = match (last_symbol, last_repeat) {
(Some(16), Some(last_repeat)) => {
let new_repeat: usize = (4 * (last_repeat - 2)) + extra_bits + 3;
for _ in 0..new_repeat - last_repeat {
actual_code_lengths.push(last_non_zero_codelength as usize);
sum += 32768 >> last_non_zero_codelength;
// debug(&format!("32768 >> code length == {:?}, sum == {:?}", 32768 >> last_non_zero_codelength, sum));
if sum == 32768 {
break;
}
}
if sum == 32768 {
break;
}
Some(new_repeat)
},
(_, _) => {
let repeat = 3 + extra_bits;
for _ in 0..repeat {
actual_code_lengths.push(last_non_zero_codelength as usize);
sum += 32768 >> last_non_zero_codelength;
// debug(&format!("32768 >> code length == {:?}, sum == {:?}", 32768 >> last_non_zero_codelength, sum));
if sum == 32768 {
break;
}
}
if sum == 32768 {
break;
}
Some(repeat)
},
};
last_symbol = Some(16);
},
Some(17) => {
let extra_bits = match self.in_stream.read_u8_from_n_bits(3) {
Ok(my_u8) => my_u8,
Err(_) => return Err(DecompressorError::UnexpectedEOF),
};
// debug(&format!("code length = 17, extra bits = {:?}", extra_bits));
last_repeat = match (last_symbol, last_repeat) {
(Some(17), Some(last_repeat)) => {
let new_repeat = (8 * (last_repeat - 2)) + extra_bits as usize + 3;
for _ in 0..new_repeat - last_repeat {
actual_code_lengths.push(0);
}
Some(new_repeat)
},
(_, _) => {
let repeat = 3 + extra_bits as usize;
for _ in 0..repeat {
actual_code_lengths.push(0);
}
Some(repeat)
},
};
last_symbol = Some(17);
},
Some(_) => unreachable!(),
None => return Err(DecompressorError::ParseErrorComplexPrefixCodeLengths),
};
if actual_code_lengths.len() > alphabet_size {
return Err(DecompressorError::ParseErrorComplexPrefixCodeLengths);
}
}
// debug(&format!(""));
// debug(&format!("Actual Code Lengths = {:?}", actual_code_lengths));
// if actual_code_lengths.iter().filter(|&l| *l > 0).collect::<Vec<_>>().len() == 1 {
// // @TODO handle case in lookup from complex prefix code when
// // there's only one symbol. In that case, no bit should
// // be consumed from the stream, and the one symbol should
// // be emitted immediately.
// // @NOTE This might not be possible to happen.
// unimplemented!();
// }
Ok((PrefixCode::Complex,
huffman::codes_from_lengths(&actual_code_lengths)))
}
fn parse_prefix_code(&mut self, alphabet_size: usize) -> Result<(PrefixCode, HuffmanCodes), DecompressorError> {
let prefix_code_kind = match self.parse_prefix_code_kind() {
Ok(kind) => kind,
Err(e) => return Err(e),
};
// debug(&format!("Prefix Code Kind = {:?}", prefix_code_kind));
match prefix_code_kind {
PrefixCodeKind::Complex(h_skip) => self.parse_complex_prefix_code(h_skip, alphabet_size),
PrefixCodeKind::Simple => self.parse_simple_prefix_code(alphabet_size),
}
}
fn parse_prefix_code_block_types_literals(&mut self) -> Result<State, DecompressorError> {
let alphabet_size = (self.meta_block.header.n_bltypes_l.unwrap() as usize) + 2;
Ok(State::PrefixCodeBlockTypesLiterals(
match self.parse_prefix_code(alphabet_size) {
Ok(prefix_code) => prefix_code,
Err(e) => return Err(e),
}
))
}
fn parse_prefix_code_block_counts_literals(&mut self) -> Result<State, DecompressorError> {
let alphabet_size = 26;
Ok(State::PrefixCodeBlockCountsLiterals(
match self.parse_prefix_code(alphabet_size) {
Ok(prefix_code) => prefix_code,
Err(e) => return Err(e),
}
))
}
fn parse_prefix_code_block_types_insert_and_copy_lengths(&mut self) -> Result<State, DecompressorError> {
let alphabet_size = (self.meta_block.header.n_bltypes_i.unwrap() as usize) + 2;
Ok(State::PrefixCodeBlockTypesInsertAndCopyLengths(
match self.parse_prefix_code(alphabet_size) {
Ok(prefix_code) => prefix_code,
Err(e) => return Err(e),
}
))
}
fn parse_prefix_code_block_counts_insert_and_copy_lengths(&mut self) -> Result<State, DecompressorError> {
let alphabet_size = 26;
Ok(State::PrefixCodeBlockCountsInsertAndCopyLengths(
match self.parse_prefix_code(alphabet_size) {
Ok(prefix_code) => prefix_code,
Err(e) => return Err(e),
}
))
}
fn parse_prefix_code_block_types_distances(&mut self) -> Result<State, DecompressorError> {
let alphabet_size = (self.meta_block.header.n_bltypes_d.unwrap() as usize) + 2;
Ok(State::PrefixCodeBlockTypesDistances(
match self.parse_prefix_code(alphabet_size) {
Ok(prefix_code) => prefix_code,
Err(e) => return Err(e),
}