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