1#![allow(non_snake_case)]
2#![allow(unused_parens)]
3#![allow(non_camel_case_types)]
4#![allow(non_snake_case)]
5#![allow(non_upper_case_globals)]
6#![allow(unused_macros)]
7
8use core;
11use super::alloc;
12pub use alloc::{AllocatedStackMemory, Allocator, SliceWrapper, SliceWrapperMut, StackAllocator};
13
14use core::mem;
15
16use super::bit_reader;
17use super::huffman;
18use super::state;
19use super::prefix;
20
21use super::transform::{TransformDictionaryWord, kNumTransforms};
22use state::{BlockTypeAndLengthState, BrotliRunningContextMapState, BrotliRunningDecodeUint8State,
23 BrotliRunningHuffmanState, BrotliRunningMetablockHeaderState,
24 BrotliRunningReadBlockLengthState, BrotliRunningState, BrotliRunningTreeGroupState,
25 BrotliRunningUncompressedState, kLiteralContextBits,
26 BrotliDecoderErrorCode,
27};
28use context::{kContextLookup};
29use ::dictionary::{kBrotliDictionary, kBrotliDictionaryOffsetsByLength,
30 kBrotliDictionarySizeBitsByLength, kBrotliMaxDictionaryWordLength,
31 kBrotliMinDictionaryWordLength};
32pub use huffman::{HuffmanCode, HuffmanTreeGroup};
33#[repr(C)]
34#[derive(Debug)]
35pub enum BrotliResult {
36 ResultSuccess = 1,
37 NeedsMoreInput = 2,
38 NeedsMoreOutput = 3,
39 ResultFailure = 0,
40}
41const kBrotliWindowGap: u32 = 16;
42const kBrotliLargeMinWbits: u32 = 10;
43const kBrotliLargeMaxWbits: u32 = 30;
44const kBrotliMaxPostfix: usize = 3;
45const kBrotliMaxAllowedDistance: u32 = 0x7FFFFFFC;
46const kDefaultCodeLength: u32 = 8;
47const kCodeLengthRepeatCode: u32 = 16;
48pub const kNumLiteralCodes: u16 = 256;
49pub const kNumInsertAndCopyCodes: u16 = 704;
50pub const kNumBlockLengthCodes: u32 = 26;
51const kDistanceContextBits: i32 = 2;
52const HUFFMAN_TABLE_BITS: u32 = 8;
53const HUFFMAN_TABLE_MASK: u32 = 0xff;
54const CODE_LENGTH_CODES: usize = 18;
55const kCodeLengthCodeOrder: [u8; CODE_LENGTH_CODES] = [1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10,
56 11, 12, 13, 14, 15];
57
58const kCodeLengthPrefixLength: [u8; 16] = [2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4];
60
61const kCodeLengthPrefixValue: [u8; 16] = [0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5];
62
63
64macro_rules! BROTLI_LOG_UINT (
65 ($num : expr) => {
66 xprintln!("{:?} = {:?}", stringify!($num), $num)
67 };
68);
69
70macro_rules! BROTLI_LOG (
71 ($str : expr, $num : expr) => {xprintln!("{:?} {:?}", $str, $num);};
72 ($str : expr, $num0 : expr, $num1 : expr) => {xprintln!("{:?} {:?} {:?}", $str, $num0, $num1);};
73 ($str : expr, $num0 : expr, $num1 : expr, $num2 : expr) => {
74 xprintln!("{:?} {:?} {:?} {:?}", $str, $num0, $num1, $num2);
75 };
76 ($str : expr, $num0 : expr, $num1 : expr, $num2 : expr, $num3 : expr) => {
77 xprintln!("{:?} {:?} {:?} {:?} {:?}", $str, $num0, $num1, $num2, $num3);
78 };
79);
80fn is_fatal(e: BrotliDecoderErrorCode) -> bool {
81 (e as i64) < 0
82}
83fn assign_error_code(output: &mut BrotliDecoderErrorCode, input: BrotliDecoderErrorCode) -> BrotliDecoderErrorCode {
84 *output = input;
85 input
86}
87
88#[allow(non_snake_case)]
89macro_rules! SaveErrorCode {
90 ($state: expr, $e:expr) => {
91 match assign_error_code(&mut $state.error_code, $e) {
92 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS =>
93 BrotliResult::ResultSuccess,
94 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT =>
95 BrotliResult::NeedsMoreInput,
96 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT =>
97 BrotliResult::NeedsMoreOutput,
98 _ =>
99 BrotliResult::ResultFailure,
100 }
101 }
102}
103macro_rules! SaveResult {
104 ($state: expr, $e:expr) => {
105 match ($state.error_code = match $e {
106 BrotliResult::ResultSuccess => BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS,
107 BrotliResult::NeedsMoreInput => BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT,
108 BrotliResult::NeedsMoreOutput => BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT,
109 BrotliResult::ResultFailure => BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE,
110 }) {
111 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS =>
112 BrotliResult::ResultSuccess,
113 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT =>
114 BrotliResult::NeedsMoreInput,
115 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT =>
116 BrotliResult::NeedsMoreOutput,
117 _ =>
118 BrotliResult::ResultFailure,
119 }
120 }
121}
122macro_rules! BROTLI_LOG_ARRAY_INDEX (
123 ($array : expr, $index : expr) => {
124 xprintln!("{:?}[{:?}] = {:?}", stringify!($array), $index, $array[$index as usize])
125 };
126);
127
128
129const NUM_DISTANCE_SHORT_CODES: u32 = 16;
130pub const BROTLI_MAX_DISTANCE_BITS:u32 = 24;
131
132pub const BROTLI_LARGE_MAX_DISTANCE_BITS: u32 = 62;
133
134pub fn BROTLI_DISTANCE_ALPHABET_SIZE(NPOSTFIX: u32, NDIRECT:u32, MAXNBITS: u32) -> u32 {
135 NUM_DISTANCE_SHORT_CODES + (NDIRECT) +
136 ((MAXNBITS) << ((NPOSTFIX) + 1))
137}
138
139pub use state::BrotliState;
144fn DecodeWindowBits(s_large_window: &mut bool,
153 s_window_bits:&mut u32,
154 br: &mut bit_reader::BrotliBitReader) -> BrotliDecoderErrorCode {
155 let mut n: u32 = 0;
156 let large_window = *s_large_window;
157 *s_large_window = false;
158 bit_reader::BrotliTakeBits(br, 1, &mut n);
159 if (n == 0) {
160 *s_window_bits = 16;
161 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
162 }
163 bit_reader::BrotliTakeBits(br, 3, &mut n);
164 if (n != 0) {
165 *s_window_bits = 17 + n;
166 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
167 }
168 bit_reader::BrotliTakeBits(br, 3, &mut n);
169 if (n == 1) {
170 if (large_window) {
171 bit_reader::BrotliTakeBits(br, 1, &mut n);
172 if (n == 1) {
173 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
174 }
175 *s_large_window = true;
176 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
177 } else {
178 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
179 }
180 }
181 if (n != 0) {
182 *s_window_bits = 8 + n;
183 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
184 }
185 *s_window_bits = 17;
186 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
187}
188
189
190#[cold]
191fn mark_unlikely() {}
192
193fn DecodeVarLenUint8(substate_decode_uint8: &mut state::BrotliRunningDecodeUint8State,
194 mut br: &mut bit_reader::BrotliBitReader,
195 value: &mut u32,
196 input: &[u8])
197 -> BrotliDecoderErrorCode {
198 let mut bits: u32 = 0;
199 loop {
200 match *substate_decode_uint8 {
201 BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_NONE => {
202 if !bit_reader::BrotliSafeReadBits(&mut br, 1, &mut bits, input) {
203 mark_unlikely();
204 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
205 }
206 if (bits == 0) {
207 *value = 0;
208 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
209 }
210 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_SHORT;
211 }
213 BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_SHORT => {
214 if !bit_reader::BrotliSafeReadBits(&mut br, 3, &mut bits, input) {
215 mark_unlikely();
216 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_SHORT;
217 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
218 }
219 if (bits == 0) {
220 *value = 1;
221 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_NONE;
222 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
223 }
224 *value = bits;
226 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_LONG;
228 }
229 BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_LONG => {
230 if !bit_reader::BrotliSafeReadBits(&mut br, *value, &mut bits, input) {
231 mark_unlikely();
232 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_LONG;
233 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
234 }
235 *value = (1u32 << *value) + bits;
236 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_NONE;
237 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
238 }
239 }
240 }
241}
242
243fn DecodeMetaBlockLength<AllocU8: alloc::Allocator<u8>,
244 AllocU32: alloc::Allocator<u32>,
245 AllocHC: alloc::Allocator<HuffmanCode>>
246 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
247 input: &[u8])
248 -> BrotliDecoderErrorCode {
249 let mut bits: u32 = 0;
250 loop {
251 match s.substate_metablock_header {
252 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE => {
253 if !bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input) {
254 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
255 }
256 s.is_last_metablock = bits as u8;
257 s.meta_block_remaining_len = 0;
258 s.is_uncompressed = 0;
259 s.is_metadata = 0;
260 if (s.is_last_metablock == 0) {
261 s.substate_metablock_header =
262 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
263 continue;
264 }
265 s.substate_metablock_header =
266 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_EMPTY;
267 }
269 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_EMPTY => {
270 if !bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input) {
271 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
272 }
273 if bits != 0 {
274 s.substate_metablock_header =
275 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE;
276 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
277 }
278 s.substate_metablock_header =
279 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
280 }
282 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NIBBLES => {
283 if !bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut bits, input) {
284 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
285 }
286 s.size_nibbles = (bits + 4) as u8;
287 s.loop_counter = 0;
288 if (bits == 3) {
289 s.is_metadata = 1;
290 s.substate_metablock_header =
291 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_RESERVED;
292 continue;
293 }
294 s.substate_metablock_header =
295 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_SIZE;
296 }
299 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_SIZE => {
300 let mut i = s.loop_counter;
301 while i < s.size_nibbles as i32 {
302 if !bit_reader::BrotliSafeReadBits(&mut s.br, 4, &mut bits, input) {
303 s.loop_counter = i;
304 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
305 }
306 if (i + 1 == s.size_nibbles as i32 && s.size_nibbles > 4 && bits == 0) {
307 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE;
308 }
309 s.meta_block_remaining_len |= (bits << (i * 4)) as i32;
310 i += 1;
311 }
312 s.substate_metablock_header =
313 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED;
314 }
316 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED => {
317 if (s.is_last_metablock == 0 && s.is_metadata == 0) {
318 if !bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input) {
319 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
320 }
321 s.is_uncompressed = bits as u8;
322 }
323 s.meta_block_remaining_len += 1;
324 s.substate_metablock_header =
325 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE;
326 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
327 }
328 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_RESERVED => {
329 if !bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input) {
330 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
331 }
332 if (bits != 0) {
333 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_RESERVED;
334 }
335 s.substate_metablock_header =
336 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_BYTES;
337 }
339 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_BYTES => {
340 if !bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut bits, input) {
341 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
342 }
343 if (bits == 0) {
344 s.substate_metablock_header =
345 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE;
346 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
347 }
348 s.size_nibbles = bits as u8;
349 s.substate_metablock_header =
350 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_METADATA;
351 }
353 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_METADATA => {
354 let mut i = s.loop_counter;
355 while i < s.size_nibbles as i32 {
356 if !bit_reader::BrotliSafeReadBits(&mut s.br, 8, &mut bits, input) {
357 s.loop_counter = i;
358 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
359 }
360 if (i + 1 == s.size_nibbles as i32 && s.size_nibbles > 1 && bits == 0) {
361 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE;
362 }
363 s.meta_block_remaining_len |= (bits << (i * 8)) as i32;
364 i += 1;
365 }
366 s.substate_metablock_header =
367 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED;
368 continue;
369 }
370 }
371 }
372}
373#[inline(always)]
378fn DecodeSymbol(bits: u32, table: &[HuffmanCode], br: &mut bit_reader::BrotliBitReader) -> u32 {
379 let mut table_index = bits & HUFFMAN_TABLE_MASK;
380 let mut table_element = fast!((table)[table_index as usize]);
381 if table_element.bits > HUFFMAN_TABLE_BITS as u8 {
382 let nbits = table_element.bits - HUFFMAN_TABLE_BITS as u8;
383 bit_reader::BrotliDropBits(br, HUFFMAN_TABLE_BITS);
384 table_index += table_element.value as u32;
385 table_element = fast!((table)[(table_index
386 + ((bits >> HUFFMAN_TABLE_BITS)
387 & bit_reader::BitMask(nbits as u32))) as usize]);
388 }
389 bit_reader::BrotliDropBits(br, table_element.bits as u32);
390 table_element.value as u32
391}
392
393#[inline(always)]
396fn ReadSymbol(table: &[HuffmanCode], br: &mut bit_reader::BrotliBitReader, input: &[u8]) -> u32 {
397 DecodeSymbol(bit_reader::BrotliGet16BitsUnmasked(br, input), table, br)
398}
399
400fn SafeDecodeSymbol(table: &[HuffmanCode],
403 mut br: &mut bit_reader::BrotliBitReader,
404 result: &mut u32)
405 -> bool {
406 let mut available_bits = bit_reader::BrotliGetAvailableBits(br);
407 if (available_bits == 0) {
408 if (fast!((table)[0]).bits == 0) {
409 *result = fast!((table)[0]).value as u32;
410 return true;
411 }
412 return false; }
414 let mut val = bit_reader::BrotliGetBitsUnmasked(br) as u32;
415 let table_index = (val & HUFFMAN_TABLE_MASK) as usize;
416 let table_element = fast!((table)[table_index]);
417 if (table_element.bits <= HUFFMAN_TABLE_BITS as u8) {
418 if (table_element.bits as u32 <= available_bits) {
419 bit_reader::BrotliDropBits(&mut br, table_element.bits as u32);
420 *result = table_element.value as u32;
421 return true;
422 } else {
423 return false; }
425 }
426 if (available_bits <= HUFFMAN_TABLE_BITS) {
427 return false; }
429
430 val = (val & bit_reader::BitMask(table_element.bits as u32)) >> HUFFMAN_TABLE_BITS;
432 available_bits -= HUFFMAN_TABLE_BITS;
433 let table_sub_element = fast!((table)[table_index + table_element.value as usize + val as usize]);
434 if (available_bits < table_sub_element.bits as u32) {
435 return false; }
437
438 bit_reader::BrotliDropBits(&mut br, HUFFMAN_TABLE_BITS + table_sub_element.bits as u32);
439 *result = table_sub_element.value as u32;
440 true
441}
442
443fn SafeReadSymbol(table: &[HuffmanCode],
444 br: &mut bit_reader::BrotliBitReader,
445 result: &mut u32,
446 input: &[u8])
447 -> bool {
448 let mut val: u32 = 0;
449 if (bit_reader::BrotliSafeGetBits(br, 15, &mut val, input)) {
450 *result = DecodeSymbol(val, table, br);
451 return true;
452 } else {
453 mark_unlikely();
454 }
455 SafeDecodeSymbol(table, br, result)
456}
457
458fn PreloadSymbol(safe: bool,
460 table: &[HuffmanCode],
461 br: &mut bit_reader::BrotliBitReader,
462 bits: &mut u32,
463 value: &mut u32,
464 input: &[u8]) {
465 if (safe) {
466 return;
467 }
468 let table_element =
469 fast!((table)[bit_reader::BrotliGetBits(br, HUFFMAN_TABLE_BITS, input) as usize]);
470 *bits = table_element.bits as u32;
471 *value = table_element.value as u32;
472}
473
474fn ReadPreloadedSymbol(table: &[HuffmanCode],
477 br: &mut bit_reader::BrotliBitReader,
478 bits: &mut u32,
479 value: &mut u32,
480 input: &[u8])
481 -> u32 {
482 let result = if *bits > HUFFMAN_TABLE_BITS {
483 mark_unlikely();
484 let val = bit_reader::BrotliGet16BitsUnmasked(br, input);
485 let mut ext_index = (val & HUFFMAN_TABLE_MASK) + *value;
486 let mask = bit_reader::BitMask((*bits - HUFFMAN_TABLE_BITS));
487 bit_reader::BrotliDropBits(br, HUFFMAN_TABLE_BITS);
488 ext_index += (val >> HUFFMAN_TABLE_BITS) & mask;
489 let ext = fast!((table)[ext_index as usize]);
490 bit_reader::BrotliDropBits(br, ext.bits as u32);
491 ext.value as u32
492 } else {
493 bit_reader::BrotliDropBits(br, *bits);
494 *value
495 };
496 PreloadSymbol(false, table, br, bits, value, input);
497 result
498}
499
500fn Log2Floor(mut x: u32) -> u32 {
501 let mut result: u32 = 0;
502 while x != 0 {
503 x >>= 1;
504 result += 1;
505 }
506 result
507}
508
509
510fn ReadSimpleHuffmanSymbols<AllocU8: alloc::Allocator<u8>,
515 AllocU32: alloc::Allocator<u32>,
516 AllocHC: alloc::Allocator<HuffmanCode>>
517 (alphabet_size: u32, max_symbol: u32,
518 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
519 input: &[u8])
520 -> BrotliDecoderErrorCode {
521
522 let max_bits = Log2Floor(alphabet_size - 1);
524 let mut i = s.sub_loop_counter;
525 let num_symbols = s.symbol;
526 for symbols_lists_item in fast_mut!((s.symbols_lists_array)[s.sub_loop_counter as usize;
527 num_symbols as usize + 1])
528 .iter_mut() {
529 let mut v: u32 = 0;
530 if !bit_reader::BrotliSafeReadBits(&mut s.br, max_bits, &mut v, input) {
531 mark_unlikely();
532 s.sub_loop_counter = i;
533 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_READ;
534 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
535 }
536 if (v >= max_symbol) {
537 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET;
538 }
539 *symbols_lists_item = v as u16;
540 BROTLI_LOG_UINT!(v);
541 i += 1;
542 }
543 i = 0;
544 for symbols_list_item in fast!((s.symbols_lists_array)[0; num_symbols as usize]).iter() {
545 for other_item in fast!((s.symbols_lists_array)[i as usize + 1 ; num_symbols as usize+ 1])
546 .iter() {
547 if (*symbols_list_item == *other_item) {
548 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME;
549 }
550 }
551 i += 1;
552 }
553 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
554}
555
556fn ProcessSingleCodeLength(code_len: u32,
564 symbol: &mut u32,
565 repeat: &mut u32,
566 space: &mut u32,
567 prev_code_len: &mut u32,
568 symbol_lists: &mut [u16],
569 symbol_list_index_offset: usize,
570 code_length_histo: &mut [u16],
571 next_symbol: &mut [i32]) {
572 *repeat = 0;
573 if (code_len != 0) {
574 fast_mut!((symbol_lists)[(symbol_list_index_offset as i32 +
577 fast_inner!((next_symbol)[code_len as usize])) as usize]) =
578 (*symbol) as u16;
579 fast_mut!((next_symbol)[code_len as usize]) = (*symbol) as i32;
580 *prev_code_len = code_len;
581 *space = space.wrapping_sub(32768 >> code_len);
582 fast_mut!((code_length_histo)[code_len as usize]) += 1;
583 BROTLI_LOG!("[ReadHuffmanCode] code_length[{:}]={:} histo[]={:}\n",
584 *symbol, code_len, code_length_histo[code_len as usize]);
585 }
586 (*symbol) += 1;
587}
588
589fn ProcessRepeatedCodeLength(code_len: u32,
599 mut repeat_delta: u32,
600 alphabet_size: u32,
601 symbol: &mut u32,
602 repeat: &mut u32,
603 space: &mut u32,
604 prev_code_len: &mut u32,
605 repeat_code_len: &mut u32,
606 symbol_lists: &mut [u16],
607 symbol_lists_index: usize,
608 code_length_histo: &mut [u16],
609 next_symbol: &mut [i32]) {
610 let old_repeat: u32;
611 let extra_bits: u32;
612 let new_len: u32;
613 if (code_len == kCodeLengthRepeatCode) {
614 extra_bits = 2;
615 new_len = *prev_code_len
616 } else {
617 extra_bits = 3;
618 new_len = 0
619 }
620 if (*repeat_code_len != new_len) {
621 *repeat = 0;
622 *repeat_code_len = new_len;
623 }
624 old_repeat = *repeat;
625 if (*repeat > 0) {
626 *repeat -= 2;
627 *repeat <<= extra_bits;
628 }
629 *repeat += repeat_delta + 3;
630 repeat_delta = *repeat - old_repeat;
631 if (*symbol + repeat_delta > alphabet_size) {
632 *symbol = alphabet_size;
633 *space = 0xFFFFF;
634 return;
635 }
636 BROTLI_LOG!("[ReadHuffmanCode] code_length[{:}..{:}] = {:}\n",
637 *symbol, *symbol + repeat_delta - 1, *repeat_code_len);
638 if (*repeat_code_len != 0) {
639 let last: u32 = *symbol + repeat_delta;
640 let mut next: i32 = fast!((next_symbol)[*repeat_code_len as usize]);
641 loop {
642 fast_mut!((symbol_lists)[(symbol_lists_index as i32 + next) as usize]) = (*symbol) as u16;
643 next = (*symbol) as i32;
644 (*symbol) += 1;
645 if *symbol == last {
646 break;
647 }
648 }
649 fast_mut!((next_symbol)[*repeat_code_len as usize]) = next;
650 *space = space.wrapping_sub(repeat_delta << (15 - *repeat_code_len));
651 fast_mut!((code_length_histo)[*repeat_code_len as usize]) =
652 (fast!((code_length_histo)[*repeat_code_len as usize]) as u32 + repeat_delta) as u16;
653 } else {
654 *symbol += repeat_delta;
655 }
656}
657
658fn ReadSymbolCodeLengths<AllocU8: alloc::Allocator<u8>,
660 AllocU32: alloc::Allocator<u32>,
661 AllocHC: alloc::Allocator<HuffmanCode>>
662 (alphabet_size: u32,
663 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
664 input: &[u8])
665 -> BrotliDecoderErrorCode {
666
667 let mut symbol = s.symbol;
668 let mut repeat = s.repeat;
669 let mut space = s.space;
670 let mut prev_code_len: u32 = s.prev_code_len;
671 let mut repeat_code_len: u32 = s.repeat_code_len;
672 if (!bit_reader::BrotliWarmupBitReader(&mut s.br, input)) {
673 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
674 }
675 while (symbol < alphabet_size && space > 0) {
676 let mut p_index = 0;
677 let code_len: u32;
678 if (!bit_reader::BrotliCheckInputAmount(&s.br, bit_reader::BROTLI_SHORT_FILL_BIT_WINDOW_READ)) {
679 s.symbol = symbol;
680 s.repeat = repeat;
681 s.prev_code_len = prev_code_len;
682 s.repeat_code_len = repeat_code_len;
683 s.space = space;
684 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
685 }
686 bit_reader::BrotliFillBitWindow16(&mut s.br, input);
687 p_index +=
688 bit_reader::BrotliGetBitsUnmasked(&s.br) &
689 bit_reader::BitMask(huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH as u32) as u64;
690 let p = fast!((s.table)[p_index as usize]);
691 bit_reader::BrotliDropBits(&mut s.br, p.bits as u32); code_len = p.value as u32; if (code_len < kCodeLengthRepeatCode) {
694 ProcessSingleCodeLength(code_len,
695 &mut symbol,
696 &mut repeat,
697 &mut space,
698 &mut prev_code_len,
699 &mut s.symbols_lists_array,
700 s.symbol_lists_index as usize,
701 &mut s.code_length_histo[..],
702 &mut s.next_symbol[..]);
703 } else {
704 let extra_bits: u32 = if code_len == kCodeLengthRepeatCode {
706 2
707 } else {
708 3
709 };
710 let repeat_delta: u32 = bit_reader::BrotliGetBitsUnmasked(&s.br) as u32 &
711 bit_reader::BitMask(extra_bits);
712 bit_reader::BrotliDropBits(&mut s.br, extra_bits);
713 ProcessRepeatedCodeLength(code_len,
714 repeat_delta,
715 alphabet_size,
716 &mut symbol,
717 &mut repeat,
718 &mut space,
719 &mut prev_code_len,
720 &mut repeat_code_len,
721 &mut s.symbols_lists_array,
722 s.symbol_lists_index as usize,
723 &mut s.code_length_histo[..],
724 &mut s.next_symbol[..]);
725 }
726 }
727 s.space = space;
728 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
729}
730
731fn SafeReadSymbolCodeLengths<AllocU8: alloc::Allocator<u8>,
732 AllocU32: alloc::Allocator<u32>,
733 AllocHC: alloc::Allocator<HuffmanCode>>
734 (alphabet_size: u32,
735 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
736 input: &[u8])
737 -> BrotliDecoderErrorCode {
738 while (s.symbol < alphabet_size && s.space > 0) {
739 let mut p_index = 0;
740 let code_len: u32;
741 let mut bits: u32 = 0;
742 let available_bits: u32 = bit_reader::BrotliGetAvailableBits(&s.br);
743 if (available_bits != 0) {
744 bits = bit_reader::BrotliGetBitsUnmasked(&s.br) as u32;
745 }
746 p_index += bits &
747 bit_reader::BitMask(huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH as u32);
748 let p = fast!((s.table)[p_index as usize]);
749 if (p.bits as u32 > available_bits) {
750 if (!bit_reader::BrotliPullByte(&mut s.br, input)) {
752 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
753 }
754 continue;
755 }
756 code_len = p.value as u32; if (code_len < kCodeLengthRepeatCode) {
758 bit_reader::BrotliDropBits(&mut s.br, p.bits as u32);
759 ProcessSingleCodeLength(code_len,
760 &mut s.symbol,
761 &mut s.repeat,
762 &mut s.space,
763 &mut s.prev_code_len,
764 &mut s.symbols_lists_array,
765 s.symbol_lists_index as usize,
766 &mut s.code_length_histo[..],
767 &mut s.next_symbol[..]);
768 } else {
769 let extra_bits: u32 = code_len - 14;
771 let repeat_delta: u32 = (bits >> p.bits) & bit_reader::BitMask(extra_bits);
772 if (available_bits < p.bits as u32 + extra_bits) {
773 if (!bit_reader::BrotliPullByte(&mut s.br, input)) {
775 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
776 }
777 continue;
778 }
779 bit_reader::BrotliDropBits(&mut s.br, p.bits as u32 + extra_bits);
780 ProcessRepeatedCodeLength(code_len,
781 repeat_delta,
782 alphabet_size,
783 &mut s.symbol,
784 &mut s.repeat,
785 &mut s.space,
786 &mut s.prev_code_len,
787 &mut s.repeat_code_len,
788 &mut s.symbols_lists_array,
789 s.symbol_lists_index as usize,
790 &mut s.code_length_histo[..],
791 &mut s.next_symbol[..]);
792 }
793 }
794 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
795}
796
797fn ReadCodeLengthCodeLengths<AllocU8: alloc::Allocator<u8>,
800 AllocU32: alloc::Allocator<u32>,
801 AllocHC: alloc::Allocator<HuffmanCode>>
802 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
803 input: &[u8])
804 -> BrotliDecoderErrorCode {
805
806 let mut num_codes: u32 = s.repeat;
807 let mut space: u32 = s.space;
808 let mut i = s.sub_loop_counter;
809 for code_length_code_order in
810 fast!((kCodeLengthCodeOrder)[s.sub_loop_counter as usize; CODE_LENGTH_CODES]).iter() {
811 let code_len_idx = *code_length_code_order;
812 let mut ix: u32 = 0;
813
814 if !bit_reader::BrotliSafeGetBits(&mut s.br, 4, &mut ix, input) {
815 mark_unlikely();
816 let available_bits: u32 = bit_reader::BrotliGetAvailableBits(&s.br);
817 if (available_bits != 0) {
818 ix = bit_reader::BrotliGetBitsUnmasked(&s.br) as u32 & 0xF;
819 } else {
820 ix = 0;
821 }
822 if (fast!((kCodeLengthPrefixLength)[ix as usize]) as u32 > available_bits) {
823 s.sub_loop_counter = i;
824 s.repeat = num_codes;
825 s.space = space;
826 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_COMPLEX;
827 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
828 }
829 }
830 BROTLI_LOG_UINT!(ix);
831 let v: u32 = fast!((kCodeLengthPrefixValue)[ix as usize]) as u32;
832 bit_reader::BrotliDropBits(&mut s.br,
833 fast!((kCodeLengthPrefixLength)[ix as usize]) as u32);
834 fast_mut!((s.code_length_code_lengths)[code_len_idx as usize]) = v as u8;
835 BROTLI_LOG_ARRAY_INDEX!(s.code_length_code_lengths, code_len_idx);
836 if v != 0 {
837 space = space.wrapping_sub(32 >> v);
838 num_codes += 1;
839 fast_mut!((s.code_length_histo)[v as usize]) += 1;
840 if space.wrapping_sub(1) >= 32 {
841 break;
843 }
844 }
845 i += 1;
846 }
847 if (!(num_codes == 1 || space == 0)) {
848 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_CL_SPACE;
849 }
850 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
851}
852
853
854fn ReadHuffmanCode<AllocU8: alloc::Allocator<u8>,
867 AllocU32: alloc::Allocator<u32>,
868 AllocHC: alloc::Allocator<HuffmanCode>>
869 (mut alphabet_size: u32,
870 max_symbol: u32,
871 table: &mut [HuffmanCode],
872 offset: usize,
873 opt_table_size: Option<&mut u32>,
874 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
875 input: &[u8])
876 -> BrotliDecoderErrorCode {
877 alphabet_size &= 0x7ff;
879 loop {
881 match s.substate_huffman {
882 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_NONE => {
883 if !bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut s.sub_loop_counter, input) {
884 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
885 }
886
887 BROTLI_LOG_UINT!(s.sub_loop_counter);
888 if (s.sub_loop_counter != 1) {
892 s.space = 32;
893 s.repeat = 0; let max_code_len_len = huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH as usize + 1;
895 for code_length_histo in fast_mut!((s.code_length_histo)[0;max_code_len_len]).iter_mut() {
896 *code_length_histo = 0; }
898 for code_length_code_length in s.code_length_code_lengths[..].iter_mut() {
899 *code_length_code_length = 0;
900 }
901 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_COMPLEX;
902 continue;
904 }
905 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
906 }
908 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_SIZE => {
909 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut s.symbol, input)) {
911 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
913 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
914 }
915 s.sub_loop_counter = 0;
916 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_READ;
918 }
919 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_READ => {
920 let result = ReadSimpleHuffmanSymbols(alphabet_size, max_symbol, s, input);
921 match result {
922 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
923 _ => return result,
924 }
925 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
927 }
928 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_BUILD => {
929 let table_size: u32;
930 if (s.symbol == 3) {
931 let mut bits: u32 = 0;
932 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input)) {
933 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
934 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
935 }
936 s.symbol += bits;
937 }
938 BROTLI_LOG_UINT!(s.symbol);
939 table_size = huffman::BrotliBuildSimpleHuffmanTable(&mut table[offset..],
940 HUFFMAN_TABLE_BITS as i32,
941 &s.symbols_lists_array[..],
942 s.symbol);
943 if let Some(opt_table_size_ref) = opt_table_size {
944 *opt_table_size_ref = table_size
945 }
946 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_NONE;
947 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
948 }
949
950 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_COMPLEX => {
952
953 let result = ReadCodeLengthCodeLengths(s, input);
954 match result {
955 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
956 _ => return result,
957 }
958 huffman::BrotliBuildCodeLengthsHuffmanTable(&mut s.table,
959 &s.code_length_code_lengths,
960 &s.code_length_histo);
961 for code_length_histo in s.code_length_histo[..].iter_mut() {
962 *code_length_histo = 0; }
964
965 let max_code_length = huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH as usize + 1;
966 for (i, next_symbol_mut) in fast_mut!((s.next_symbol)[0; max_code_length])
967 .iter_mut()
968 .enumerate() {
969 *next_symbol_mut = i as i32 - (max_code_length as i32);
970 fast_mut!((s.symbols_lists_array)[(s.symbol_lists_index as i32
971 + i as i32
972 - (max_code_length as i32)) as usize]) = 0xFFFF;
973 }
974
975 s.symbol = 0;
976 s.prev_code_len = kDefaultCodeLength;
977 s.repeat = 0;
978 s.repeat_code_len = 0;
979 s.space = 32768;
980 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
982 }
983 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS => {
984 let table_size: u32;
985 let mut result = ReadSymbolCodeLengths(max_symbol, s, input);
986 if let BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT = result {
987 result = SafeReadSymbolCodeLengths(max_symbol, s, input)
988 }
989 match result {
990 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
991 _ => return result,
992 }
993
994 if (s.space != 0) {
995 BROTLI_LOG!("[ReadHuffmanCode] space = %d\n", s.space);
996 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE;
997 }
998 table_size = huffman::BrotliBuildHuffmanTable(fast_mut!((table)[offset;]),
999 HUFFMAN_TABLE_BITS as i32,
1000 &s.symbols_lists_array[..],
1001 s.symbol_lists_index,
1002 &mut s.code_length_histo);
1003 if let Some(opt_table_size_ref) = opt_table_size {
1004 *opt_table_size_ref = table_size
1005 }
1006 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_NONE;
1007 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1008 }
1009 }
1010 }
1011}
1012
1013fn ReadBlockLength(table: &[HuffmanCode],
1015 br: &mut bit_reader::BrotliBitReader,
1016 input: &[u8])
1017 -> u32 {
1018 let code: u32;
1019 let nbits: u32;
1020 code = ReadSymbol(table, br, input);
1021 nbits = fast_ref!((prefix::kBlockLengthPrefixCode)[code as usize]).nbits as u32; fast_ref!((prefix::kBlockLengthPrefixCode)[code as usize]).offset as u32 +
1023 bit_reader::BrotliReadBits(br, nbits, input)
1024}
1025
1026
1027fn SafeReadBlockLengthIndex(substate_read_block_length: &state::BrotliRunningReadBlockLengthState,
1030 block_length_index: u32,
1031 table: &[HuffmanCode],
1032 mut br: &mut bit_reader::BrotliBitReader,
1033 input: &[u8])
1034 -> (bool, u32) {
1035 match *substate_read_block_length {
1036 state::BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_NONE => {
1037 let mut index: u32 = 0;
1038 if (!SafeReadSymbol(table, &mut br, &mut index, input)) {
1039 return (false, 0);
1040 }
1041 (true, index)
1042 }
1043 _ => (true, block_length_index),
1044 }
1045}
1046fn SafeReadBlockLengthFromIndex<
1047 AllocHC : alloc::Allocator<HuffmanCode> >(s : &mut BlockTypeAndLengthState<AllocHC>,
1048 br : &mut bit_reader::BrotliBitReader,
1049 result : &mut u32,
1050 res_index : (bool, u32),
1051 input : &[u8]) -> bool{
1052 let (res, index) = res_index;
1053 if !res {
1054 return false;
1055 }
1056 let mut bits: u32 = 0;
1057 let nbits = fast_ref!((prefix::kBlockLengthPrefixCode)[index as usize]).nbits; if (!bit_reader::BrotliSafeReadBits(br, nbits as u32, &mut bits, input)) {
1059 s.block_length_index = index;
1060 s.substate_read_block_length =
1061 state::BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX;
1062 return false;
1063 }
1064 *result = fast_ref!((prefix::kBlockLengthPrefixCode)[index as usize]).offset as u32 + bits;
1065 s.substate_read_block_length =
1066 state::BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
1067 true
1068}
1069macro_rules! SafeReadBlockLength (
1070 ($state : expr, $result : expr , $table : expr) => {
1071 SafeReadBlockLengthFromIndex(&mut $state, &mut $result,
1072 SafeReadBlockLengthIndex($state.substate_read_block_length,
1073 $state.block_length_index,
1074 $table,
1075 &mut $state.br))
1076 };
1077);
1078
1079fn InverseMoveToFrontTransform(v: &mut [u8],
1095 v_len: u32,
1096 mtf: &mut [u8;256],
1097 mtf_upper_bound: &mut u32) {
1098 let mut upper_bound: u32 = *mtf_upper_bound;
1100 for (i, item) in fast_mut!((mtf)[0;(upper_bound as usize + 1usize)]).iter_mut().enumerate() {
1101 *item = i as u8;
1102 }
1103
1104 upper_bound = 0;
1106 for v_i in fast_mut!((v)[0usize ; (v_len as usize)]).iter_mut() {
1107 let mut index = (*v_i) as i32;
1108 let value = fast!((mtf)[index as usize]);
1109 upper_bound |= (*v_i) as u32;
1110 *v_i = value;
1111 if index <= 0 {
1112 fast_mut!((mtf)[0]) = 0;
1113 } else {
1114 loop {
1115 index -= 1;
1116 fast_mut!((mtf)[(index + 1) as usize]) = fast!((mtf)[index as usize]);
1117 if index <= 0 {
1118 break;
1119 }
1120 }
1121 }
1122 fast_mut!((mtf)[0]) = value;
1123 }
1124 *mtf_upper_bound = upper_bound;
1126}
1127fn HuffmanTreeGroupDecode<AllocU8: alloc::Allocator<u8>,
1129 AllocU32: alloc::Allocator<u32>,
1130 AllocHC: alloc::Allocator<HuffmanCode>>
1131 (group_index: i32,
1132 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1133 input: &[u8])
1134 -> BrotliDecoderErrorCode {
1135 let mut hcodes: AllocHC::AllocatedMemory;
1136 let mut htrees: AllocU32::AllocatedMemory;
1137 let alphabet_size: u16;
1138 let group_num_htrees: u16;
1139 let group_max_symbol;
1140 if group_index == 0 {
1141 hcodes = mem::replace(&mut s.literal_hgroup.codes,
1142 AllocHC::AllocatedMemory::default());
1143 htrees = mem::replace(&mut s.literal_hgroup.htrees,
1144 AllocU32::AllocatedMemory::default());
1145 group_num_htrees = s.literal_hgroup.num_htrees;
1146 alphabet_size = s.literal_hgroup.alphabet_size;
1147 group_max_symbol = s.literal_hgroup.max_symbol;
1148 } else if group_index == 1 {
1149 hcodes = mem::replace(&mut s.insert_copy_hgroup.codes,
1150 AllocHC::AllocatedMemory::default());
1151 htrees = mem::replace(&mut s.insert_copy_hgroup.htrees,
1152 AllocU32::AllocatedMemory::default());
1153 group_num_htrees = s.insert_copy_hgroup.num_htrees;
1154 alphabet_size = s.insert_copy_hgroup.alphabet_size;
1155 group_max_symbol = s.insert_copy_hgroup.max_symbol;
1156 } else {
1157 if group_index != 2 {
1158 let ret = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
1159 SaveErrorCode!(s, ret);
1160 return ret;
1161 }
1162 hcodes = mem::replace(&mut s.distance_hgroup.codes,
1163 AllocHC::AllocatedMemory::default());
1164 htrees = mem::replace(&mut s.distance_hgroup.htrees,
1165 AllocU32::AllocatedMemory::default());
1166 group_num_htrees = s.distance_hgroup.num_htrees;
1167 alphabet_size = s.distance_hgroup.alphabet_size;
1168 group_max_symbol = s.distance_hgroup.max_symbol;
1169 }
1170 match s.substate_tree_group {
1171 BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_NONE => {
1172 s.htree_next_offset = 0;
1173 s.htree_index = 0;
1174 s.substate_tree_group = BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_LOOP;
1175 }
1176 BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_LOOP => {}
1177 }
1178 let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1179 for htree_iter in
1180 fast_mut!((htrees.slice_mut())[s.htree_index as usize ; (group_num_htrees as usize)])
1181 .iter_mut() {
1182 let mut table_size: u32 = 0;
1183 result = ReadHuffmanCode(u32::from(alphabet_size), u32::from(group_max_symbol),
1184 hcodes.slice_mut(),
1185 s.htree_next_offset as usize,
1186 Some(&mut table_size),
1187 &mut s,
1188 input);
1189 match result {
1190 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1191 _ => break, }
1193 *htree_iter = s.htree_next_offset;
1194 s.htree_next_offset += table_size;
1195 s.htree_index += 1;
1196 }
1197 if group_index == 0 {
1198 let _ = mem::replace(&mut s.literal_hgroup.codes,
1199 mem::replace(&mut hcodes, AllocHC::AllocatedMemory::default()));
1200 let _ = mem::replace(&mut s.literal_hgroup.htrees,
1201 mem::replace(&mut htrees, AllocU32::AllocatedMemory::default()));
1202 } else if group_index == 1 {
1203 let _ = mem::replace(&mut s.insert_copy_hgroup.codes,
1204 mem::replace(&mut hcodes, AllocHC::AllocatedMemory::default()));
1205 let _ = mem::replace(&mut s.insert_copy_hgroup.htrees,
1206 mem::replace(&mut htrees, AllocU32::AllocatedMemory::default()));
1207 } else {
1208 let _ = mem::replace(&mut s.distance_hgroup.codes,
1209 mem::replace(&mut hcodes, AllocHC::AllocatedMemory::default()));
1210 let _ = mem::replace(&mut s.distance_hgroup.htrees,
1211 mem::replace(&mut htrees, AllocU32::AllocatedMemory::default()));
1212 }
1213 if let BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS = result {
1214 s.substate_tree_group = BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_NONE
1215 }
1216 result
1217}
1218#[allow(dead_code)]
1219pub fn lg_window_size(first_byte: u8, second_byte: u8) -> Result<(u8, u8), ()> {
1220 if first_byte & 1 == 0 {
1221 return Ok((16, 1));
1222 }
1223 match first_byte & 15 {
1224 0x3 => return Ok((18, 4)),
1225 0x5 => return Ok((19, 4)),
1226 0x7 => return Ok((20, 4)),
1227 0x9 => return Ok((21, 4)),
1228 0xb => return Ok((22, 4)),
1229 0xd => return Ok((23, 4)),
1230 0xf => return Ok((24, 4)),
1231 _ => match first_byte & 127 {
1232 0x71 => return Ok((15, 7)),
1233 0x61 => return Ok((14, 7)),
1234 0x51 => return Ok((13, 7)),
1235 0x41 => return Ok((12, 7)),
1236 0x31 => return Ok((11, 7)),
1237 0x21 => return Ok((10, 7)),
1238 0x1 => return Ok((17, 7)),
1239 _ => {},
1240 }
1241 }
1242 if (first_byte & 0x80) != 0 {
1243 return Err(());
1244 }
1245 let ret = second_byte & 0x3f;
1246 if ret < 10 || ret > 30 {
1247 return Err(());
1248 }
1249 Ok((ret, 14))
1250
1251}
1252
1253
1254fn bzero(data: &mut [u8]) {
1255 for iter in data.iter_mut() {
1256 *iter = 0;
1257 }
1258}
1259
1260
1261fn DecodeContextMapInner<AllocU8: alloc::Allocator<u8>,
1271 AllocU32: alloc::Allocator<u32>,
1272 AllocHC: alloc::Allocator<HuffmanCode>>
1273 (context_map_size: u32,
1274 num_htrees: &mut u32,
1275 context_map_arg: &mut AllocU8::AllocatedMemory,
1276 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1277 input: &[u8])
1278 -> BrotliDecoderErrorCode {
1279
1280 let mut result;
1281 loop {
1282 match s.substate_context_map {
1283 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_NONE => {
1284 result = DecodeVarLenUint8(&mut s.substate_decode_uint8, &mut s.br, num_htrees, input);
1285 match result {
1286 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1287 _ => return result,
1288 }
1289 (*num_htrees) += 1;
1290 s.context_index = 0;
1291 BROTLI_LOG_UINT!(context_map_size);
1292 BROTLI_LOG_UINT!(*num_htrees);
1293 *context_map_arg = s.alloc_u8.alloc_cell(context_map_size as usize);
1294 if (context_map_arg.slice().len() < context_map_size as usize) {
1295 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP;
1296 }
1297 if (*num_htrees <= 1) {
1298 bzero(context_map_arg.slice_mut()); return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1301 }
1302 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_READ_PREFIX;
1303 }
1305 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_READ_PREFIX => {
1306 let mut bits: u32 = 0;
1307 if (!bit_reader::BrotliSafeGetBits(&mut s.br, 5, &mut bits, input)) {
1310 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1311 }
1312 if ((bits & 1) != 0) {
1313 s.max_run_length_prefix = (bits >> 1) + 1;
1315 bit_reader::BrotliDropBits(&mut s.br, 5);
1316 } else {
1317 s.max_run_length_prefix = 0;
1318 bit_reader::BrotliDropBits(&mut s.br, 1);
1319 }
1320 BROTLI_LOG_UINT!(s.max_run_length_prefix);
1321 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_HUFFMAN;
1322 }
1324 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_HUFFMAN => {
1325
1326 let mut local_context_map_table = mem::replace(&mut s.context_map_table,
1327 AllocHC::AllocatedMemory::default());
1328 let alphabet_size = *num_htrees + s.max_run_length_prefix;
1329 result = ReadHuffmanCode(alphabet_size, alphabet_size,
1330 &mut local_context_map_table.slice_mut(),
1331 0,
1332 None,
1333 &mut s,
1334 input);
1335 let _ = mem::replace(&mut s.context_map_table,
1336 mem::replace(&mut local_context_map_table,
1337 AllocHC::AllocatedMemory::default()));
1338 match result {
1339 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1340 _ => return result,
1341 }
1342 s.code = 0xFFFF;
1343 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_DECODE;
1344 }
1346 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_DECODE => {
1347 let mut context_index: u32 = s.context_index;
1348 let max_run_length_prefix: u32 = s.max_run_length_prefix;
1349 let context_map = &mut context_map_arg.slice_mut();
1350 let mut code: u32 = s.code;
1351 let mut rleCodeGoto = (code != 0xFFFF);
1352 while (rleCodeGoto || context_index < context_map_size) {
1353 if !rleCodeGoto {
1354 if (!SafeReadSymbol(s.context_map_table.slice(), &mut s.br, &mut code, input)) {
1355 s.code = 0xFFFF;
1356 s.context_index = context_index;
1357 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1358 }
1359 BROTLI_LOG_UINT!(code);
1360
1361 if code == 0 {
1362 fast_mut!((context_map)[context_index as usize]) = 0;
1363 BROTLI_LOG_ARRAY_INDEX!(context_map, context_index as usize);
1364 context_index += 1;
1365 continue;
1366 }
1367 if code > max_run_length_prefix {
1368 fast_mut!((context_map)[context_index as usize]) =
1369 (code - max_run_length_prefix) as u8;
1370 BROTLI_LOG_ARRAY_INDEX!(context_map, context_index as usize);
1371 context_index += 1;
1372 continue;
1373 }
1374 }
1375 rleCodeGoto = false; {
1378 let mut reps: u32 = 0;
1379 if (!bit_reader::BrotliSafeReadBits(&mut s.br, code, &mut reps, input)) {
1380 s.code = code;
1381 s.context_index = context_index;
1382 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1383 }
1384 reps += 1u32 << code;
1385 BROTLI_LOG_UINT!(reps);
1386 if (context_index + reps > context_map_size) {
1387 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT;
1388 }
1389 loop {
1390 fast_mut!((context_map)[context_index as usize]) = 0;
1391 BROTLI_LOG_ARRAY_INDEX!(context_map, context_index as usize);
1392 context_index += 1;
1393 reps -= 1;
1394 if reps == 0 {
1395 break;
1396 }
1397 }
1398 }
1399 }
1400 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
1402 }
1403 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_TRANSFORM => {
1404 let mut bits: u32 = 0;
1405 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input)) {
1406 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
1407 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1408 }
1409 if (bits != 0) {
1410 if let Ok(ref mut mtf) = s.mtf_or_error_string {
1411 InverseMoveToFrontTransform(context_map_arg.slice_mut(),
1412 context_map_size,
1413 mtf,
1414 &mut s.mtf_upper_bound);
1415 } else {
1416 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
1418 }
1419 }
1420 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_NONE;
1421 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1422 }
1423 }
1424 }
1425 }
1427
1428fn DecodeContextMap<AllocU8: alloc::Allocator<u8>,
1429 AllocU32: alloc::Allocator<u32>,
1430 AllocHC: alloc::Allocator<HuffmanCode>>
1431 (context_map_size: usize,
1432 is_dist_context_map: bool,
1433 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1434 input: &[u8])
1435 -> BrotliDecoderErrorCode {
1436
1437 match s.state {
1438 BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1 => assert_eq!(is_dist_context_map, false),
1439 BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2 => assert_eq!(is_dist_context_map, true),
1440 _ => unreachable!(),
1441 }
1442 let (mut num_htrees, mut context_map_arg) = if is_dist_context_map {
1443 (s.num_dist_htrees, mem::replace(&mut s.dist_context_map, AllocU8::AllocatedMemory::default()))
1444 } else {
1445 (s.num_literal_htrees, mem::replace(&mut s.context_map, AllocU8::AllocatedMemory::default()))
1446 };
1447
1448 let retval = DecodeContextMapInner(context_map_size as u32,
1449 &mut num_htrees,
1450 &mut context_map_arg,
1451 &mut s,
1452 input);
1453 if is_dist_context_map {
1454 s.num_dist_htrees = num_htrees;
1455 let _ = mem::replace(&mut s.dist_context_map,
1456 mem::replace(&mut context_map_arg, AllocU8::AllocatedMemory::default()));
1457 } else {
1458 s.num_literal_htrees = num_htrees;
1459 let _ = mem::replace(&mut s.context_map,
1460 mem::replace(&mut context_map_arg, AllocU8::AllocatedMemory::default()));
1461 }
1462 retval
1463}
1464
1465fn DecodeBlockTypeAndLength<
1468 AllocHC : alloc::Allocator<HuffmanCode>> (safe : bool,
1469 s : &mut BlockTypeAndLengthState<AllocHC>,
1470 br : &mut bit_reader::BrotliBitReader,
1471 tree_type : i32,
1472 input : &[u8]) -> bool {
1473 let max_block_type = fast!((s.num_block_types)[tree_type as usize]);
1474 let tree_offset = tree_type as usize * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as usize;
1475
1476 let mut block_type: u32 = 0;
1477 if max_block_type <= 1 {
1478 return false;
1479 }
1480 if (!safe) {
1482 block_type = ReadSymbol(fast_slice!((s.block_type_trees)[tree_offset;]), br, input);
1483 fast_mut!((s.block_length)[tree_type as usize]) =
1484 ReadBlockLength(fast_slice!((s.block_len_trees)[tree_offset;]), br, input);
1485 } else {
1486 let memento = bit_reader::BrotliBitReaderSaveState(br);
1487 if (!SafeReadSymbol(fast_slice!((s.block_type_trees)[tree_offset;]),
1488 br,
1489 &mut block_type,
1490 input)) {
1491 return false;
1492 }
1493 let mut block_length_out: u32 = 0;
1494
1495 let index_ret = SafeReadBlockLengthIndex(&s.substate_read_block_length,
1496 s.block_length_index,
1497 fast_slice!((s.block_len_trees)[tree_offset;]),
1498 br,
1499 input);
1500 if !SafeReadBlockLengthFromIndex(s, br, &mut block_length_out, index_ret, input) {
1501 s.substate_read_block_length =
1502 BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
1503 bit_reader::BrotliBitReaderRestoreState(br, &memento);
1504 return false;
1505 }
1506 fast_mut!((s.block_length)[tree_type as usize]) = block_length_out;
1507 }
1508 let ringbuffer: &mut [u32] = &mut fast_mut!((s.block_type_rb)[tree_type as usize * 2;]);
1509 if (block_type == 1) {
1510 block_type = fast!((ringbuffer)[1]) + 1;
1511 } else if (block_type == 0) {
1512 block_type = fast!((ringbuffer)[0]);
1513 } else {
1514 block_type -= 2;
1515 }
1516 if (block_type >= max_block_type) {
1517 block_type -= max_block_type;
1518 }
1519 fast_mut!((ringbuffer)[0]) = fast!((ringbuffer)[1]);
1520 fast_mut!((ringbuffer)[1]) = block_type;
1521 true
1522}
1523fn DetectTrivialLiteralBlockTypes<AllocU8: alloc::Allocator<u8>,
1524 AllocU32: alloc::Allocator<u32>,
1525 AllocHC: alloc::Allocator<HuffmanCode>>
1526 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>) {
1527 for iter in s.trivial_literal_contexts.iter_mut() {
1528 *iter = 0;
1529 }
1530 let mut i: usize = 0;
1531 while i < fast!((s.block_type_length_state.num_block_types)[0]) as usize {
1532 let offset = (i as usize) << kLiteralContextBits;
1533 let mut error = 0usize;
1534 let sample: usize = fast_slice!((s.context_map)[offset]) as usize;
1535 let mut j = 0usize;
1536 while j < ((1 as usize) << kLiteralContextBits) {
1537 error |= fast_slice!((s.context_map)[offset + j]) as usize ^ sample;
1538 j += 1;
1539 error |= fast_slice!((s.context_map)[offset + j]) as usize ^ sample;
1540 j += 1;
1541 error |= fast_slice!((s.context_map)[offset + j]) as usize ^ sample;
1542 j += 1;
1543 error |= fast_slice!((s.context_map)[offset + j]) as usize ^ sample;
1544 j += 1
1545 }
1546 if error == 0 {
1547 s.trivial_literal_contexts[i >> 5] |= ((1 as u32) << (i & 31));
1548 }
1549 i += 1
1550 }
1551}
1552fn PrepareLiteralDecoding<AllocU8: alloc::Allocator<u8>,
1553 AllocU32: alloc::Allocator<u32>,
1554 AllocHC: alloc::Allocator<HuffmanCode>>
1555 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>) {
1556
1557 let context_offset: u32;
1558 let block_type = fast!((s.block_type_length_state.block_type_rb)[1]) as usize;
1559 context_offset = (block_type << kLiteralContextBits) as u32;
1560 s.context_map_slice_index = context_offset as usize;
1561 let trivial = fast!((s.trivial_literal_contexts)[block_type >> 5]);
1562 s.trivial_literal_context = ((trivial >> (block_type & 31)) & 1) as i32;
1563
1564 s.literal_htree_index = fast_slice!((s.context_map)[s.context_map_slice_index]);
1565 let context_mode_index = fast!((s.context_modes.slice())[block_type]) & 3;
1567 s.context_lookup = &kContextLookup[context_mode_index as usize];
1568}
1569
1570fn DecodeLiteralBlockSwitchInternal<AllocU8: alloc::Allocator<u8>,
1574 AllocU32: alloc::Allocator<u32>,
1575 AllocHC: alloc::Allocator<HuffmanCode>>
1576 (safe: bool,
1577 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1578 input: &[u8])
1579 -> bool {
1580
1581 if !DecodeBlockTypeAndLength(safe, &mut s.block_type_length_state, &mut s.br, 0, input) {
1582 return false;
1583 }
1584 PrepareLiteralDecoding(s);
1585 true
1586}
1587fn DecodeCommandBlockSwitchInternal<AllocU8: alloc::Allocator<u8>,
1608 AllocU32: alloc::Allocator<u32>,
1609 AllocHC: alloc::Allocator<HuffmanCode>>
1610 (safe: bool,
1611 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1612 input: &[u8])
1613 -> bool {
1614 if (!DecodeBlockTypeAndLength(safe, &mut s.block_type_length_state, &mut s.br, 1, input)) {
1615 return false;
1616 }
1617 s.htree_command_index = fast!((s.block_type_length_state.block_type_rb)[3]) as u16;
1618 true
1619}
1620
1621#[allow(dead_code)]
1622fn DecodeCommandBlockSwitch<AllocU8: alloc::Allocator<u8>,
1623 AllocU32: alloc::Allocator<u32>,
1624 AllocHC: alloc::Allocator<HuffmanCode>>
1625 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1626 input: &[u8]) {
1627 DecodeCommandBlockSwitchInternal(false, s, input);
1628}
1629#[allow(dead_code)]
1630fn SafeDecodeCommandBlockSwitch<AllocU8: alloc::Allocator<u8>,
1631 AllocU32: alloc::Allocator<u32>,
1632 AllocHC: alloc::Allocator<HuffmanCode>>
1633 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1634 input: &[u8])
1635 -> bool {
1636 DecodeCommandBlockSwitchInternal(true, s, input)
1637}
1638
1639fn DecodeDistanceBlockSwitchInternal<AllocU8: alloc::Allocator<u8>,
1642 AllocU32: alloc::Allocator<u32>,
1643 AllocHC: alloc::Allocator<HuffmanCode>>
1644 (safe: bool,
1645 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1646 input: &[u8])
1647 -> bool {
1648 if (!DecodeBlockTypeAndLength(safe, &mut s.block_type_length_state, &mut s.br, 2, input)) {
1649 return false;
1650 }
1651 s.dist_context_map_slice_index =
1652 (fast!((s.block_type_length_state.block_type_rb)[5]) << kDistanceContextBits) as usize;
1653 s.dist_htree_index = fast_slice!((s.dist_context_map)[s.dist_context_map_slice_index
1654 + s.distance_context as usize]);
1655 true
1656}
1657
1658#[allow(dead_code)]
1659fn DecodeDistanceBlockSwitch<AllocU8: alloc::Allocator<u8>,
1660 AllocU32: alloc::Allocator<u32>,
1661 AllocHC: alloc::Allocator<HuffmanCode>>
1662 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1663 input: &[u8]) {
1664 DecodeDistanceBlockSwitchInternal(false, s, input);
1665}
1666
1667#[allow(dead_code)]
1668fn SafeDecodeDistanceBlockSwitch<AllocU8: alloc::Allocator<u8>,
1669 AllocU32: alloc::Allocator<u32>,
1670 AllocHC: alloc::Allocator<HuffmanCode>>
1671 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1672 input: &[u8])
1673 -> bool {
1674 DecodeDistanceBlockSwitchInternal(true, s, input)
1675}
1676
1677fn UnwrittenBytes<AllocU8: alloc::Allocator<u8>,
1678 AllocU32: alloc::Allocator<u32>,
1679 AllocHC: alloc::Allocator<HuffmanCode>> (
1680 s: &BrotliState<AllocU8, AllocU32, AllocHC>,
1681 wrap: bool,
1682) -> usize {
1683 let pos = if wrap && s.pos > s.ringbuffer_size {
1684 s.ringbuffer_size as usize
1685 } else {
1686 s.pos as usize
1687 };
1688 let partial_pos_rb = (s.rb_roundtrips as usize * s.ringbuffer_size as usize) + pos as usize;
1689 (partial_pos_rb - s.partial_pos_out) as usize
1690}
1691fn WriteRingBuffer<'a,
1692 AllocU8: alloc::Allocator<u8>,
1693 AllocU32: alloc::Allocator<u32>,
1694 AllocHC: alloc::Allocator<HuffmanCode>>(
1695 available_out: &mut usize,
1696 opt_output: Option<&mut [u8]>,
1697 output_offset: &mut usize,
1698 total_out: &mut usize,
1699 force: bool,
1700 s: &'a mut BrotliState<AllocU8, AllocU32, AllocHC>,
1701) -> (BrotliDecoderErrorCode, &'a [u8]) {
1702 let to_write = UnwrittenBytes(s, true);
1703 let mut num_written = *available_out as usize;
1704 if (num_written > to_write) {
1705 num_written = to_write;
1706 }
1707 if (s.meta_block_remaining_len < 0) {
1708 return (BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1, &[]);
1709 }
1710 let start_index = (s.partial_pos_out & s.ringbuffer_mask as usize) as usize;
1711 let start = fast_slice!((s.ringbuffer)[start_index ; start_index + num_written as usize]);
1712 if let Some(output) = opt_output {
1713 fast_mut!((output)[*output_offset ; *output_offset + num_written as usize])
1714 .clone_from_slice(start);
1715 }
1716 *output_offset += num_written;
1717 *available_out -= num_written;
1718 BROTLI_LOG_UINT!(to_write);
1719 BROTLI_LOG_UINT!(num_written);
1720 s.partial_pos_out += num_written as usize;
1721 *total_out = s.partial_pos_out;
1722 if (num_written < to_write) {
1723 if s.ringbuffer_size == (1 << s.window_bits) || force {
1724 return (BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT, &[]);
1725 } else {
1726 return (BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS, start);
1727 }
1728 }
1729 if (s.ringbuffer_size == (1 << s.window_bits) &&
1730 s.pos >= s.ringbuffer_size) {
1731 s.pos -= s.ringbuffer_size;
1732 s.rb_roundtrips += 1;
1733 s.should_wrap_ringbuffer = s.pos != 0;
1734 }
1735 (BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS, start)
1736 }
1737
1738fn WrapRingBuffer<AllocU8: alloc::Allocator<u8>,
1739 AllocU32: alloc::Allocator<u32>,
1740 AllocHC: alloc::Allocator<HuffmanCode>>(
1741 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1742) {
1743 if s.should_wrap_ringbuffer {
1744 let (ring_buffer_start, ring_buffer_end) = s.ringbuffer.slice_mut().split_at_mut(s.ringbuffer_size as usize);
1745 let pos = s.pos as usize;
1746 ring_buffer_start.split_at_mut(pos).0.clone_from_slice(ring_buffer_end.split_at(pos).0);
1747 s.should_wrap_ringbuffer = false;
1748 }
1749
1750}
1751
1752fn CopyUncompressedBlockToOutput<AllocU8: alloc::Allocator<u8>,
1753 AllocU32: alloc::Allocator<u32>,
1754 AllocHC: alloc::Allocator<HuffmanCode>>
1755 (mut available_out: &mut usize,
1756 mut output: &mut [u8],
1757 mut output_offset: &mut usize,
1758 mut total_out: &mut usize,
1759 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1760 input: &[u8])
1761 -> BrotliDecoderErrorCode {
1762 loop {
1764 match s.substate_uncompressed {
1765 BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_NONE => {
1766 let mut nbytes = bit_reader::BrotliGetRemainingBytes(&s.br) as i32;
1767 if (nbytes > s.meta_block_remaining_len) {
1768 nbytes = s.meta_block_remaining_len;
1769 }
1770 if (s.pos + nbytes > s.ringbuffer_size) {
1771 nbytes = s.ringbuffer_size - s.pos;
1772 }
1773 bit_reader::BrotliCopyBytes(fast_mut!((s.ringbuffer.slice_mut())[s.pos as usize;]),
1775 &mut s.br,
1776 nbytes as u32,
1777 input);
1778 s.pos += nbytes;
1779 s.meta_block_remaining_len -= nbytes;
1780 if s.pos < (1 << s.window_bits) {
1781 if (s.meta_block_remaining_len == 0) {
1782 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1783 }
1784 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1785 }
1786 s.substate_uncompressed = BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_WRITE;
1787 }
1790 BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_WRITE => {
1791 let (result, _) = WriteRingBuffer(&mut available_out,
1792 Some(&mut output),
1793 &mut output_offset,
1794 &mut total_out,
1795 false,
1796 &mut s);
1797 match result {
1798 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1799 _ => return result,
1800 }
1801 if s.ringbuffer_size == 1 << s.window_bits {
1802 s.max_distance = s.max_backward_distance;
1803 }
1804 s.substate_uncompressed = BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_NONE;
1805 }
1806 }
1807 }
1808}
1809
1810fn BrotliAllocateRingBuffer<AllocU8: alloc::Allocator<u8>,
1811 AllocU32: alloc::Allocator<u32>,
1812 AllocHC: alloc::Allocator<HuffmanCode>>
1813 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1814 input: &[u8])
1815 -> bool {
1816 const kRingBufferWriteAheadSlack: i32 = 42;
1820 let mut is_last = s.is_last_metablock;
1821 s.ringbuffer_size = 1 << s.window_bits;
1822
1823 if (s.is_uncompressed != 0) {
1824 let next_block_header =
1825 bit_reader::BrotliPeekByte(&mut s.br, s.meta_block_remaining_len as u32, input);
1826 if (next_block_header != -1) &&
1827 ((next_block_header & 3) == 3) {
1829 is_last = 1;
1831 }
1832 }
1833 let max_dict_size = s.ringbuffer_size as usize - 16;
1834 {
1835 let custom_dict = if s.custom_dict_size as usize > max_dict_size {
1836 let cd = fast_slice!((s.custom_dict)[(s.custom_dict_size as usize - max_dict_size); s.custom_dict_size as usize]);
1837 s.custom_dict_size = max_dict_size as i32;
1838 cd
1839 } else {
1840 fast_slice!((s.custom_dict)[0; s.custom_dict_size as usize])
1841 };
1842
1843 if (is_last != 0) {
1846 while (s.ringbuffer_size >= (s.custom_dict_size + s.meta_block_remaining_len) * 2 && s.ringbuffer_size > 32) {
1847 s.ringbuffer_size >>= 1;
1848 }
1849 }
1850 if s.ringbuffer_size > (1 << s.window_bits) {
1851 s.ringbuffer_size = (1 << s.window_bits);
1852 }
1853
1854 s.ringbuffer_mask = s.ringbuffer_size - 1;
1855 s.ringbuffer = s.alloc_u8
1856 .alloc_cell((s.ringbuffer_size as usize + kRingBufferWriteAheadSlack as usize +
1857 kBrotliMaxDictionaryWordLength as usize));
1858 if (s.ringbuffer.slice().len() == 0) {
1859 return false;
1860 }
1861 fast_mut!((s.ringbuffer.slice_mut())[s.ringbuffer_size as usize - 1]) = 0;
1862 fast_mut!((s.ringbuffer.slice_mut())[s.ringbuffer_size as usize - 2]) = 0;
1863 if custom_dict.len() != 0 {
1864 let offset = ((-s.custom_dict_size) & s.ringbuffer_mask) as usize;
1865 fast_mut!((s.ringbuffer.slice_mut())[offset ; offset + s.custom_dict_size as usize]).clone_from_slice(custom_dict);
1866 }
1867 }
1868 if s.custom_dict.slice().len() != 0 {
1869 s.alloc_u8.free_cell(core::mem::replace(&mut s.custom_dict,
1870 AllocU8::AllocatedMemory::default()));
1871 }
1872 true
1873}
1874
1875pub fn ReadContextModes<AllocU8: alloc::Allocator<u8>,
1877 AllocU32: alloc::Allocator<u32>,
1878 AllocHC: alloc::Allocator<HuffmanCode>>
1879 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1880 input: &[u8])
1881 -> BrotliDecoderErrorCode {
1882
1883 let mut i: i32 = s.loop_counter;
1884
1885 for context_mode_iter in fast_mut!((s.context_modes.slice_mut())[i as usize ;
1886 (s.block_type_length_state.num_block_types[0]
1887 as usize)])
1888 .iter_mut() {
1889 let mut bits: u32 = 0;
1890 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut bits, input)) {
1891 mark_unlikely();
1892 s.loop_counter = i;
1893 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1894 }
1895 *context_mode_iter = bits as u8;
1896 BROTLI_LOG_UINT!(i);
1897 i += 1;
1898 }
1899 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
1900}
1901
1902pub fn TakeDistanceFromRingBuffer<AllocU8: alloc::Allocator<u8>,
1903 AllocU32: alloc::Allocator<u32>,
1904 AllocHC: alloc::Allocator<HuffmanCode>>
1905 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>) {
1906 if (s.distance_code == 0) {
1907 s.dist_rb_idx -= 1;
1908 s.distance_code = fast!((s.dist_rb)[(s.dist_rb_idx & 3) as usize]);
1909 s.distance_context = 1;
1910 } else {
1911 let distance_code = s.distance_code << 1;
1912 const kDistanceShortCodeIndexOffset: u32 = 0xaaafff1b;
1915 const kDistanceShortCodeValueOffset: u32 = 0xfa5fa500;
1918 let mut v = (s.dist_rb_idx as i32 +
1919 (kDistanceShortCodeIndexOffset as i32 >>
1920 distance_code as i32)) as i32 & 0x3;
1921 s.distance_code = fast!((s.dist_rb)[v as usize]);
1922 v = (kDistanceShortCodeValueOffset >> distance_code) as i32 & 0x3;
1923 if ((distance_code & 0x3) != 0) {
1924 s.distance_code += v;
1925 } else {
1926 s.distance_code -= v;
1927 if (s.distance_code <= 0) {
1928 s.distance_code = 0x7fffffff;
1931 }
1932 }
1933 }
1934}
1935
1936pub fn SafeReadBits(br: &mut bit_reader::BrotliBitReader,
1937 n_bits: u32,
1938 val: &mut u32,
1939 input: &[u8])
1940 -> bool {
1941 if (n_bits != 0) {
1942 bit_reader::BrotliSafeReadBits(br, n_bits, val, input)
1943 } else {
1944 *val = 0;
1945 true
1946 }
1947}
1948
1949pub fn ReadDistanceInternal<AllocU8: alloc::Allocator<u8>,
1951 AllocU32: alloc::Allocator<u32>,
1952 AllocHC: alloc::Allocator<HuffmanCode>>
1953 (safe: bool,
1954 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1955 input: &[u8],
1956 distance_hgroup: &[&[HuffmanCode]; 256])
1957 -> bool {
1958 let mut distval: i32;
1959 let mut memento = bit_reader::BrotliBitReaderState::default();
1960 if (!safe) {
1961 s.distance_code = ReadSymbol(fast!((distance_hgroup)[s.dist_htree_index as usize]),
1962 &mut s.br,
1963 input) as i32;
1964 } else {
1965 let mut code: u32 = 0;
1966 memento = bit_reader::BrotliBitReaderSaveState(&s.br);
1967 if !SafeReadSymbol(fast!((distance_hgroup)[s.dist_htree_index as usize]),
1968 &mut s.br,
1969 &mut code,
1970 input) {
1971 return false;
1972 }
1973 s.distance_code = code as i32;
1974 }
1975 s.distance_context = 0;
1978 if ((s.distance_code as u64 & 0xfffffffffffffff0) == 0) {
1979 TakeDistanceFromRingBuffer(s);
1980 fast_mut!((s.block_type_length_state.block_length)[2]) -= 1;
1981 return true;
1982 }
1983 distval = s.distance_code - s.num_direct_distance_codes as i32;
1984 if (distval >= 0) {
1985 let nbits: u32;
1986 let postfix: i32;
1987 let offset: i32;
1988 if (!safe && (s.distance_postfix_bits == 0)) {
1989 nbits = (distval as u32 >> 1) + 1;
1990 offset = ((2 + (distval & 1)) << nbits) - 4;
1991 s.distance_code = s.num_direct_distance_codes as i32 + offset +
1992 bit_reader::BrotliReadBits(&mut s.br, nbits, input) as i32;
1993 } else {
1994 let mut bits: u32 = 0;
1996 postfix = distval & s.distance_postfix_mask;
1997 distval >>= s.distance_postfix_bits;
1998 nbits = (distval as u32 >> 1) + 1;
1999 if (safe) {
2000 if (!SafeReadBits(&mut s.br, nbits, &mut bits, input)) {
2001 s.distance_code = -1; bit_reader::BrotliBitReaderRestoreState(&mut s.br, &memento);
2003 return false;
2004 }
2005 } else {
2006 bits = bit_reader::BrotliReadBits(&mut s.br, nbits, input);
2007 }
2008 offset = (((distval & 1).wrapping_add(2)) << nbits).wrapping_sub(4);
2009 s.distance_code = ((offset + bits as i32) << s.distance_postfix_bits).wrapping_add(postfix).wrapping_add(s.num_direct_distance_codes as i32);
2010 }
2011 }
2012 s.distance_code = s.distance_code.wrapping_sub(NUM_DISTANCE_SHORT_CODES as i32).wrapping_add(1);
2013 fast_mut!((s.block_type_length_state.block_length)[2]) -= 1;
2014 true
2015}
2016
2017
2018pub fn ReadCommandInternal<AllocU8: alloc::Allocator<u8>,
2019 AllocU32: alloc::Allocator<u32>,
2020 AllocHC: alloc::Allocator<HuffmanCode>>
2021 (safe: bool,
2022 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2023 insert_length: &mut i32,
2024 input: &[u8],
2025 insert_copy_hgroup: &[&[HuffmanCode]; 256])
2026 -> bool {
2027 let mut cmd_code: u32 = 0;
2028 let mut insert_len_extra: u32 = 0;
2029 let mut copy_length: u32 = 0;
2030 let v: prefix::CmdLutElement;
2031 let mut memento = bit_reader::BrotliBitReaderState::default();
2032 if (!safe) {
2033 cmd_code = ReadSymbol(fast!((insert_copy_hgroup)[s.htree_command_index as usize]),
2034 &mut s.br,
2035 input);
2036 } else {
2037 memento = bit_reader::BrotliBitReaderSaveState(&s.br);
2038 if (!SafeReadSymbol(fast!((insert_copy_hgroup)[s.htree_command_index as usize]),
2039 &mut s.br,
2040 &mut cmd_code,
2041 input)) {
2042 return false;
2043 }
2044 }
2045 v = fast!((prefix::kCmdLut)[cmd_code as usize]);
2046 s.distance_code = v.distance_code as i32;
2047 s.distance_context = v.context as i32;
2048 s.dist_htree_index = fast_slice!((s.dist_context_map)[s.dist_context_map_slice_index
2049 + s.distance_context as usize]);
2050 *insert_length = v.insert_len_offset as i32;
2051 if (!safe) {
2052 if v.insert_len_extra_bits != 0 {
2053 mark_unlikely();
2054 insert_len_extra =
2055 bit_reader::BrotliReadBits(&mut s.br, v.insert_len_extra_bits as u32, input);
2056 }
2057 copy_length = bit_reader::BrotliReadBits(&mut s.br, v.copy_len_extra_bits as u32, input);
2058 } else if (!SafeReadBits(&mut s.br,
2059 v.insert_len_extra_bits as u32,
2060 &mut insert_len_extra,
2061 input)) ||
2062 (!SafeReadBits(&mut s.br,
2063 v.copy_len_extra_bits as u32,
2064 &mut copy_length,
2065 input)) {
2066 bit_reader::BrotliBitReaderRestoreState(&mut s.br, &memento);
2067 return false;
2068 }
2069 s.copy_length = copy_length as i32 + v.copy_len_offset as i32;
2070 fast_mut!((s.block_type_length_state.block_length)[1]) -= 1;
2071 *insert_length += insert_len_extra as i32;
2072 true
2073}
2074
2075
2076fn WarmupBitReader(safe: bool, br: &mut bit_reader::BrotliBitReader, input: &[u8]) -> bool {
2077 safe || bit_reader::BrotliWarmupBitReader(br, input)
2078}
2079
2080fn CheckInputAmount(safe: bool, br: &bit_reader::BrotliBitReader, num: u32) -> bool {
2081 safe || bit_reader::BrotliCheckInputAmount(br, num)
2082}
2083
2084#[inline(always)]
2085fn memmove16(data: &mut [u8], u32off_dst: u32, u32off_src: u32) {
2086 let off_dst = u32off_dst as usize;
2087 let off_src = u32off_src as usize;
2088 let mut local_array: [u8; 16] = fast_uninitialized!(16);
2108 local_array.clone_from_slice(fast!((data)[off_src as usize ; off_src as usize + 16]));
2109 fast_mut!((data)[off_dst as usize ; off_dst as usize + 16]).clone_from_slice(&local_array);
2110
2111
2112}
2113
2114
2115#[cfg(not(feature="unsafe"))]
2116fn memcpy_within_slice(data: &mut [u8], off_dst: usize, off_src: usize, size: usize) {
2117 if off_dst > off_src {
2118 let (src, dst) = data.split_at_mut(off_dst);
2119 let src_slice = fast!((src)[off_src ; off_src + size]);
2120 fast_mut!((dst)[0;size]).clone_from_slice(src_slice);
2121 } else {
2122 let (dst, src) = data.split_at_mut(off_src);
2123 let src_slice = fast!((src)[0;size]);
2124 fast_mut!((dst)[off_dst;off_dst + size]).clone_from_slice(src_slice);
2125 }
2126}
2127
2128#[cfg(feature="unsafe")]
2129fn memcpy_within_slice(data: &mut [u8], off_dst: usize, off_src: usize, size: usize) {
2130 let ptr = data.as_mut_ptr();
2131 unsafe {
2132 let dst = ptr.offset(off_dst as isize);
2133 let src = ptr.offset(off_src as isize);
2134 core::ptr::copy_nonoverlapping(src, dst, size);
2135 }
2136}
2137
2138pub fn BrotliDecoderHasMoreOutput<AllocU8: alloc::Allocator<u8>,
2139 AllocU32: alloc::Allocator<u32>,
2140 AllocHC: alloc::Allocator<HuffmanCode>>
2141 (s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
2142 if is_fatal(s.error_code) {
2144 return false;
2145 }
2146 s.ringbuffer.len() != 0 && UnwrittenBytes(s, false) != 0
2147}
2148pub fn BrotliDecoderTakeOutput<'a,
2149 AllocU8: alloc::Allocator<u8>,
2150 AllocU32: alloc::Allocator<u32>,
2151 AllocHC: alloc::Allocator<HuffmanCode>>(
2152 s: &'a mut BrotliState<AllocU8, AllocU32, AllocHC>,
2153 size: &mut usize,
2154) -> &'a [u8] {
2155 let one:usize = 1;
2156 let mut available_out = if *size != 0 { *size } else { one << 24 };
2157 let requested_out = available_out;
2158 if (s.ringbuffer.len() == 0) || is_fatal(s.error_code) {
2159 *size = 0;
2160 return &[];
2161 }
2162 WrapRingBuffer(s);
2163 let mut ign = 0usize;
2164 let mut ign2 = 0usize;
2165 let (status, result) = WriteRingBuffer(&mut available_out, None, &mut ign,&mut ign2, true, s);
2166 match status {
2168 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS | BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT => {
2169 *size = requested_out - available_out;
2170 },
2171 _ => {
2172 if is_fatal(status) {
2175 }
2178 *size = 0;
2179 return &[];
2180 }
2181 }
2182 return result;
2183}
2184
2185#[cfg(feature="ffi-api")]
2186pub fn BrotliDecoderIsUsed<AllocU8: alloc::Allocator<u8>,
2187 AllocU32: alloc::Allocator<u32>,
2188 AllocHC: alloc::Allocator<HuffmanCode>>(
2189 s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
2190 if let BrotliRunningState::BROTLI_STATE_UNINITED = s.state {
2191 false
2192 } else {
2193 bit_reader::BrotliGetAvailableBits(&s.br) != 0
2194 }
2195}
2196
2197pub fn BrotliDecoderIsFinished<AllocU8: alloc::Allocator<u8>,
2198 AllocU32: alloc::Allocator<u32>,
2199 AllocHC: alloc::Allocator<HuffmanCode>>(
2200 s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
2201 if let BrotliRunningState::BROTLI_STATE_DONE = s.state {
2202 !BrotliDecoderHasMoreOutput(s)
2203 } else {
2204 false
2205 }
2206}
2207
2208pub fn BrotliDecoderGetErrorCode<AllocU8: alloc::Allocator<u8>,
2209 AllocU32: alloc::Allocator<u32>,
2210 AllocHC: alloc::Allocator<HuffmanCode>>(
2211 s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> BrotliDecoderErrorCode {
2212 s.error_code
2213}
2214
2215fn ProcessCommandsInternal<AllocU8: alloc::Allocator<u8>,
2216 AllocU32: alloc::Allocator<u32>,
2217 AllocHC: alloc::Allocator<HuffmanCode>>
2218 (safe: bool,
2219 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2220 input: &[u8])
2221 -> BrotliDecoderErrorCode {
2222 if (!CheckInputAmount(safe, &s.br, 28)) || (!WarmupBitReader(safe, &mut s.br, input)) {
2223 mark_unlikely();
2224 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2225 }
2226 let mut pos = s.pos;
2227 let mut i: i32 = s.loop_counter; let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2229 let mut saved_literal_hgroup =
2230 core::mem::replace(&mut s.literal_hgroup,
2231 HuffmanTreeGroup::<AllocU32, AllocHC>::default());
2232 let mut saved_distance_hgroup =
2233 core::mem::replace(&mut s.distance_hgroup,
2234 HuffmanTreeGroup::<AllocU32, AllocHC>::default());
2235 let mut saved_insert_copy_hgroup =
2236 core::mem::replace(&mut s.insert_copy_hgroup,
2237 HuffmanTreeGroup::<AllocU32, AllocHC>::default());
2238 {
2239
2240 let literal_hgroup = saved_literal_hgroup.build_hgroup_cache();
2241 let distance_hgroup = saved_distance_hgroup.build_hgroup_cache();
2242 let insert_copy_hgroup = saved_insert_copy_hgroup.build_hgroup_cache();
2243
2244 loop {
2245 match s.state {
2246 BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN => {
2247 if (!CheckInputAmount(safe, &s.br, 28)) {
2248 mark_unlikely();
2250 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2251 break; }
2253 if (fast_mut!((s.block_type_length_state.block_length)[1]) == 0) {
2254 mark_unlikely();
2255 if !DecodeCommandBlockSwitchInternal(safe, s, input) {
2256 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2257 break; }
2259 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
2260 continue; }
2262 if (!ReadCommandInternal(safe, s, &mut i, input, &insert_copy_hgroup)) && safe {
2264 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2265 break; }
2267 BROTLI_LOG!("[ProcessCommandsInternal] pos = %d insert = %d copy = %d distance = %d\n",
2268 pos, i, s.copy_length, s.distance_code);
2269 if (i == 0) {
2270 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2271 continue; }
2273 s.meta_block_remaining_len -= i;
2274 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
2275 }
2276 BrotliRunningState::BROTLI_STATE_COMMAND_INNER => {
2277 if (s.trivial_literal_context != 0) {
2279 let mut bits: u32 = 0;
2280 let mut value: u32 = 0;
2281 let mut literal_htree = &fast!((literal_hgroup)[s.literal_htree_index as usize]);
2282 PreloadSymbol(safe, literal_htree, &mut s.br, &mut bits, &mut value, input);
2283 let mut inner_return: bool = false;
2284 let mut inner_continue: bool = false;
2285 loop {
2286 if (!CheckInputAmount(safe, &s.br, 28)) {
2287 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2289 inner_return = true;
2290 break;
2291 }
2292 if (fast!((s.block_type_length_state.block_length)[0]) == 0) {
2293 mark_unlikely();
2294 if (!DecodeLiteralBlockSwitchInternal(safe, s, input)) && safe {
2295 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2296 inner_return = true;
2297 break;
2298 }
2299 literal_htree = fast_ref!((literal_hgroup)[s.literal_htree_index as usize]);
2300 PreloadSymbol(safe, literal_htree, &mut s.br, &mut bits, &mut value, input);
2301 if (s.trivial_literal_context == 0) {
2302 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
2303 inner_continue = true;
2304 break; }
2306 }
2307 if (!safe) {
2308 fast_mut!((s.ringbuffer.slice_mut())[pos as usize]) =
2309 ReadPreloadedSymbol(literal_htree, &mut s.br, &mut bits, &mut value, input) as u8;
2310 } else {
2311 let mut literal: u32 = 0;
2312 if (!SafeReadSymbol(literal_htree, &mut s.br, &mut literal, input)) {
2313 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2314 inner_return = true;
2315 break;
2316 }
2317 fast_mut!((s.ringbuffer.slice_mut())[pos as usize]) = literal as u8;
2318 }
2319 fast_mut!((s.block_type_length_state.block_length)[0]) -= 1;
2320 BROTLI_LOG_UINT!(s.literal_htree_index);
2321 BROTLI_LOG_ARRAY_INDEX!(s.ringbuffer.slice(), pos);
2322 pos += 1;
2323 if (pos == s.ringbuffer_size) {
2324 mark_unlikely();
2325 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE;
2326 i -= 1;
2327 inner_return = true;
2328 break;
2329 }
2330 i -= 1;
2331 if i == 0 {
2332 break;
2333 }
2334 }
2335 if inner_return {
2336 break; }
2338 if inner_continue {
2339 mark_unlikely();
2340 continue;
2341 }
2342 } else {
2343 let mut p1 = fast_slice!((s.ringbuffer)[((pos - 1) & s.ringbuffer_mask) as usize]);
2344 let mut p2 = fast_slice!((s.ringbuffer)[((pos - 2) & s.ringbuffer_mask) as usize]);
2345 let mut inner_return: bool = false;
2346 let mut inner_continue: bool = false;
2347 loop {
2348 if (!CheckInputAmount(safe, &s.br, 28)) {
2349 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
2351 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2352 inner_return = true;
2353 break;
2354 }
2355 if (fast!((s.block_type_length_state.block_length)[0]) == 0) {
2356 mark_unlikely();
2357 if (!DecodeLiteralBlockSwitchInternal(safe, s, input)) && safe {
2358 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2359 inner_return = true;
2360 break;
2361 }
2362 if s.trivial_literal_context != 0 {
2363 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
2364 inner_continue = true;
2365 break;
2366 }
2367 }
2368 let context = s.context_lookup[p1 as usize] | s.context_lookup[p2 as usize |256];
2369 BROTLI_LOG_UINT!(p1);
2370 BROTLI_LOG_UINT!(p2);
2371 BROTLI_LOG_UINT!(context);
2372 let hc: &[HuffmanCode];
2373 {
2374 let i = fast_slice!((s.context_map)[s.context_map_slice_index + context as usize]);
2375 hc = fast!((literal_hgroup)[i as usize]);
2376 }
2377 p2 = p1;
2378 if (!safe) {
2379 p1 = ReadSymbol(hc, &mut s.br, input) as u8;
2380 } else {
2381 let mut literal: u32 = 0;
2382 if (!SafeReadSymbol(hc, &mut s.br, &mut literal, input)) {
2383 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2384 inner_return = true;
2385 break;
2386 }
2387 p1 = literal as u8;
2388 }
2389 fast_slice_mut!((s.ringbuffer)[pos as usize]) = p1;
2390 fast_mut!((s.block_type_length_state.block_length)[0]) -= 1;
2391 BROTLI_LOG_UINT!(s.context_map.slice()[s.context_map_slice_index as usize +
2392 context as usize]);
2393 BROTLI_LOG_ARRAY_INDEX!(s.ringbuffer.slice(), pos & s.ringbuffer_mask);
2394 pos += 1;
2395 if (pos == s.ringbuffer_size) {
2396 mark_unlikely();
2397 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE;
2398 i -= 1;
2399 inner_return = true;
2400 break;
2401 }
2402 i -= 1;
2403 if i == 0 {
2404 break;
2405 }
2406 }
2407 if inner_return {
2408 break; }
2410 if inner_continue {
2411 mark_unlikely();
2412 continue;
2413 }
2414 }
2415 if (s.meta_block_remaining_len <= 0) {
2416 mark_unlikely();
2417 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2418 break; }
2420 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2421 }
2422 BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS => {
2423 if s.distance_code >= 0 {
2424 let not_distance_code = if s.distance_code != 0 { 0 } else { 1 };
2425 s.distance_context = not_distance_code;
2426 s.dist_rb_idx -= 1;
2427 s.distance_code = fast!((s.dist_rb)[(s.dist_rb_idx & 3) as usize]);
2428 } else {
2430 if fast!((s.block_type_length_state.block_length)[2]) == 0 {
2431 mark_unlikely();
2432 if (!DecodeDistanceBlockSwitchInternal(safe, s, input)) && safe {
2433 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2434 break; }
2436 }
2437 if (!ReadDistanceInternal(safe, s, input, &distance_hgroup)) && safe {
2438 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2439 break; }
2441 }
2442 BROTLI_LOG!("[ProcessCommandsInternal] pos = %d distance = %d\n",
2444 pos, s.distance_code);
2445
2446 if (s.max_distance != s.max_backward_distance) {
2447 if (pos < s.max_backward_distance_minus_custom_dict_size) {
2448 s.max_distance = pos + s.custom_dict_size;
2449 } else {
2450 s.max_distance = s.max_backward_distance;
2451 }
2452 }
2453 i = s.copy_length;
2454 if (s.distance_code > s.max_distance) {
2457 if s.distance_code > kBrotliMaxAllowedDistance as i32 {
2458 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE;
2459 }
2460 if (i >= kBrotliMinDictionaryWordLength as i32 &&
2461 i <= kBrotliMaxDictionaryWordLength as i32) {
2462 let mut offset = fast!((kBrotliDictionaryOffsetsByLength)[i as usize]) as i32;
2463 let word_id = s.distance_code - s.max_distance - 1;
2464 let shift = fast!((kBrotliDictionarySizeBitsByLength)[i as usize]);
2465 let mask = bit_reader::BitMask(shift as u32) as i32;
2466 let word_idx = word_id & mask;
2467 let transform_idx = word_id >> shift;
2468 s.dist_rb_idx += s.distance_context;
2469 offset += word_idx * i;
2470 if (transform_idx < kNumTransforms) {
2471 let mut len = i;
2472 let word = fast!((kBrotliDictionary)[offset as usize ; (offset + len) as usize]);
2473 if (transform_idx == 0) {
2474 fast_slice_mut!((s.ringbuffer)[pos as usize ; ((pos + len) as usize)])
2475 .clone_from_slice(word);
2476 } else {
2477 len = TransformDictionaryWord(fast_slice_mut!((s.ringbuffer)[pos as usize;]),
2478 word,
2479 len,
2480 transform_idx);
2481 }
2482 pos += len;
2483 s.meta_block_remaining_len -= len;
2484 if (pos >= s.ringbuffer_size) {
2485 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1;
2487 break; }
2489 } else {
2490 BROTLI_LOG!(
2491 "Invalid backward reference. pos: %d distance: %d len: %d bytes left: %d\n",
2492 pos, s.distance_code, i,
2493 s.meta_block_remaining_len);
2494 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM;
2495 break; }
2497 } else {
2498 BROTLI_LOG!(
2499 "Invalid backward reference. pos:%d distance:%d len:%d bytes left:%d\n",
2500 pos, s.distance_code, i, s.meta_block_remaining_len);
2501 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DICTIONARY;
2502 break; }
2504 } else {
2505 fast_mut!((s.dist_rb)[(s.dist_rb_idx & 3) as usize]) = s.distance_code;
2507 s.dist_rb_idx += 1;
2508 s.meta_block_remaining_len -= i;
2509 let src_start = ((pos - s.distance_code) & s.ringbuffer_mask) as u32;
2514 let dst_start = pos as u32;
2515 let dst_end = pos as u32 + i as u32;
2516 let src_end = src_start + i as u32;
2517 memmove16(&mut s.ringbuffer.slice_mut(), dst_start, src_start);
2518 if (src_end > pos as u32 && dst_end > src_start) {
2521 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
2522 continue; }
2524 if (dst_end >= s.ringbuffer_size as u32 || src_end >= s.ringbuffer_size as u32) {
2525 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
2526 continue; }
2528 pos += i;
2529 if (i > 16) {
2530 if (i > 32) {
2531 memcpy_within_slice(s.ringbuffer.slice_mut(),
2532 dst_start as usize + 16,
2533 src_start as usize + 16,
2534 (i - 16) as usize);
2535 } else {
2536 memmove16(&mut s.ringbuffer.slice_mut(),
2539 dst_start + 16,
2540 src_start + 16);
2541 }
2542 }
2543 }
2544 if (s.meta_block_remaining_len <= 0) {
2545 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2547 break; } else {
2549 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
2550 continue; }
2552 }
2553 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY => {
2554 let mut wrap_guard = s.ringbuffer_size - pos;
2555 let mut inner_return: bool = false;
2556 while i > 0 {
2557 i -= 1;
2558 fast_slice_mut!((s.ringbuffer)[pos as usize]) =
2559 fast_slice!((s.ringbuffer)[((pos - s.distance_code) & s.ringbuffer_mask) as usize]);
2560 pos += 1;
2561 wrap_guard -= 1;
2562 if (wrap_guard == 0) {
2563 mark_unlikely();
2564 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2;
2566 inner_return = true;
2567 break; }
2569 }
2570 if inner_return {
2571 mark_unlikely();
2572 break;
2573 }
2574 i -= 1;
2575 if (s.meta_block_remaining_len <= 0) {
2576 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2578 break; } else {
2580 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
2581 continue;
2582 }
2583 }
2584 _ => {
2585 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
2586 break; }
2588 }
2589 }
2590 }
2591 s.pos = pos;
2592 s.loop_counter = i;
2593
2594 let _ = core::mem::replace(&mut s.literal_hgroup,
2595 core::mem::replace(&mut saved_literal_hgroup,
2596 HuffmanTreeGroup::<AllocU32, AllocHC>::default()));
2597
2598 let _ = core::mem::replace(&mut s.distance_hgroup,
2599 core::mem::replace(&mut saved_distance_hgroup,
2600 HuffmanTreeGroup::<AllocU32, AllocHC>::default()));
2601
2602 let _ = core::mem::replace(&mut s.insert_copy_hgroup,
2603 core::mem::replace(&mut saved_insert_copy_hgroup,
2604 HuffmanTreeGroup::<AllocU32, AllocHC>::default()));
2605
2606 result
2607}
2608
2609fn ProcessCommands<AllocU8: alloc::Allocator<u8>,
2610 AllocU32: alloc::Allocator<u32>,
2611 AllocHC: alloc::Allocator<HuffmanCode>>
2612 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2613 input: &[u8])
2614 -> BrotliDecoderErrorCode {
2615 ProcessCommandsInternal(false, s, input)
2616}
2617
2618fn SafeProcessCommands<AllocU8: alloc::Allocator<u8>,
2619 AllocU32: alloc::Allocator<u32>,
2620 AllocHC: alloc::Allocator<HuffmanCode>>
2621 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2622 input: &[u8])
2623 -> BrotliDecoderErrorCode {
2624 ProcessCommandsInternal(true, s, input)
2625}
2626
2627pub fn BrotliMaxDistanceSymbol(ndirect: u32, npostfix: u32) -> u32{
2630 let bound:[u32;kBrotliMaxPostfix + 1] = [0, 4, 12, 28];
2631 let diff:[u32;kBrotliMaxPostfix + 1] = [73, 126, 228, 424];
2632 let postfix = 1 << npostfix;
2633 if (ndirect < bound[npostfix as usize ]) {
2634 return ndirect + diff[npostfix as usize] + postfix;
2635 } else if (ndirect > bound[npostfix as usize] + postfix) {
2636 return ndirect + diff[npostfix as usize];
2637 } else {
2638 return bound[npostfix as usize] + diff[npostfix as usize] + postfix;
2639 }
2640}
2641
2642pub fn BrotliDecompressStream<AllocU8: alloc::Allocator<u8>,
2643 AllocU32: alloc::Allocator<u32>,
2644 AllocHC: alloc::Allocator<HuffmanCode>>
2645 (available_in: &mut usize,
2646 input_offset: &mut usize,
2647 xinput: &[u8],
2648 mut available_out: &mut usize,
2649 mut output_offset: &mut usize,
2650 mut output: &mut [u8],
2651 mut total_out: &mut usize,
2652 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
2653 -> BrotliResult {
2654
2655 let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2656
2657 let mut saved_buffer: [u8; 8] = s.buffer;
2658 let mut local_input: &[u8];
2659 if is_fatal(s.error_code) {
2660 return BrotliResult::ResultFailure;
2661 }
2662 if *available_in as u64 >= (1u64 << 32) {
2663 return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
2664 }
2665 if *input_offset as u64 >= (1u64 << 32) {
2666 return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
2667 }
2668 if *input_offset + *available_in > xinput.len() {
2669 return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
2670 }
2671 if *output_offset + *available_out > output.len() {
2672 return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
2673 }
2674 if s.buffer_length == 0 {
2675 local_input = xinput;
2676 s.br.avail_in = *available_in as u32;
2677 s.br.next_in = *input_offset as u32;
2678 } else {
2679 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2680 let copy_len = core::cmp::min(saved_buffer.len() - s.buffer_length as usize, *available_in);
2681 if copy_len > 0 {
2682 fast_mut!((saved_buffer)[s.buffer_length as usize ; (s.buffer_length as usize + copy_len)])
2683 .clone_from_slice(fast!((xinput)[*input_offset ; copy_len + *input_offset]));
2684 fast_mut!((s.buffer)[s.buffer_length as usize ; (s.buffer_length as usize + copy_len)])
2685 .clone_from_slice(fast!((xinput)[*input_offset ; copy_len + *input_offset]));
2686 }
2687 local_input = &saved_buffer[..];
2688 s.br.next_in = 0;
2689 }
2690 loop {
2691 match result {
2692 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2693 _ => {
2694 match result {
2695 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT => {
2696 if s.ringbuffer.slice().len() != 0 {
2697 let (intermediate_result, _) = WriteRingBuffer(available_out,
2698 Some(&mut output),
2699 &mut output_offset,
2700 &mut total_out,
2701 true,
2702 &mut s);
2703 if is_fatal(intermediate_result) {
2704 result = intermediate_result;
2705 break;
2706 }
2707 }
2708 if s.buffer_length != 0 {
2709 if s.br.avail_in == 0 {
2711 s.buffer_length = 0;
2715 result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2717 local_input = xinput;
2718 s.br.avail_in = *available_in as u32;
2719 s.br.next_in = *input_offset as u32;
2720 continue;
2721 } else if *available_in != 0 {
2722 result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2725 let new_byte = fast!((xinput)[*input_offset]);
2726 fast_mut!((s.buffer)[s.buffer_length as usize]) = new_byte;
2727 assert_eq!(fast!((saved_buffer)[s.buffer_length as usize]), new_byte);
2730 s.buffer_length += 1;
2731 s.br.avail_in = s.buffer_length;
2732 (*input_offset) += 1;
2733 (*available_in) -= 1;
2734 continue;
2737 }
2738 break;
2745 } else {
2746 *input_offset = s.br.next_in as usize;
2749 *available_in = s.br.avail_in as usize;
2750 while *available_in != 0 {
2751 fast_mut!((s.buffer)[s.buffer_length as usize]) = fast!((xinput)[*input_offset]);
2752 s.buffer_length += 1;
2753 (*input_offset) += 1;
2754 (*available_in) -= 1;
2755 }
2756 break;
2757 }
2758 }
2760 _ => {
2761 if s.buffer_length != 0 {
2763 s.buffer_length = 0;
2766 } else {
2767 bit_reader::BrotliBitReaderUnload(&mut s.br);
2771 *available_in = s.br.avail_in as usize;
2772 *input_offset = s.br.next_in as usize;
2773 }
2774 }
2775 }
2776 break;
2777 }
2778 }
2779 loop {
2780 match s.state {
2782 BrotliRunningState::BROTLI_STATE_UNINITED => {
2783 if (!bit_reader::BrotliWarmupBitReader(&mut s.br, local_input)) {
2785 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2786 break;
2787 }
2788 result = DecodeWindowBits(&mut s.large_window, &mut s.window_bits, &mut s.br);
2791 match result {
2792 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2793 _ => break,
2794 }
2795 if s.large_window {
2796 s.state = BrotliRunningState::BROTLI_STATE_LARGE_WINDOW_BITS;
2797 } else {
2798 s.state = BrotliRunningState::BROTLI_STATE_INITIALIZE;
2799 }
2800 }
2801 BrotliRunningState::BROTLI_STATE_LARGE_WINDOW_BITS => {
2802 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 6, &mut s.window_bits, local_input)) {
2803 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2804 break;
2805 }
2806 if (s.window_bits < kBrotliLargeMinWbits ||
2807 s.window_bits > kBrotliLargeMaxWbits) {
2808 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
2809 break;
2810 }
2811 s.state = BrotliRunningState::BROTLI_STATE_INITIALIZE;
2812 }
2813 BrotliRunningState::BROTLI_STATE_INITIALIZE => {
2814 s.max_backward_distance = (1 << s.window_bits) - kBrotliWindowGap as i32;
2815 s.max_backward_distance_minus_custom_dict_size = s.max_backward_distance -
2816 s.custom_dict_size;
2817
2818 s.block_type_length_state.block_type_trees = s.alloc_hc
2820 .alloc_cell(3 * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as usize);
2821 if (s.block_type_length_state.block_type_trees.slice().len() == 0) {
2822 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES;
2823 break;
2824 }
2825 s.block_type_length_state.block_len_trees = s.alloc_hc
2826 .alloc_cell(3 * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as usize);
2827
2828 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
2829 }
2831 BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN => {
2832 s.BrotliStateMetablockBegin();
2833 BROTLI_LOG_UINT!(s.pos);
2834 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER;
2835 }
2837 BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER => {
2838 result = DecodeMetaBlockLength(&mut s, local_input); match result {
2840 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2841 _ => break,
2842 }
2843 BROTLI_LOG_UINT!(s.is_last_metablock);
2844 BROTLI_LOG_UINT!(s.meta_block_remaining_len);
2845 BROTLI_LOG_UINT!(s.is_metadata);
2846 BROTLI_LOG_UINT!(s.is_uncompressed);
2847 if (s.is_metadata != 0 || s.is_uncompressed != 0) &&
2848 !bit_reader::BrotliJumpToByteBoundary(&mut s.br) {
2849 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_2;
2850 break;
2851 }
2852 if s.is_metadata != 0 {
2853 s.state = BrotliRunningState::BROTLI_STATE_METADATA;
2854 break;
2855 }
2856 if s.meta_block_remaining_len == 0 {
2857 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2858 break;
2859 }
2860 if s.ringbuffer.slice().len() == 0 && !BrotliAllocateRingBuffer(&mut s, local_input) {
2861 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2;
2862 break;
2863 }
2864 if s.is_uncompressed != 0 {
2865 s.state = BrotliRunningState::BROTLI_STATE_UNCOMPRESSED;
2866 break;
2867 }
2868 s.loop_counter = 0;
2869 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0;
2870 break;
2871 }
2872 BrotliRunningState::BROTLI_STATE_UNCOMPRESSED => {
2873 let mut _bytes_copied = s.meta_block_remaining_len;
2874 result = CopyUncompressedBlockToOutput(&mut available_out,
2875 &mut output,
2876 &mut output_offset,
2877 &mut total_out,
2878 &mut s,
2879 local_input);
2880 _bytes_copied -= s.meta_block_remaining_len;
2881 match result {
2882 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2883 _ => break,
2884 }
2885 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2886 break;
2887 }
2888 BrotliRunningState::BROTLI_STATE_METADATA => {
2889 while s.meta_block_remaining_len > 0 {
2890 let mut bits = 0u32;
2891 if !bit_reader::BrotliSafeReadBits(&mut s.br, 8, &mut bits, local_input) {
2893 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2894 break;
2895 }
2896 s.meta_block_remaining_len -= 1;
2897 }
2898 if let BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS = result {
2899 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE
2900 }
2901 break;
2902 }
2903 BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0 => {
2904 if s.loop_counter >= 3 {
2905 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER_2;
2906 break;
2907 }
2908 {
2910 let index = s.loop_counter as usize;
2911 result =
2912 DecodeVarLenUint8(&mut s.substate_decode_uint8,
2913 &mut s.br,
2914 &mut fast_mut!((s.block_type_length_state.num_block_types)[index]),
2915 local_input);
2916 }
2917 match result {
2918 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2919 _ => break,
2920 }
2921 fast_mut!((s.block_type_length_state.num_block_types)[s.loop_counter as usize]) += 1;
2922 BROTLI_LOG_UINT!(s.block_type_length_state.num_block_types[s.loop_counter as usize]);
2923 if fast!((s.block_type_length_state.num_block_types)[s.loop_counter as usize]) < 2 {
2924 s.loop_counter += 1;
2925 break;
2926 }
2927 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_1;
2928 }
2930 BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_1 => {
2931 let tree_offset = s.loop_counter as u32 * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as u32;
2932 let mut new_huffman_table = mem::replace(&mut s.block_type_length_state.block_type_trees,
2933 AllocHC::AllocatedMemory::default());
2934 let loop_counter = s.loop_counter as usize;
2935 let alphabet_size = fast!((s.block_type_length_state.num_block_types)[loop_counter]) + 2;
2936 result =
2937 ReadHuffmanCode(alphabet_size, alphabet_size,
2938 new_huffman_table.slice_mut(),
2939 tree_offset as usize,
2940 None,
2941 &mut s,
2942 local_input);
2943 let _ = mem::replace(&mut s.block_type_length_state.block_type_trees,
2944 new_huffman_table);
2945 match result {
2946 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2947 _ => break,
2948 }
2949 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_2;
2950 }
2952 BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_2 => {
2953 let tree_offset = s.loop_counter * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as i32;
2954 let mut new_huffman_table = mem::replace(&mut s.block_type_length_state.block_len_trees,
2955 AllocHC::AllocatedMemory::default());
2956 result = ReadHuffmanCode(kNumBlockLengthCodes, kNumBlockLengthCodes,
2957 new_huffman_table.slice_mut(),
2958 tree_offset as usize,
2959 None,
2960 &mut s,
2961 local_input);
2962 let _ = mem::replace(&mut s.block_type_length_state.block_len_trees,
2963 new_huffman_table);
2964 match result {
2965 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2966 _ => break,
2967 }
2968 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_3;
2969 }
2971 BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_3 => {
2972 let tree_offset = s.loop_counter * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as i32;
2973
2974 let mut block_length_out: u32 = 0;
2975 let ind_ret: (bool, u32);
2976
2977 ind_ret = SafeReadBlockLengthIndex(&s.block_type_length_state.substate_read_block_length,
2978 s.block_type_length_state.block_length_index,
2979 fast_slice!((s.block_type_length_state.block_len_trees)
2980 [tree_offset as usize;]),
2981 &mut s.br, local_input);
2982
2983 if !SafeReadBlockLengthFromIndex(&mut s.block_type_length_state,
2984 &mut s.br,
2985 &mut block_length_out,
2986 ind_ret,
2987 local_input) {
2988 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2989 break;
2990 }
2991 fast_mut!((s.block_type_length_state.block_length)[s.loop_counter as usize]) =
2992 block_length_out;
2993 BROTLI_LOG_UINT!(s.block_type_length_state.block_length[s.loop_counter as usize]);
2994 s.loop_counter += 1;
2995 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0;
2996 break;
2997 }
2998 BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER_2 => {
2999 let mut bits: u32 = 0;
3000 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 6, &mut bits, local_input)) {
3001 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
3002 break;
3003 }
3004 s.distance_postfix_bits = bits & bit_reader::BitMask(2);
3005 bits >>= 2;
3006 s.num_direct_distance_codes = NUM_DISTANCE_SHORT_CODES +
3007 (bits << s.distance_postfix_bits);
3008 BROTLI_LOG_UINT!(s.num_direct_distance_codes);
3009 BROTLI_LOG_UINT!(s.distance_postfix_bits);
3010 s.distance_postfix_mask = bit_reader::BitMask(s.distance_postfix_bits) as i32;
3011 s.context_modes = s.alloc_u8
3012 .alloc_cell(fast!((s.block_type_length_state.num_block_types)[0]) as usize);
3013 if (s.context_modes.slice().len() == 0) {
3014 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES;
3015 break;
3016 }
3017 s.loop_counter = 0;
3018 s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MODES;
3019 }
3021 BrotliRunningState::BROTLI_STATE_CONTEXT_MODES => {
3022 result = ReadContextModes(&mut s, local_input);
3023 match result {
3024 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3025 _ => break,
3026 }
3027 s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1;
3028 }
3030 BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1 => {
3031 result =
3032 DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[0]) as usize) <<
3033 kLiteralContextBits as usize,
3034 false,
3035 &mut s,
3036 local_input);
3037 match result {
3038 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3039 _ => break,
3040 }
3041 DetectTrivialLiteralBlockTypes(s);
3042 s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2;
3043 }
3045 BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2 => {
3046 let num_direct_codes =
3047 s.num_direct_distance_codes - NUM_DISTANCE_SHORT_CODES;
3048 let num_distance_codes = BROTLI_DISTANCE_ALPHABET_SIZE(
3049 s.distance_postfix_bits, num_direct_codes,
3050 (if s.large_window { BROTLI_LARGE_MAX_DISTANCE_BITS } else {
3051 BROTLI_MAX_DISTANCE_BITS}));
3052 let max_distance_symbol = if s.large_window {
3053 BrotliMaxDistanceSymbol(
3054 num_direct_codes, s.distance_postfix_bits)
3055 } else {
3056 num_distance_codes
3057 };
3058 result =
3059 DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[2]) as usize) <<
3060 kDistanceContextBits as usize,
3061 true,
3062 s,
3063 local_input);
3064 match result {
3065 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3066 _ => break,
3067 }
3068 s.literal_hgroup.init(&mut s.alloc_u32,
3069 &mut s.alloc_hc,
3070 kNumLiteralCodes,
3071 kNumLiteralCodes,
3072 s.num_literal_htrees as u16);
3073 s.insert_copy_hgroup.init(&mut s.alloc_u32,
3074 &mut s.alloc_hc,
3075 kNumInsertAndCopyCodes,
3076 kNumInsertAndCopyCodes,
3077 fast!((s.block_type_length_state.num_block_types)[1]) as u16);
3078 s.distance_hgroup.init(&mut s.alloc_u32,
3079 &mut s.alloc_hc,
3080 num_distance_codes as u16,
3081 max_distance_symbol as u16,
3082 s.num_dist_htrees as u16);
3083 if (s.literal_hgroup.codes.slice().len() == 0 ||
3084 s.insert_copy_hgroup.codes.slice().len() == 0 ||
3085 s.distance_hgroup.codes.slice().len() == 0) {
3086 return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE);
3087 }
3088
3089 s.loop_counter = 0;
3121 s.state = BrotliRunningState::BROTLI_STATE_TREE_GROUP;
3122 }
3124 BrotliRunningState::BROTLI_STATE_TREE_GROUP => {
3125 result = HuffmanTreeGroupDecode(s.loop_counter, &mut s, local_input);
3126 match result {
3127 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3128 _ => break,
3129 }
3130 s.loop_counter += 1;
3131 if (s.loop_counter >= 3) {
3132 PrepareLiteralDecoding(s);
3133 s.dist_context_map_slice_index = 0;
3134 s.htree_command_index = 0;
3141 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
3143 }
3144 break;
3145 }
3146 BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN |
3147 BrotliRunningState::BROTLI_STATE_COMMAND_INNER |
3148 BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS |
3149 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY => {
3150 result = ProcessCommands(s, local_input);
3151 if let BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT = result {
3152 result = SafeProcessCommands(s, local_input)
3153 }
3154 break;
3155 }
3156 BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE |
3157 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1 |
3158 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2 => {
3159 let (xresult, _) = WriteRingBuffer(&mut available_out,
3160 Some(&mut output),
3161 &mut output_offset,
3162 &mut total_out,
3163 false,
3164 &mut s);
3165 result = xresult;
3166 match result {
3167 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3168 _ => break,
3169 }
3170 WrapRingBuffer(s);
3171 if s.ringbuffer_size == 1 << s.window_bits {
3172 s.max_distance = s.max_backward_distance;
3173 }
3174 match s.state {
3175 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1 => {
3176 if (s.meta_block_remaining_len <= 0) {
3177 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
3179 } else {
3180 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
3181 }
3182 break;
3183 }
3184 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2 => {
3185 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
3186 }
3187 _ => {
3188 if (s.loop_counter == 0) {
3190 if (s.meta_block_remaining_len <= 0) {
3191 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
3192 } else {
3193 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
3194 }
3195 break;
3196 }
3197 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
3198 }
3199 }
3200 break;
3201 }
3202 BrotliRunningState::BROTLI_STATE_METABLOCK_DONE => {
3203 s.BrotliStateCleanupAfterMetablock();
3204 if (s.is_last_metablock == 0) {
3205 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
3206 break;
3207 }
3208 if (!bit_reader::BrotliJumpToByteBoundary(&mut s.br)) {
3209 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_2;
3210 }
3211 if (s.buffer_length == 0) {
3212 bit_reader::BrotliBitReaderUnload(&mut s.br);
3213 *available_in = s.br.avail_in as usize;
3214 *input_offset = s.br.next_in as usize;
3215 }
3216 s.state = BrotliRunningState::BROTLI_STATE_DONE;
3217 }
3219 BrotliRunningState::BROTLI_STATE_DONE => {
3220 if (s.ringbuffer.slice().len() != 0) {
3221 let (xresult, _) = WriteRingBuffer(&mut available_out,
3222 Some(&mut output),
3223 &mut output_offset,
3224 &mut total_out,
3225 true,
3226 &mut s);
3227 result = xresult;
3228 match result {
3229 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3230 _ => break,
3231 }
3232 }
3233 return SaveErrorCode!(s, result);
3234 }
3235 }
3236 }
3237 }
3238
3239 SaveErrorCode!(s, result)
3240}
3241