1#![allow(non_camel_case_types)]
2#![allow(non_snake_case)]
3#![allow(non_upper_case_globals)]
4
5
6use alloc;
7use core;
8use context::kContextLookup;
9use bit_reader::{BrotliBitReader, BrotliGetAvailableBits, BrotliInitBitReader};
10use huffman::{BROTLI_HUFFMAN_MAX_CODE_LENGTH, BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE,
11 BROTLI_HUFFMAN_MAX_SIZE_272, HuffmanCode, HuffmanTreeGroup};
12use alloc::SliceWrapper;
13use alloc::SliceWrapperMut;
14use shared_dictionary;
15use shared_dictionary::{BrotliSharedDictionary, TRANSFORM_LIST_STRIDE, WORD_LIST_STRIDE};
16
17#[allow(dead_code)]
18pub enum WhichTreeGroup {
19 LITERAL,
20 INSERT_COPY,
21 DISTANCE,
22}
23#[repr(C)]
26#[derive(Clone,Copy, Debug)]
27pub enum BrotliDecoderParameter {
28 BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION = 0,
29 BROTLI_DECODER_PARAM_LARGE_WINDOW = 1,
30}
31#[repr(C)]
32#[derive(Clone,Copy, Debug)]
33pub enum BrotliDecoderErrorCode{
34 BROTLI_DECODER_NO_ERROR = 0,
35 BROTLI_DECODER_SUCCESS = 1,
37 BROTLI_DECODER_NEEDS_MORE_INPUT = 2,
38 BROTLI_DECODER_NEEDS_MORE_OUTPUT = 3,
39
40 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE = -1,
42 BROTLI_DECODER_ERROR_FORMAT_RESERVED = -2,
43 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE = -3,
44 BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET = -4,
45 BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME = -5,
46 BROTLI_DECODER_ERROR_FORMAT_CL_SPACE = -6,
47 BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE = -7,
48 BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT = -8,
49 BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1 = -9,
50 BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2 = -10,
51 BROTLI_DECODER_ERROR_FORMAT_TRANSFORM = -11,
52 BROTLI_DECODER_ERROR_FORMAT_DICTIONARY = -12,
53 BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS = -13,
54 BROTLI_DECODER_ERROR_FORMAT_PADDING_1 = -14,
55 BROTLI_DECODER_ERROR_FORMAT_PADDING_2 = -15,
56 BROTLI_DECODER_ERROR_FORMAT_DISTANCE = -16,
57 BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH = -17,
58
59 BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY = -18,
60 BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET = -19,
61 BROTLI_DECODER_ERROR_INVALID_ARGUMENTS = -20,
62
63 BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES = -21,
65 BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS = -22,
67 BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP = -25,
69 BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1 = -26,
70 BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2 = -27,
71 BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES = -30,
73
74 BROTLI_DECODER_ERROR_UNREACHABLE = -31,
76}
77
78#[derive(Debug)]
79pub enum BrotliRunningState {
80 BROTLI_STATE_UNINITED,
81 BROTLI_STATE_LARGE_WINDOW_BITS,
82 BROTLI_STATE_INITIALIZE,
83 BROTLI_STATE_METABLOCK_BEGIN,
84 BROTLI_STATE_METABLOCK_HEADER,
85 BROTLI_STATE_METABLOCK_HEADER_2,
86 BROTLI_STATE_CONTEXT_MODES,
87 BROTLI_STATE_COMMAND_BEGIN,
88 BROTLI_STATE_COMMAND_INNER,
89 BROTLI_STATE_COMMAND_POST_DECODE_LITERALS,
90 BROTLI_STATE_COMMAND_POST_WRAP_COPY,
91 BROTLI_STATE_UNCOMPRESSED,
92 BROTLI_STATE_METADATA,
93 BROTLI_STATE_COMMAND_INNER_WRITE,
94 BROTLI_STATE_METABLOCK_DONE,
95 BROTLI_STATE_COMMAND_POST_WRITE_1,
96 BROTLI_STATE_COMMAND_POST_WRITE_2,
97 BROTLI_STATE_HUFFMAN_CODE_0,
98 BROTLI_STATE_HUFFMAN_CODE_1,
99 BROTLI_STATE_HUFFMAN_CODE_2,
100 BROTLI_STATE_HUFFMAN_CODE_3,
101 BROTLI_STATE_CONTEXT_MAP_1,
102 BROTLI_STATE_CONTEXT_MAP_2,
103 BROTLI_STATE_TREE_GROUP,
104 BROTLI_STATE_DONE,
105}
106
107pub enum BrotliRunningMetablockHeaderState {
108 BROTLI_STATE_METABLOCK_HEADER_NONE,
109 BROTLI_STATE_METABLOCK_HEADER_EMPTY,
110 BROTLI_STATE_METABLOCK_HEADER_NIBBLES,
111 BROTLI_STATE_METABLOCK_HEADER_SIZE,
112 BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED,
113 BROTLI_STATE_METABLOCK_HEADER_RESERVED,
114 BROTLI_STATE_METABLOCK_HEADER_BYTES,
115 BROTLI_STATE_METABLOCK_HEADER_METADATA,
116}
117pub enum BrotliRunningUncompressedState {
118 BROTLI_STATE_UNCOMPRESSED_NONE,
119 BROTLI_STATE_UNCOMPRESSED_WRITE,
120}
121
122pub enum BrotliRunningTreeGroupState {
123 BROTLI_STATE_TREE_GROUP_NONE,
124 BROTLI_STATE_TREE_GROUP_LOOP,
125}
126
127pub enum BrotliRunningContextMapState {
128 BROTLI_STATE_CONTEXT_MAP_NONE,
129 BROTLI_STATE_CONTEXT_MAP_READ_PREFIX,
130 BROTLI_STATE_CONTEXT_MAP_HUFFMAN,
131 BROTLI_STATE_CONTEXT_MAP_DECODE,
132 BROTLI_STATE_CONTEXT_MAP_TRANSFORM,
133}
134
135pub enum BrotliRunningHuffmanState {
136 BROTLI_STATE_HUFFMAN_NONE,
137 BROTLI_STATE_HUFFMAN_SIMPLE_SIZE,
138 BROTLI_STATE_HUFFMAN_SIMPLE_READ,
139 BROTLI_STATE_HUFFMAN_SIMPLE_BUILD,
140 BROTLI_STATE_HUFFMAN_COMPLEX,
141 BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS,
142}
143
144pub enum BrotliRunningDecodeUint8State {
145 BROTLI_STATE_DECODE_UINT8_NONE,
146 BROTLI_STATE_DECODE_UINT8_SHORT,
147 BROTLI_STATE_DECODE_UINT8_LONG,
148}
149
150pub enum BrotliRunningReadBlockLengthState {
151 BROTLI_STATE_READ_BLOCK_LENGTH_NONE,
152 BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX,
153}
154
155pub const kLiteralContextBits: usize = 6;
156
157pub const SHARED_BROTLI_MAX_COMPOUND_DICTS: usize = 15;
161#[cfg(target_pointer_width = "64")]
164pub const SHARED_BROTLI_MAX_RAW_DICT_SIZE: usize = 1usize << 31;
165#[cfg(not(target_pointer_width = "64"))]
166pub const SHARED_BROTLI_MAX_RAW_DICT_SIZE: usize = 1usize << 27;
167
168#[allow(dead_code)]
179pub enum MaybeOwnedSlice<AllocU8: alloc::Allocator<u8>> {
180 Owned(AllocU8::AllocatedMemory),
181 Borrowed(&'static [u8]),
186 External(usize),
189}
190
191impl<AllocU8: alloc::Allocator<u8>> Default for MaybeOwnedSlice<AllocU8> {
192 fn default() -> Self {
193 MaybeOwnedSlice::Owned(AllocU8::AllocatedMemory::default())
194 }
195}
196
197impl<AllocU8: alloc::Allocator<u8>> alloc::SliceWrapper<u8> for MaybeOwnedSlice<AllocU8> {
198 fn slice(&self) -> &[u8] {
199 match *self {
200 MaybeOwnedSlice::Owned(ref mem) => mem.slice(),
201 MaybeOwnedSlice::Borrowed(data) => data,
202 MaybeOwnedSlice::External(_) => &[],
203 }
204 }
205}
206
207pub const COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED: u32 = 255;
214
215
216pub trait BrotliMetadataCallback {
217 fn start(&mut self, _size: usize) {}
218 fn chunk(&mut self, _data: &[u8]) {}
219}
220
221pub struct BrotliDecoderCompoundDictionary<AllocU8: alloc::Allocator<u8>> {
227 pub num_chunks: usize,
228 pub total_size: usize,
229 pub block_bits: u32,
233 pub block_map: [u8; 256],
234 pub chunk_offsets: [u32; SHARED_BROTLI_MAX_COMPOUND_DICTS + 1],
237 pub chunks: [MaybeOwnedSlice<AllocU8>; SHARED_BROTLI_MAX_COMPOUND_DICTS],
238 pub br_index: usize,
241 pub br_offset: usize,
242 pub br_length: usize,
243 pub br_copied: usize,
244}
245
246impl<AllocU8: alloc::Allocator<u8>> Default for BrotliDecoderCompoundDictionary<AllocU8> {
247 fn default() -> Self {
248 BrotliDecoderCompoundDictionary::<AllocU8> {
249 num_chunks: 0,
250 total_size: 0,
251 block_bits: COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED,
252 block_map: [0; 256],
253 chunk_offsets: [0; SHARED_BROTLI_MAX_COMPOUND_DICTS + 1],
254 chunks: Default::default(),
255 br_index: 0,
256 br_offset: 0,
257 br_length: 0,
258 br_copied: 0,
259 }
260 }
261}
262
263pub struct BlockTypeAndLengthState<AllocHC: alloc::Allocator<HuffmanCode>> {
264 pub substate_read_block_length: BrotliRunningReadBlockLengthState,
265 pub num_block_types: [u32; 3],
266 pub block_length_index: u32,
267 pub block_length: [u32; 3],
268 pub block_type_trees: AllocHC::AllocatedMemory,
269 pub block_len_trees: AllocHC::AllocatedMemory,
270 pub block_type_rb: [u32; 6],
271}
272
273pub struct BrotliState<AllocU8: alloc::Allocator<u8>,
274 AllocU32: alloc::Allocator<u32>,
275 AllocHC: alloc::Allocator<HuffmanCode>>
276{
277 pub state: BrotliRunningState,
278
279 pub loop_counter: i32,
281 pub br: BrotliBitReader,
282 pub alloc_u8: AllocU8,
283 pub alloc_u32: AllocU32,
284 pub alloc_hc: AllocHC,
285 pub buffer: [u8; 8],
287 pub buffer_length: u32,
288 pub pos: i32,
289 pub max_backward_distance: i32,
290 pub max_distance: i32,
291 pub ringbuffer_size: i32,
292 pub ringbuffer_mask: i32,
293 pub(crate) new_ringbuffer_size: i32,
297 pub(crate) u8_pool_size: usize,
303 pub(crate) initial_ringbuffer_size: u32,
306 pub(crate) one_shot_output_size: u32,
309 pub dist_rb_idx: i32,
310 pub dist_rb: [i32; 4],
311 pub ringbuffer: AllocU8::AllocatedMemory,
312 pub htree_command_index: u16,
314 pub context_lookup: &'static [u8;512],
315 pub context_map_slice_index: usize,
316 pub dist_context_map_slice_index: usize,
317
318 pub sub_loop_counter: u32,
319
320 pub literal_hgroup: HuffmanTreeGroup<AllocU32, AllocHC>,
323 pub insert_copy_hgroup: HuffmanTreeGroup<AllocU32, AllocHC>,
324 pub distance_hgroup: HuffmanTreeGroup<AllocU32, AllocHC>,
325 pub trivial_literal_context: i32,
328 pub distance_context: i32,
331 pub meta_block_remaining_len: i32,
332 pub block_type_length_state: BlockTypeAndLengthState<AllocHC>,
333 pub distance_postfix_bits: u32,
334 pub num_direct_distance_codes: u32,
335 pub distance_postfix_mask: i32,
336 pub num_dist_htrees: u32,
337 pub dist_context_map: AllocU8::AllocatedMemory,
338 pub literal_htree_index: u8,
340 pub dist_htree_index: u8,
341 pub large_window: bool,
342 pub(crate) canny_ringbuffer_allocation: bool,
343 pub should_wrap_ringbuffer: bool,
344 pub error_code: BrotliDecoderErrorCode,
345 pub repeat_code_len: u32,
346 pub prev_code_len: u32,
347
348 pub copy_length: i32,
349 pub distance_code: i32,
350
351 pub rb_roundtrips: u64, pub partial_pos_out: u64, pub symbol: u32,
359 pub repeat: u32,
360 pub space: u32,
361
362 pub table: [HuffmanCode; 32],
363 pub symbol_lists_index: usize, pub symbols_lists_array: [u16; BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1 +
367 BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE],
368 pub next_symbol: [i32; 32],
370 pub code_length_code_lengths: [u8; 18],
371 pub code_length_histo: [u16; 16],
373
374 pub htree_index: i32,
376 pub htree_next_offset: u32,
377
378 pub context_index: u32,
380 pub max_run_length_prefix: u32,
381 pub code: u32,
382 pub context_map_table: AllocHC::AllocatedMemory,
384
385 pub mtf_upper_bound: u32,
387 pub mtf_or_error_string: Result<[u8; 256], [u8; 256]>,
388
389 pub custom_dict: AllocU8::AllocatedMemory,
391 pub compound_dictionary: BrotliDecoderCompoundDictionary<AllocU8>,
392 pub dictionary: BrotliSharedDictionary<AllocU8, AllocU32>,
395 pub substate_metablock_header: BrotliRunningMetablockHeaderState,
398 pub substate_tree_group: BrotliRunningTreeGroupState,
399 pub substate_context_map: BrotliRunningContextMapState,
400 pub substate_uncompressed: BrotliRunningUncompressedState,
401 pub substate_huffman: BrotliRunningHuffmanState,
402 pub substate_decode_uint8: BrotliRunningDecodeUint8State,
403
404 pub is_last_metablock: u8,
405 pub is_uncompressed: u8,
406 pub is_metadata: u8,
407 pub size_nibbles: u8,
408 pub window_bits: u32,
409
410 pub num_literal_htrees: u32,
411 pub context_map: AllocU8::AllocatedMemory,
412 pub context_modes: AllocU8::AllocatedMemory,
413 pub trivial_literal_contexts: [u32; 8],
414}
415macro_rules! make_brotli_state {
416 ($alloc_u8 : expr, $alloc_u32 : expr, $alloc_hc : expr, $custom_dict : expr) => (BrotliState::<AllocU8, AllocU32, AllocHC>{
417 state : BrotliRunningState::BROTLI_STATE_UNINITED,
418 loop_counter : 0,
419 br : BrotliBitReader::default(),
420 alloc_u8 : $alloc_u8,
421 alloc_u32 : $alloc_u32,
422 alloc_hc : $alloc_hc,
423 buffer : [0u8; 8],
424 buffer_length : 0,
425 pos : 0,
426 max_backward_distance : 0,
427 max_distance : 0,
428 ringbuffer_size : 0,
429 ringbuffer_mask: 0,
430 new_ringbuffer_size : 0,
431 u8_pool_size : 0,
432 initial_ringbuffer_size : 0,
433 one_shot_output_size : 0,
434 dist_rb_idx : 0,
435 dist_rb : [16, 15, 11, 4],
436 ringbuffer : AllocU8::AllocatedMemory::default(),
437 htree_command_index : 0,
438 context_lookup : &kContextLookup[0],
439 context_map_slice_index : 0,
440 dist_context_map_slice_index : 0,
441 sub_loop_counter : 0,
442
443 literal_hgroup : HuffmanTreeGroup::<AllocU32, AllocHC>::default(),
444 insert_copy_hgroup : HuffmanTreeGroup::<AllocU32, AllocHC>::default(),
445 distance_hgroup : HuffmanTreeGroup::<AllocU32, AllocHC>::default(),
446 trivial_literal_context : 0,
447 distance_context : 0,
448 meta_block_remaining_len : 0,
449 block_type_length_state : BlockTypeAndLengthState::<AllocHC> {
450 block_length_index : 0,
451 block_length : [0; 3],
452 num_block_types : [0;3],
453 block_type_rb: [0;6],
454 substate_read_block_length : BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_NONE,
455 block_type_trees : AllocHC::AllocatedMemory::default(),
456 block_len_trees : AllocHC::AllocatedMemory::default(),
457 },
458 distance_postfix_bits : 0,
459 num_direct_distance_codes : 0,
460 distance_postfix_mask : 0,
461 num_dist_htrees : 0,
462 dist_context_map : AllocU8::AllocatedMemory::default(),
463 literal_htree_index : 0,
465 dist_htree_index : 0,
466 repeat_code_len : 0,
467 prev_code_len : 0,
468 copy_length : 0,
469 distance_code : 0,
470 rb_roundtrips : 0, partial_pos_out : 0, symbol : 0,
473 repeat : 0,
474 space : 0,
475 table : [HuffmanCode::default(); 32],
476 symbol_lists_index : BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1,
478 symbols_lists_array : [0;BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1 +
479 BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE],
480 next_symbol : [0; 32],
481 code_length_code_lengths : [0; 18],
482 code_length_histo : [0; 16],
483 htree_index : 0,
484 htree_next_offset : 0,
485
486 context_index : 0,
488 max_run_length_prefix : 0,
489 code : 0,
490 context_map_table : AllocHC::AllocatedMemory::default(),
491
492 mtf_upper_bound : 255,
494 mtf_or_error_string : Ok([0; 256]),
495
496 custom_dict : $custom_dict,
498 compound_dictionary : BrotliDecoderCompoundDictionary::default(),
499 dictionary : BrotliSharedDictionary::default(),
500 substate_metablock_header : BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE,
503 substate_tree_group : BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_NONE,
504 substate_context_map : BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_NONE,
505 substate_uncompressed : BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_NONE,
506 substate_huffman : BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_NONE,
507 substate_decode_uint8 : BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_NONE,
508
509 is_last_metablock : 0,
510 is_uncompressed : 0,
511 is_metadata : 0,
512 size_nibbles : 0,
513 window_bits : 0,
514 large_window: false,
515 canny_ringbuffer_allocation: true,
516 should_wrap_ringbuffer: false,
517 error_code: BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS,
518 num_literal_htrees : 0,
519 context_map : AllocU8::AllocatedMemory::default(),
520 context_modes : AllocU8::AllocatedMemory::default(),
521 trivial_literal_contexts : [0u32; 8],
522 }
523 );
524}
525impl <'brotli_state,
526 AllocU8 : alloc::Allocator<u8>,
527 AllocU32 : alloc::Allocator<u32>,
528 AllocHC : alloc::Allocator<HuffmanCode> > BrotliState<AllocU8, AllocU32, AllocHC> {
529 pub fn new(alloc_u8 : AllocU8,
530 alloc_u32 : AllocU32,
531 alloc_hc : AllocHC) -> Self{
532 let mut retval = make_brotli_state!(alloc_u8, alloc_u32, alloc_hc, AllocU8::AllocatedMemory::default());
533 retval.large_window = true;
534 BrotliInitBitReader(&mut retval.br);
535 retval
536 }
537 pub fn new_with_custom_dictionary(alloc_u8 : AllocU8,
538 alloc_u32 : AllocU32,
539 alloc_hc : AllocHC,
540 custom_dict: AllocU8::AllocatedMemory) -> Self{
541 let custom_dict_len = custom_dict.slice().len();
542 let mut retval = make_brotli_state!(alloc_u8, alloc_u32, alloc_hc, custom_dict);
543 retval.large_window = true;
544 BrotliInitBitReader(&mut retval.br);
545 if custom_dict_len != 0 && custom_dict_len <= SHARED_BROTLI_MAX_RAW_DICT_SIZE {
549 let dict = core::mem::replace(&mut retval.custom_dict,
550 AllocU8::AllocatedMemory::default());
551 let attached = retval.attach_compound_dictionary_chunk(MaybeOwnedSlice::Owned(dict));
555 debug_assert!(attached);
556 }
557 retval
558 }
559 pub fn new_strict(alloc_u8 : AllocU8,
560 alloc_u32 : AllocU32,
561 alloc_hc : AllocHC) -> Self{
562 let mut retval = make_brotli_state!(alloc_u8, alloc_u32, alloc_hc, AllocU8::AllocatedMemory::default());
563 retval.large_window = false;
564 BrotliInitBitReader(&mut retval.br);
565 retval
566 }
567 pub fn set_parameter(self : &mut Self,
573 param: BrotliDecoderParameter,
574 value: u32) -> bool {
575 match self.state {
576 BrotliRunningState::BROTLI_STATE_UNINITED => {},
577 _ => return false,
578 }
579 match param {
580 BrotliDecoderParameter::BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION =>
581 self.canny_ringbuffer_allocation = value == 0,
582 BrotliDecoderParameter::BROTLI_DECODER_PARAM_LARGE_WINDOW =>
583 self.large_window = value != 0,
584 }
585 true
586 }
587 pub fn set_initial_ring_buffer_size(self : &mut Self, size: u32) -> bool {
601 match self.state {
602 BrotliRunningState::BROTLI_STATE_UNINITED => {},
603 _ => return false,
604 }
605 self.initial_ringbuffer_size = size;
606 true
607 }
608 pub fn attach_dictionary(self : &mut Self,
615 dict: AllocU8::AllocatedMemory) -> bool {
616 self.attach_dictionary_chunk(MaybeOwnedSlice::Owned(dict))
617 }
618 pub fn attach_dictionary_borrowed(self : &mut Self, dict: &'static [u8]) -> bool {
627 self.attach_dictionary_chunk(MaybeOwnedSlice::Borrowed(dict))
628 }
629 pub fn attach_external_dictionary(self : &mut Self, size: usize) -> bool {
635 if self.external_dictionary_len() != 0 {
636 return false;
637 }
638 self.attach_dictionary_chunk(MaybeOwnedSlice::External(size))
639 }
640 pub(crate) fn external_dictionary_len(&self) -> usize {
642 let addon = &self.compound_dictionary;
643 for chunk in addon.chunks.iter().take(addon.num_chunks) {
644 if let MaybeOwnedSlice::External(len) = *chunk {
645 return len;
646 }
647 }
648 0
649 }
650 fn attach_dictionary_chunk(self : &mut Self,
651 dict: MaybeOwnedSlice<AllocU8>) -> bool {
652 match self.state {
653 BrotliRunningState::BROTLI_STATE_UNINITED => {},
654 _ => {
655 self.free_chunk(dict);
656 return false;
657 },
658 }
659 self.attach_compound_dictionary_chunk(dict)
660 }
661 pub fn attach_serialized_dictionary(self : &mut Self,
670 dict_data: AllocU8::AllocatedMemory) -> bool {
671 self.attach_serialized_dictionary_chunk(MaybeOwnedSlice::Owned(dict_data))
672 }
673 pub fn attach_serialized_dictionary_borrowed(self : &mut Self,
679 dict_data: &'static [u8]) -> bool {
680 self.attach_serialized_dictionary_chunk(MaybeOwnedSlice::Borrowed(dict_data))
681 }
682 fn attach_serialized_dictionary_chunk(self : &mut Self,
683 dict_data: MaybeOwnedSlice<AllocU8>) -> bool {
684 match self.state {
685 BrotliRunningState::BROTLI_STATE_UNINITED => {},
686 _ => {
687 self.free_chunk(dict_data);
688 return false;
689 },
690 }
691 let summary = match shared_dictionary::dry_parse_serialized_dictionary(
692 dict_data.slice()) {
693 Ok(summary) => summary,
694 Err(()) => {
695 self.free_chunk(dict_data);
696 return false;
697 },
698 };
699 let is_custom = summary.num_word_lists != 0 || summary.num_transform_lists != 0;
700 if is_custom && self.dictionary.is_custom() {
703 self.free_chunk(dict_data);
704 return false;
705 }
706 let borrowed_blob: Option<&'static [u8]> = match dict_data {
710 MaybeOwnedSlice::Borrowed(data) => Some(data),
711 MaybeOwnedSlice::Owned(_) | MaybeOwnedSlice::External(_) => None,
712 };
713 let mut parsed = BrotliSharedDictionary::<AllocU8, AllocU32>::default();
714 if is_custom {
715 let arena_size = summary.num_word_lists as usize * WORD_LIST_STRIDE +
716 summary.num_transform_lists as usize * TRANSFORM_LIST_STRIDE;
717 parsed.meta = self.alloc_u32.alloc_cell(arena_size);
718 if parsed.meta.slice().len() != arena_size ||
719 shared_dictionary::parse_serialized_dictionary_into(
720 dict_data.slice(), &summary, &mut parsed).is_err() {
721 self.alloc_u32.free_cell(core::mem::replace(&mut parsed.meta,
722 AllocU32::AllocatedMemory::default()));
723 self.free_chunk(dict_data);
724 return false;
725 }
726 }
727 if let Some((prefix_offset, prefix_len)) = summary.prefix {
728 let chunk = match borrowed_blob {
729 Some(blob) => MaybeOwnedSlice::Borrowed(
730 &blob[prefix_offset..prefix_offset + prefix_len]),
731 None => {
736 let mut chunk = self.alloc_u8.alloc_cell(prefix_len);
737 if chunk.slice().len() != prefix_len {
738 self.alloc_u8.free_cell(chunk);
739 self.alloc_u32.free_cell(core::mem::replace(&mut parsed.meta,
740 AllocU32::AllocatedMemory::default()));
741 self.free_chunk(dict_data);
742 return false;
743 }
744 chunk.slice_mut().clone_from_slice(
745 &dict_data.slice()[prefix_offset..prefix_offset + prefix_len]);
746 MaybeOwnedSlice::Owned(chunk)
747 },
748 };
749 if !self.attach_compound_dictionary_chunk(chunk) {
750 self.alloc_u32.free_cell(core::mem::replace(&mut parsed.meta,
751 AllocU32::AllocatedMemory::default()));
752 self.free_chunk(dict_data);
753 return false;
754 }
755 }
756 if is_custom {
757 parsed.blob = dict_data;
758 let old = core::mem::replace(&mut self.dictionary, parsed);
759 self.free_chunk(old.blob);
760 self.alloc_u32.free_cell(old.meta);
761 } else {
762 self.free_chunk(dict_data);
765 }
766 true
767 }
768 pub(crate) fn free_chunk(self : &mut Self, chunk: MaybeOwnedSlice<AllocU8>) {
775 if let MaybeOwnedSlice::Owned(mem) = chunk {
776 self.alloc_u8.free_cell(mem);
777 }
778 }
779 pub(crate) fn attach_compound_dictionary_chunk(self : &mut Self,
780 chunk: MaybeOwnedSlice<AllocU8>) -> bool {
781 let size = match chunk {
782 MaybeOwnedSlice::External(len) => len,
783 _ => chunk.slice().len(),
784 };
785 if size == 0 {
787 self.free_chunk(chunk);
788 return true;
789 }
790 let addon = &mut self.compound_dictionary;
791 if addon.num_chunks == SHARED_BROTLI_MAX_COMPOUND_DICTS ||
792 size > SHARED_BROTLI_MAX_RAW_DICT_SIZE - addon.total_size {
793 self.free_chunk(chunk);
794 return false;
795 }
796 addon.chunks[addon.num_chunks] = chunk;
797 addon.num_chunks += 1;
798 addon.total_size += size;
799 addon.chunk_offsets[addon.num_chunks] = addon.total_size as u32;
800 addon.block_bits = COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED;
802 true
803 }
804 pub fn BrotliStateMetablockBegin(self : &mut Self) {
805 self.meta_block_remaining_len = 0;
806 self.block_type_length_state.block_length[0] = 1u32 << 24;
807 self.block_type_length_state.block_length[1] = 1u32 << 24;
808 self.block_type_length_state.block_length[2] = 1u32 << 24;
809 self.block_type_length_state.num_block_types[0] = 1;
810 self.block_type_length_state.num_block_types[1] = 1;
811 self.block_type_length_state.num_block_types[2] = 1;
812 self.block_type_length_state.block_type_rb[0] = 1;
813 self.block_type_length_state.block_type_rb[1] = 0;
814 self.block_type_length_state.block_type_rb[2] = 1;
815 self.block_type_length_state.block_type_rb[3] = 0;
816 self.block_type_length_state.block_type_rb[4] = 1;
817 self.block_type_length_state.block_type_rb[5] = 0;
818 self.context_map_slice_index = 0;
819 self.literal_htree_index = 0;
820 self.dist_context_map_slice_index = 0;
821 self.dist_htree_index = 0;
822 self.context_lookup = &kContextLookup[0];
823 }
824 pub fn BrotliStateCleanupAfterMetablock(self : &mut Self) {
825 self.alloc_u8.free_cell(core::mem::replace(&mut self.context_map,
826 AllocU8::AllocatedMemory::default()));
827 self.alloc_u8.free_cell(core::mem::replace(&mut self.context_modes,
828 AllocU8::AllocatedMemory::default()));
829 self.alloc_u8.free_cell(core::mem::replace(&mut self.dist_context_map,
830 AllocU8::AllocatedMemory::default()));
831
832
833 self.literal_hgroup.reset(&mut self.alloc_u32, &mut self.alloc_hc);
834 self.insert_copy_hgroup.reset(&mut self.alloc_u32, &mut self.alloc_hc);
835 self.distance_hgroup.reset(&mut self.alloc_u32, &mut self.alloc_hc);
836 }
837
838 fn BrotliStateCleanup(self : &mut Self) {
839 self.BrotliStateCleanupAfterMetablock();
840 self.alloc_u8.free_cell(core::mem::replace(&mut self.ringbuffer,
841 AllocU8::AllocatedMemory::default()));
842 self.alloc_hc.free_cell(core::mem::replace(&mut self.block_type_length_state.block_type_trees,
843 AllocHC::AllocatedMemory::default()));
844 self.alloc_hc.free_cell(core::mem::replace(&mut self.block_type_length_state.block_len_trees,
845 AllocHC::AllocatedMemory::default()));
846 self.alloc_hc.free_cell(core::mem::replace(&mut self.context_map_table,
847 AllocHC::AllocatedMemory::default()));
848 self.alloc_u8.free_cell(core::mem::replace(&mut self.custom_dict,
849 AllocU8::AllocatedMemory::default()));
850 let num_chunks = self.compound_dictionary.num_chunks.min(self.compound_dictionary.chunks.len());
851 for chunk in self.compound_dictionary.chunks[..num_chunks].iter_mut() {
852 if let MaybeOwnedSlice::Owned(mem) =
853 core::mem::replace(chunk, MaybeOwnedSlice::default()) {
854 self.alloc_u8.free_cell(mem);
855 }
856 }
857 self.compound_dictionary.num_chunks = 0;
858 self.compound_dictionary.total_size = 0;
859 if let MaybeOwnedSlice::Owned(mem) =
860 core::mem::replace(&mut self.dictionary.blob, MaybeOwnedSlice::default()) {
861 self.alloc_u8.free_cell(mem);
862 }
863 self.alloc_u32.free_cell(core::mem::replace(&mut self.dictionary.meta,
864 AllocU32::AllocatedMemory::default()));
865
866 }
869
870 pub fn BrotliStateIsStreamStart(self : &Self) -> bool {
871 match self.state {
872 BrotliRunningState::BROTLI_STATE_UNINITED =>
873 BrotliGetAvailableBits(&self.br) == 0,
874 _ => false,
875 }
876 }
877
878 pub fn BrotliStateIsStreamEnd(self : &Self) -> bool {
879 match self.state {
880 BrotliRunningState::BROTLI_STATE_DONE => true,
881 _ => false
882 }
883 }
884 pub fn BrotliHuffmanTreeGroupInit(self :&mut Self, group : WhichTreeGroup,
885 alphabet_size : u16, max_symbol: u16, ntrees : u16) {
886 match group {
887 WhichTreeGroup::LITERAL => self.literal_hgroup.init(&mut self.alloc_u32,
888 &mut self.alloc_hc,
889 alphabet_size, max_symbol, ntrees),
890 WhichTreeGroup::INSERT_COPY => self.insert_copy_hgroup.init(&mut self.alloc_u32,
891 &mut self.alloc_hc,
892 alphabet_size, max_symbol, ntrees),
893 WhichTreeGroup::DISTANCE => self.distance_hgroup.init(&mut self.alloc_u32,
894 &mut self.alloc_hc,
895 alphabet_size, max_symbol, ntrees),
896 }
897 }
898 pub fn BrotliHuffmanTreeGroupRelease(self :&mut Self, group : WhichTreeGroup) {
899 match group {
900 WhichTreeGroup::LITERAL => self.literal_hgroup.reset(&mut self.alloc_u32,
901 &mut self.alloc_hc),
902 WhichTreeGroup::INSERT_COPY => self.insert_copy_hgroup.reset(&mut self.alloc_u32,
903 &mut self.alloc_hc),
904 WhichTreeGroup::DISTANCE => self.distance_hgroup.reset(&mut self.alloc_u32,
905 &mut self.alloc_hc),
906 }
907 }
908}
909
910impl <'brotli_state,
911 AllocU8 : alloc::Allocator<u8>,
912 AllocU32 : alloc::Allocator<u32>,
913 AllocHC : alloc::Allocator<HuffmanCode> > Drop for BrotliState<AllocU8, AllocU32, AllocHC> {
914 fn drop(&mut self) {
915 self.BrotliStateCleanup();
916 }
917}
918
919
920
921pub fn BrotliDecoderErrorStr(c: BrotliDecoderErrorCode) -> &'static str {
922 match c {
923 BrotliDecoderErrorCode::BROTLI_DECODER_NO_ERROR => "NO_ERROR\0",
924 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => "SUCCESS\0",
926 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT => "NEEDS_MORE_INPUT\0",
927 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT => "NEEDS_MORE_OUTPUT\0",
928
929 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE => "ERROR_FORMAT_EXUBERANT_NIBBLE\0",
931 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_RESERVED => "ERROR_FORMAT_RESERVED\0",
932 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE => "ERROR_FORMAT_EXUBERANT_META_NIBBLE\0",
933 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET => "ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET\0",
934 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME => "ERROR_FORMAT_SIMPLE_HUFFMAN_SAME\0",
935 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_CL_SPACE => "ERROR_FORMAT_FL_SPACE\0",
936 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => "ERROR_FORMAT_HUFFMAN_SPACE\0",
937 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT => "ERROR_FORMAT_CONTEXT_MAP_REPEAT\0",
938 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1 =>"ERROR_FORMAT_BLOCK_LENGTH_1\0",
939 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2 =>"ERROR_FORMAT_BLOCK_LENGTH_2\0",
940 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM => "ERROR_FORMAT_TRANSFORM\0",
941 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DICTIONARY =>"ERROR_FORMAT_DICTIONARY\0",
942 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS =>"ERROR_FORMAT_WINDOW_BITS\0",
943 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_1 =>"ERROR_FORMAT_PADDING_1\0",
944 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_2 =>"ERROR_FORMAT_PADDING_2\0",
945 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE =>"ERROR_FORMAT_DISTANCE\0",
946 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH =>"ERROR_FORMAT_BLOCK_SWITCH\0",
947
948 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY => "ERROR_COMPOUND_DICTIONARY\0",
949 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET => "ERROR_DICTIONARY_NOT_SET\0",
950 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS => "ERROR_INVALID_ARGUMENTS\0",
951
952 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES => "ERROR_ALLOC_CONTEXT_MODES\0",
954 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS => "ERROR_ALLOC_TREE_GROUPS\0",
956 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP => "ERROR_ALLOC_CONTEXT_MAP\0",
958 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1 => "ERROR_ALLOC_RING_BUFFER_1\0",
959 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2 => "ERROR_ALLOC_RING_BUFFER_2\0",
960 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES => "ERROR_ALLOC_BLOCK_TYPE_TREES\0",
962
963 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => "ERROR_UNREACHABLE\0",
965 }
966}