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, copy_bytes, kNumTransforms};
22use state::{BlockTypeAndLengthState, BrotliRunningContextMapState, BrotliRunningDecodeUint8State,
23 BrotliRunningHuffmanState, BrotliRunningMetablockHeaderState,
24 BrotliRunningReadBlockLengthState, BrotliRunningState, BrotliRunningTreeGroupState,
25 BrotliRunningUncompressedState, kLiteralContextBits,
26 BrotliDecoderErrorCode, COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED,
27};
28use context::{kContextLookup};
29use ::dictionary::{kBrotliDictionary, kBrotliDictionaryOffsetsByLength,
30 kBrotliDictionarySizeBitsByLength, kBrotliMaxDictionaryWordLength,
31 kBrotliMinDictionaryWordLength};
32use ::shared_dictionary::{SHARED_BROTLI_MIN_DICTIONARY_WORD_LENGTH,
33 SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH,
34 SHARED_BROTLI_MAX_TRANSFORM_AFFIX_LENGTH,
35 DictionaryLookupError};
36pub use huffman::{HuffmanCode, HuffmanTreeGroup};
37use huffman::{HuffmanTable, LITERAL_TABLE_WINDOW, INSERT_COPY_TABLE_WINDOW, DISTANCE_ROOT_WINDOW};
38#[repr(C)]
39#[derive(Debug)]
40pub enum BrotliResult {
41 ResultSuccess = 1,
42 NeedsMoreInput = 2,
43 NeedsMoreOutput = 3,
44 ResultFailure = 0,
45}
46const kBrotliWindowGap: u32 = 16;
47const kBrotliLargeMinWbits: u32 = 10;
48const kBrotliLargeMaxWbits: u32 = 30;
49const kBrotliMaxPostfix: usize = 3;
50const kBrotliMaxAllowedDistance: u32 = 0x7FFFFFFC;
51const kDefaultCodeLength: u32 = 8;
52const kCodeLengthRepeatCode: u32 = 16;
53pub const kNumLiteralCodes: u16 = 256;
54pub const kNumInsertAndCopyCodes: u16 = 704;
55pub const kNumBlockLengthCodes: u32 = 26;
56const kDistanceContextBits: i32 = 2;
57const HUFFMAN_TABLE_BITS: u32 = 8;
58const HUFFMAN_TABLE_MASK: u32 = 0xff;
59const CODE_LENGTH_CODES: usize = 18;
60const kCodeLengthCodeOrder: [u8; CODE_LENGTH_CODES] = [1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10,
61 11, 12, 13, 14, 15];
62
63const kCodeLengthPrefixLength: [u8; 16] = [2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4];
65
66const kCodeLengthPrefixValue: [u8; 16] = [0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5];
67
68
69macro_rules! BROTLI_LOG_UINT (
70 ($num : expr) => {
71 xprintln!("{:?} = {:?}", stringify!($num), $num)
72 };
73);
74
75macro_rules! BROTLI_LOG (
76 ($str : expr, $num : expr) => {xprintln!("{:?} {:?}", $str, $num);};
77 ($str : expr, $num0 : expr, $num1 : expr) => {xprintln!("{:?} {:?} {:?}", $str, $num0, $num1);};
78 ($str : expr, $num0 : expr, $num1 : expr, $num2 : expr) => {
79 xprintln!("{:?} {:?} {:?} {:?}", $str, $num0, $num1, $num2);
80 };
81 ($str : expr, $num0 : expr, $num1 : expr, $num2 : expr, $num3 : expr) => {
82 xprintln!("{:?} {:?} {:?} {:?} {:?}", $str, $num0, $num1, $num2, $num3);
83 };
84);
85fn is_fatal(e: BrotliDecoderErrorCode) -> bool {
86 (e as i64) < 0
87}
88fn assign_error_code(output: &mut BrotliDecoderErrorCode, input: BrotliDecoderErrorCode) -> BrotliDecoderErrorCode {
89 *output = input;
90 input
91}
92
93#[allow(non_snake_case)]
94macro_rules! SaveErrorCode {
95 ($state: expr, $e:expr) => {
96 match assign_error_code(&mut $state.error_code, $e) {
97 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS =>
98 BrotliResult::ResultSuccess,
99 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT =>
100 BrotliResult::NeedsMoreInput,
101 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT =>
102 BrotliResult::NeedsMoreOutput,
103 _ =>
104 BrotliResult::ResultFailure,
105 }
106 }
107}
108macro_rules! SaveResult {
109 ($state: expr, $e:expr) => {
110 match ($state.error_code = match $e {
111 BrotliResult::ResultSuccess => BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS,
112 BrotliResult::NeedsMoreInput => BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT,
113 BrotliResult::NeedsMoreOutput => BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT,
114 BrotliResult::ResultFailure => BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE,
115 }) {
116 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS =>
117 BrotliResult::ResultSuccess,
118 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT =>
119 BrotliResult::NeedsMoreInput,
120 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT =>
121 BrotliResult::NeedsMoreOutput,
122 _ =>
123 BrotliResult::ResultFailure,
124 }
125 }
126}
127macro_rules! BROTLI_LOG_ARRAY_INDEX (
128 ($array : expr, $index : expr) => {
129 xprintln!("{:?}[{:?}] = {:?}", stringify!($array), $index, $array[$index as usize])
130 };
131);
132
133
134const NUM_DISTANCE_SHORT_CODES: u32 = 16;
135pub const BROTLI_MAX_DISTANCE_BITS:u32 = 24;
136
137pub const BROTLI_LARGE_MAX_DISTANCE_BITS: u32 = 62;
138
139pub fn BROTLI_DISTANCE_ALPHABET_SIZE(NPOSTFIX: u32, NDIRECT:u32, MAXNBITS: u32) -> u32 {
140 NUM_DISTANCE_SHORT_CODES + (NDIRECT) +
141 ((MAXNBITS) << ((NPOSTFIX) + 1))
142}
143
144pub use state::BrotliState;
149fn DecodeWindowBits(s_large_window: &mut bool,
158 s_window_bits:&mut u32,
159 br: &mut bit_reader::BrotliBitReader) -> BrotliDecoderErrorCode {
160 let mut n: u32 = 0;
161 let large_window = *s_large_window;
162 *s_large_window = false;
163 bit_reader::BrotliTakeBits(br, 1, &mut n);
164 if (n == 0) {
165 *s_window_bits = 16;
166 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
167 }
168 bit_reader::BrotliTakeBits(br, 3, &mut n);
169 if (n != 0) {
170 *s_window_bits = 17 + n;
171 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
172 }
173 bit_reader::BrotliTakeBits(br, 3, &mut n);
174 if (n == 1) {
175 if (large_window) {
176 bit_reader::BrotliTakeBits(br, 1, &mut n);
177 if (n == 1) {
178 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
179 }
180 *s_large_window = true;
181 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
182 } else {
183 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
184 }
185 }
186 if (n != 0) {
187 *s_window_bits = 8 + n;
188 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
189 }
190 *s_window_bits = 17;
191 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
192}
193
194
195#[cold]
196fn mark_unlikely() {}
197
198fn DecodeVarLenUint8(substate_decode_uint8: &mut state::BrotliRunningDecodeUint8State,
199 mut br: &mut bit_reader::BrotliBitReader,
200 value: &mut u32,
201 input: &[u8])
202 -> BrotliDecoderErrorCode {
203 let mut bits: u32 = 0;
204 loop {
205 match *substate_decode_uint8 {
206 BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_NONE => {
207 if !bit_reader::BrotliSafeReadBits(&mut br, 1, &mut bits, input) {
208 mark_unlikely();
209 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
210 }
211 if (bits == 0) {
212 *value = 0;
213 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
214 }
215 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_SHORT;
216 }
218 BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_SHORT => {
219 if !bit_reader::BrotliSafeReadBits(&mut br, 3, &mut bits, input) {
220 mark_unlikely();
221 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_SHORT;
222 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
223 }
224 if (bits == 0) {
225 *value = 1;
226 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_NONE;
227 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
228 }
229 *value = bits;
231 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_LONG;
233 }
234 BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_LONG => {
235 if !bit_reader::BrotliSafeReadBits(&mut br, *value, &mut bits, input) {
236 mark_unlikely();
237 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_LONG;
238 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
239 }
240 *value = (1u32 << *value) + bits;
241 *substate_decode_uint8 = BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_NONE;
242 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
243 }
244 }
245 }
246}
247
248fn DecodeMetaBlockLength<AllocU8: alloc::Allocator<u8>,
249 AllocU32: alloc::Allocator<u32>,
250 AllocHC: alloc::Allocator<HuffmanCode>>
251 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
252 input: &[u8])
253 -> BrotliDecoderErrorCode {
254 let mut bits: u32 = 0;
255 loop {
256 match s.substate_metablock_header {
257 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE => {
258 if !bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input) {
259 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
260 }
261 s.is_last_metablock = bits as u8;
262 s.meta_block_remaining_len = 0;
263 s.is_uncompressed = 0;
264 s.is_metadata = 0;
265 if (s.is_last_metablock == 0) {
266 s.substate_metablock_header =
267 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
268 continue;
269 }
270 s.substate_metablock_header =
271 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_EMPTY;
272 }
274 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_EMPTY => {
275 if !bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input) {
276 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
277 }
278 if bits != 0 {
279 s.substate_metablock_header =
280 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE;
281 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
282 }
283 s.substate_metablock_header =
284 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
285 }
287 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NIBBLES => {
288 if !bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut bits, input) {
289 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
290 }
291 s.size_nibbles = (bits + 4) as u8;
292 s.loop_counter = 0;
293 if (bits == 3) {
294 s.is_metadata = 1;
295 s.substate_metablock_header =
296 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_RESERVED;
297 continue;
298 }
299 s.substate_metablock_header =
300 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_SIZE;
301 }
304 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_SIZE => {
305 let mut i = s.loop_counter;
306 while i < s.size_nibbles as i32 {
307 if !bit_reader::BrotliSafeReadBits(&mut s.br, 4, &mut bits, input) {
308 s.loop_counter = i;
309 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
310 }
311 if (i + 1 == s.size_nibbles as i32 && s.size_nibbles > 4 && bits == 0) {
312 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE;
313 }
314 s.meta_block_remaining_len |= (bits << (i * 4)) as i32;
315 i += 1;
316 }
317 s.substate_metablock_header =
318 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED;
319 }
321 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED => {
322 if (s.is_last_metablock == 0 && s.is_metadata == 0) {
323 if !bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input) {
324 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
325 }
326 s.is_uncompressed = bits as u8;
327 }
328 s.meta_block_remaining_len += 1;
329 s.substate_metablock_header =
330 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE;
331 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
332 }
333 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_RESERVED => {
334 if !bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input) {
335 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
336 }
337 if (bits != 0) {
338 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_RESERVED;
339 }
340 s.substate_metablock_header =
341 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_BYTES;
342 }
344 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_BYTES => {
345 if !bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut bits, input) {
346 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
347 }
348 if (bits == 0) {
349 s.substate_metablock_header =
350 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE;
351 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
352 }
353 s.size_nibbles = bits as u8;
354 s.substate_metablock_header =
355 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_METADATA;
356 }
358 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_METADATA => {
359 let mut i = s.loop_counter;
360 while i < s.size_nibbles as i32 {
361 if !bit_reader::BrotliSafeReadBits(&mut s.br, 8, &mut bits, input) {
362 s.loop_counter = i;
363 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
364 }
365 if (i + 1 == s.size_nibbles as i32 && s.size_nibbles > 1 && bits == 0) {
366 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE;
367 }
368 s.meta_block_remaining_len |= (bits << (i * 8)) as i32;
369 i += 1;
370 }
371 s.substate_metablock_header =
372 BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED;
373 continue;
374 }
375 }
376 }
377}
378#[inline(always)]
383fn DecodeSymbol<T: HuffmanTable + ?Sized>(bits: u32, table: &T, br: &mut bit_reader::BrotliBitReader) -> u32 {
384 let mut table_index = bits & HUFFMAN_TABLE_MASK;
385 let mut table_element = table.entry(table_index as usize);
386 if table_element.bits > HUFFMAN_TABLE_BITS as u8 {
387 mark_unlikely();
388 let nbits = table_element.bits - HUFFMAN_TABLE_BITS as u8;
389 bit_reader::BrotliDropBits(br, HUFFMAN_TABLE_BITS);
390 table_index += table_element.value as u32;
391 let ext_idx = (table_index
392 + ((bits >> HUFFMAN_TABLE_BITS)
393 & bit_reader::BitMask(nbits as u32))) as usize;
394 table_element = table.entry(ext_idx);
395 }
396 bit_reader::BrotliDropBits(br, table_element.bits as u32);
397 table_element.value as u32
398}
399
400#[inline(always)]
403fn ReadSymbol<T: HuffmanTable + ?Sized>(table: &T, br: &mut bit_reader::BrotliBitReader, input: &[u8]) -> u32 {
404 DecodeSymbol(bit_reader::BrotliGet16BitsUnmasked(br, input), table, br)
405}
406
407#[cold]
410fn SafeDecodeSymbol<T: HuffmanTable + ?Sized>(table: &T,
411 mut br: &mut bit_reader::BrotliBitReader,
412 result: &mut u32)
413 -> bool {
414 let mut available_bits = bit_reader::BrotliGetAvailableBits(br);
415 if (available_bits == 0) {
416 let root0 = table.entry(0);
417 if (root0.bits == 0) {
418 *result = root0.value as u32;
419 return true;
420 }
421 return false; }
423 let mut val = bit_reader::BrotliGetBitsUnmasked(br) as u32;
424 let table_index = (val & HUFFMAN_TABLE_MASK) as usize;
425 let table_element = table.entry(table_index);
426 if (table_element.bits <= HUFFMAN_TABLE_BITS as u8) {
427 if (table_element.bits as u32 <= available_bits) {
428 bit_reader::BrotliDropBits(&mut br, table_element.bits as u32);
429 *result = table_element.value as u32;
430 return true;
431 } else {
432 return false; }
434 }
435 if (available_bits <= HUFFMAN_TABLE_BITS) {
436 return false; }
438
439 val = (val & bit_reader::BitMask(table_element.bits as u32)) >> HUFFMAN_TABLE_BITS;
441 available_bits -= HUFFMAN_TABLE_BITS;
442 let table_sub_element =
443 table.entry(table_index + table_element.value as usize + val as usize);
444 if (available_bits < table_sub_element.bits as u32) {
445 return false; }
447
448 bit_reader::BrotliDropBits(&mut br, HUFFMAN_TABLE_BITS + table_sub_element.bits as u32);
449 *result = table_sub_element.value as u32;
450 true
451}
452
453#[inline(always)]
454fn SafeReadSymbol<T: HuffmanTable + ?Sized>(table: &T,
455 br: &mut bit_reader::BrotliBitReader,
456 result: &mut u32,
457 input: &[u8])
458 -> bool {
459 let mut val: u32 = 0;
460 if (bit_reader::BrotliSafeGetBits(br, 15, &mut val, input)) {
461 *result = DecodeSymbol(val, table, br);
462 return true;
463 } else {
464 mark_unlikely();
465 }
466 SafeDecodeSymbol(table, br, result)
467}
468
469static EMPTY_LITERAL_TABLE: LiteralTable =
471 [HuffmanCode { value: 0, bits: 0 }; LITERAL_TABLE_WINDOW];
472static EMPTY_CONTEXT_TREES: [&'static LiteralTable; 64] = [&EMPTY_LITERAL_TABLE; 64];
473static EMPTY_DISTANCE_ROOT_TABLE: DistanceRootTable =
474 [HuffmanCode { value: 0, bits: 0 }; DISTANCE_ROOT_WINDOW];
475static EMPTY_DISTANCE_ROOTS: [&'static DistanceRootTable; 4] = [&EMPTY_DISTANCE_ROOT_TABLE; 4];
476
477#[inline(always)]
478fn decode_symbol_bits<T: HuffmanTable + ?Sized>(bits: u32, table: &T) -> (u32, u32) {
479 let table_index = (bits & HUFFMAN_TABLE_MASK) as usize;
480 let table_element = table.entry(table_index);
481 if table_element.bits > HUFFMAN_TABLE_BITS as u8 {
482 mark_unlikely();
483 let sub_idx = table_index
484 + table_element.value as usize
485 + (((bits & bit_reader::BitMask(table_element.bits as u32)) >> HUFFMAN_TABLE_BITS) as usize);
486 let sub = table.entry(sub_idx);
487 return (sub.value as u32, HUFFMAN_TABLE_BITS + (sub.bits as u32 & 7));
491 }
492 (table_element.value as u32, table_element.bits as u32)
493}
494
495#[inline(always)]
496fn decode_symbol_no_fill<T: HuffmanTable + ?Sized>(
497 fbr: &mut bit_reader::BitReaderSlice,
498 table: &T,
499) -> u32 {
500 let (sym, consumed) = decode_symbol_bits(fbr.val as u32, table);
501 fbr.avail_bits = fbr.avail_bits.wrapping_sub(consumed);
502 fbr.val >>= consumed & bit_reader::SLICE_SHIFT_MASK;
503 sym
504}
505
506#[inline(always)]
507fn read_symbol_slice<T: HuffmanTable + ?Sized>(
508 fbr: &mut bit_reader::BitReaderSlice,
509 table: &T,
510) -> u32 {
511 fbr.fill16();
512 decode_symbol_no_fill(fbr, table)
513}
514
515fn Log2Floor(mut x: u32) -> u32 {
516 let mut result: u32 = 0;
517 while x != 0 {
518 x >>= 1;
519 result += 1;
520 }
521 result
522}
523
524
525fn ReadSimpleHuffmanSymbols<AllocU8: alloc::Allocator<u8>,
530 AllocU32: alloc::Allocator<u32>,
531 AllocHC: alloc::Allocator<HuffmanCode>>
532 (alphabet_size: u32, max_symbol: u32,
533 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
534 input: &[u8])
535 -> BrotliDecoderErrorCode {
536
537 let max_bits = Log2Floor(alphabet_size - 1);
539 let mut i = s.sub_loop_counter;
540 let num_symbols = s.symbol;
541 for symbols_lists_item in fast_mut!((s.symbols_lists_array)[s.sub_loop_counter as usize;
542 num_symbols as usize + 1])
543 .iter_mut() {
544 let mut v: u32 = 0;
545 if !bit_reader::BrotliSafeReadBits(&mut s.br, max_bits, &mut v, input) {
546 mark_unlikely();
547 s.sub_loop_counter = i;
548 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_READ;
549 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
550 }
551 if (v >= max_symbol) {
552 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET;
553 }
554 *symbols_lists_item = v as u16;
555 BROTLI_LOG_UINT!(v);
556 i += 1;
557 }
558 i = 0;
559 for symbols_list_item in fast!((s.symbols_lists_array)[0; num_symbols as usize]).iter() {
560 for other_item in fast!((s.symbols_lists_array)[i as usize + 1 ; num_symbols as usize+ 1])
561 .iter() {
562 if (*symbols_list_item == *other_item) {
563 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME;
564 }
565 }
566 i += 1;
567 }
568 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
569}
570
571const SYMBOL_LISTS_OFFSET: usize = huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1;
577
578#[inline(always)]
586fn ProcessSingleCodeLength(code_len: u32,
587 symbol: &mut u32,
588 repeat: &mut u32,
589 space: &mut u32,
590 prev_code_len: &mut u32,
591 symbol_lists: &mut [u16; huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1 +
592 huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE],
593 code_length_histo: &mut [u16; 16],
594 next_symbol: &mut [i32; 32]) {
595 *repeat = 0;
596 if (code_len != 0) {
597 let cl = (code_len as usize) & 15;
600 let idx = (SYMBOL_LISTS_OFFSET as isize).wrapping_add(next_symbol[cl] as isize) as usize;
601 debug_assert!(idx < symbol_lists.len());
602 if let Some(slot) = symbol_lists.get_mut(idx) {
603 *slot = (*symbol) as u16;
604 }
605 next_symbol[cl] = (*symbol) as i32;
606 *prev_code_len = code_len;
607 *space = space.wrapping_sub(32768 >> code_len);
608 code_length_histo[cl] += 1;
609 BROTLI_LOG!("[ReadHuffmanCode] code_length[{:}]={:} histo[]={:}\n",
610 *symbol, code_len, code_length_histo[cl]);
611 }
612 (*symbol) += 1;
613}
614
615#[inline(always)]
625fn ProcessRepeatedCodeLength(code_len: u32,
626 mut repeat_delta: u32,
627 alphabet_size: u32,
628 symbol: &mut u32,
629 repeat: &mut u32,
630 space: &mut u32,
631 prev_code_len: &mut u32,
632 repeat_code_len: &mut u32,
633 symbol_lists: &mut [u16; huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1 +
634 huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE],
635 code_length_histo: &mut [u16; 16],
636 next_symbol: &mut [i32; 32]) {
637 let old_repeat: u32;
638 let extra_bits: u32;
639 let new_len: u32;
640 if (code_len == kCodeLengthRepeatCode) {
641 extra_bits = 2;
642 new_len = *prev_code_len
643 } else {
644 extra_bits = 3;
645 new_len = 0
646 }
647 if (*repeat_code_len != new_len) {
648 *repeat = 0;
649 *repeat_code_len = new_len;
650 }
651 old_repeat = *repeat;
652 if (*repeat > 0) {
653 *repeat -= 2;
654 *repeat <<= extra_bits;
655 }
656 *repeat += repeat_delta + 3;
657 repeat_delta = *repeat - old_repeat;
658 if (*symbol + repeat_delta > alphabet_size) {
659 *symbol = alphabet_size;
660 *space = 0xFFFFF;
661 return;
662 }
663 BROTLI_LOG!("[ReadHuffmanCode] code_length[{:}..{:}] = {:}\n",
664 *symbol, *symbol + repeat_delta - 1, *repeat_code_len);
665 if (*repeat_code_len != 0) {
666 let last: u32 = *symbol + repeat_delta;
667 let rcl = (*repeat_code_len as usize) & 15;
668 let mut next: i32 = next_symbol[rcl];
669 loop {
670 let idx = (SYMBOL_LISTS_OFFSET as isize).wrapping_add(next as isize) as usize;
671 debug_assert!(idx < symbol_lists.len());
672 if let Some(slot) = symbol_lists.get_mut(idx) {
673 *slot = (*symbol) as u16;
674 }
675 next = (*symbol) as i32;
676 (*symbol) += 1;
677 if *symbol == last {
678 break;
679 }
680 }
681 next_symbol[rcl] = next;
682 *space = space.wrapping_sub(repeat_delta << (15 - *repeat_code_len));
683 code_length_histo[rcl] = (code_length_histo[rcl] as u32 + repeat_delta) as u16;
684 } else {
685 *symbol += repeat_delta;
686 }
687}
688
689fn ReadSymbolCodeLengths<AllocU8: alloc::Allocator<u8>,
691 AllocU32: alloc::Allocator<u32>,
692 AllocHC: alloc::Allocator<HuffmanCode>>
693 (alphabet_size: u32,
694 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
695 input: &[u8])
696 -> BrotliDecoderErrorCode {
697
698 let mut symbol = s.symbol;
699 let mut repeat = s.repeat;
700 let mut space = s.space;
701 let mut prev_code_len: u32 = s.prev_code_len;
702 let mut repeat_code_len: u32 = s.repeat_code_len;
703 if (!bit_reader::BrotliWarmupBitReader(&mut s.br, input)) {
704 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
705 }
706 let mut br = match bit_reader::BitReaderSlice::new(&s.br, input) {
707 Some(r) => r,
708 None => return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE,
709 };
710 while (symbol < alphabet_size && space > 0) {
711 if br.avail_in() < bit_reader::BROTLI_SHORT_FILL_BIT_WINDOW_READ {
712 br.sync_to(&mut s.br);
713 s.symbol = symbol;
714 s.repeat = repeat;
715 s.prev_code_len = prev_code_len;
716 s.repeat_code_len = repeat_code_len;
717 s.space = space;
718 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
719 }
720 br.fill_short();
721 let p_index = (br.val as usize)
722 & ((1usize << huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH) - 1);
723 #[cfg(target_pointer_width = "64")]
724 let p = s.table[p_index];
725 #[cfg(not(target_pointer_width = "64"))]
726 let p = s.table[..].entry(p_index);
727 br.drop_bits(p.bits as u32); let code_len: u32 = p.value as u32; if (code_len < kCodeLengthRepeatCode) {
730 ProcessSingleCodeLength(code_len,
731 &mut symbol,
732 &mut repeat,
733 &mut space,
734 &mut prev_code_len,
735 &mut s.symbols_lists_array,
736 &mut s.code_length_histo,
737 &mut s.next_symbol);
738 } else {
739 let extra_bits: u32 = if code_len == kCodeLengthRepeatCode {
741 2
742 } else {
743 3
744 };
745 let repeat_delta: u32 = br.take_bits(extra_bits);
746 ProcessRepeatedCodeLength(code_len,
747 repeat_delta,
748 alphabet_size,
749 &mut symbol,
750 &mut repeat,
751 &mut space,
752 &mut prev_code_len,
753 &mut repeat_code_len,
754 &mut s.symbols_lists_array,
755 &mut s.code_length_histo,
756 &mut s.next_symbol);
757 }
758 }
759 br.sync_to(&mut s.br);
760 s.space = space;
761 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
762}
763
764fn SafeReadSymbolCodeLengths<AllocU8: alloc::Allocator<u8>,
765 AllocU32: alloc::Allocator<u32>,
766 AllocHC: alloc::Allocator<HuffmanCode>>
767 (alphabet_size: u32,
768 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
769 input: &[u8])
770 -> BrotliDecoderErrorCode {
771 while (s.symbol < alphabet_size && s.space > 0) {
772 let mut p_index = 0;
773 let code_len: u32;
774 let mut bits: u32 = 0;
775 let available_bits: u32 = bit_reader::BrotliGetAvailableBits(&s.br);
776 if (available_bits != 0) {
777 bits = bit_reader::BrotliGetBitsUnmasked(&s.br) as u32;
778 }
779 p_index += bits &
780 bit_reader::BitMask(huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH as u32);
781 #[cfg(target_pointer_width = "64")]
782 let p = fast!((s.table)[p_index as usize]);
783 #[cfg(not(target_pointer_width = "64"))]
784 let p = s.table[..].entry(p_index as usize);
785 if (p.bits as u32 > available_bits) {
786 if (!bit_reader::BrotliPullByte(&mut s.br, input)) {
788 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
789 }
790 continue;
791 }
792 code_len = p.value as u32; if (code_len < kCodeLengthRepeatCode) {
794 bit_reader::BrotliDropBits(&mut s.br, p.bits as u32);
795 ProcessSingleCodeLength(code_len,
796 &mut s.symbol,
797 &mut s.repeat,
798 &mut s.space,
799 &mut s.prev_code_len,
800 &mut s.symbols_lists_array,
801 &mut s.code_length_histo,
802 &mut s.next_symbol);
803 } else {
804 let extra_bits: u32 = code_len - 14;
806 let repeat_delta: u32 = (bits >> p.bits) & bit_reader::BitMask(extra_bits);
807 if (available_bits < p.bits as u32 + extra_bits) {
808 if (!bit_reader::BrotliPullByte(&mut s.br, input)) {
810 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
811 }
812 continue;
813 }
814 bit_reader::BrotliDropBits(&mut s.br, p.bits as u32 + extra_bits);
815 ProcessRepeatedCodeLength(code_len,
816 repeat_delta,
817 alphabet_size,
818 &mut s.symbol,
819 &mut s.repeat,
820 &mut s.space,
821 &mut s.prev_code_len,
822 &mut s.repeat_code_len,
823 &mut s.symbols_lists_array,
824 &mut s.code_length_histo,
825 &mut s.next_symbol);
826 }
827 }
828 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
829}
830
831fn ReadCodeLengthCodeLengths<AllocU8: alloc::Allocator<u8>,
834 AllocU32: alloc::Allocator<u32>,
835 AllocHC: alloc::Allocator<HuffmanCode>>
836 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
837 input: &[u8])
838 -> BrotliDecoderErrorCode {
839
840 let mut num_codes: u32 = s.repeat;
841 let mut space: u32 = s.space;
842 let mut i = s.sub_loop_counter;
843 for code_length_code_order in
844 fast!((kCodeLengthCodeOrder)[s.sub_loop_counter as usize; CODE_LENGTH_CODES]).iter() {
845 let code_len_idx = *code_length_code_order;
846 let mut ix: u32 = 0;
847
848 if !bit_reader::BrotliSafeGetBits(&mut s.br, 4, &mut ix, input) {
849 mark_unlikely();
850 let available_bits: u32 = bit_reader::BrotliGetAvailableBits(&s.br);
851 if (available_bits != 0) {
852 ix = bit_reader::BrotliGetBitsUnmasked(&s.br) as u32 & 0xF;
853 } else {
854 ix = 0;
855 }
856 if (fast!((kCodeLengthPrefixLength)[ix as usize]) as u32 > available_bits) {
857 s.sub_loop_counter = i;
858 s.repeat = num_codes;
859 s.space = space;
860 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_COMPLEX;
861 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
862 }
863 }
864 BROTLI_LOG_UINT!(ix);
865 let v: u32 = fast!((kCodeLengthPrefixValue)[ix as usize]) as u32;
866 bit_reader::BrotliDropBits(&mut s.br,
867 fast!((kCodeLengthPrefixLength)[ix as usize]) as u32);
868 fast_mut!((s.code_length_code_lengths)[code_len_idx as usize]) = v as u8;
869 BROTLI_LOG_ARRAY_INDEX!(s.code_length_code_lengths, code_len_idx);
870 if v != 0 {
871 space = space.wrapping_sub(32 >> v);
872 num_codes += 1;
873 fast_mut!((s.code_length_histo)[v as usize]) += 1;
874 if space.wrapping_sub(1) >= 32 {
875 break;
877 }
878 }
879 i += 1;
880 }
881 if (!(num_codes == 1 || space == 0)) {
882 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_CL_SPACE;
883 }
884 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
885}
886
887
888fn ReadHuffmanCode<AllocU8: alloc::Allocator<u8>,
901 AllocU32: alloc::Allocator<u32>,
902 AllocHC: alloc::Allocator<HuffmanCode>>
903 (mut alphabet_size: u32,
904 max_symbol: u32,
905 table: &mut [HuffmanCode],
906 offset: usize,
907 opt_table_size: Option<&mut u32>,
908 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
909 input: &[u8])
910 -> BrotliDecoderErrorCode {
911 if offset > table.len() {
912 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE;
913 }
914 alphabet_size &= 0x7ff;
916 loop {
918 match s.substate_huffman {
919 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_NONE => {
920 if !bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut s.sub_loop_counter, input) {
921 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
922 }
923
924 BROTLI_LOG_UINT!(s.sub_loop_counter);
925 if (s.sub_loop_counter != 1) {
929 s.space = 32;
930 s.repeat = 0; let max_code_len_len = huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH as usize + 1;
932 for code_length_histo in fast_mut!((s.code_length_histo)[0;max_code_len_len]).iter_mut() {
933 *code_length_histo = 0; }
935 for code_length_code_length in s.code_length_code_lengths[..].iter_mut() {
936 *code_length_code_length = 0;
937 }
938 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_COMPLEX;
939 continue;
941 }
942 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
943 }
945 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_SIZE => {
946 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut s.symbol, input)) {
948 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
950 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
951 }
952 s.sub_loop_counter = 0;
953 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_READ;
955 }
956 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_READ => {
957 let result = ReadSimpleHuffmanSymbols(alphabet_size, max_symbol, s, input);
958 match result {
959 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
960 _ => return result,
961 }
962 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
964 }
965 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_BUILD => {
966 let table_size: u32;
967 if (s.symbol == 3) {
968 let mut bits: u32 = 0;
969 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input)) {
970 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
971 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
972 }
973 s.symbol += bits;
974 }
975 BROTLI_LOG_UINT!(s.symbol);
976 table_size = huffman::BrotliBuildSimpleHuffmanTable(&mut table[offset..],
977 HUFFMAN_TABLE_BITS as i32,
978 &s.symbols_lists_array[..],
979 s.symbol);
980 if table_size == 0 {
981 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE;
982 }
983 if let Some(opt_table_size_ref) = opt_table_size {
984 *opt_table_size_ref = table_size
985 }
986 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_NONE;
987 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
988 }
989
990 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_COMPLEX => {
992
993 let result = ReadCodeLengthCodeLengths(s, input);
994 match result {
995 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
996 _ => return result,
997 }
998 if !huffman::BrotliBuildCodeLengthsHuffmanTable(
999 &mut s.table,
1000 &s.code_length_code_lengths,
1001 &s.code_length_histo,
1002 ) {
1003 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE;
1004 }
1005 for code_length_histo in s.code_length_histo.iter_mut() {
1006 *code_length_histo = 0;
1007 }
1008
1009 let max_code_length = huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH as usize + 1;
1010 for (i, next_symbol_mut) in s.next_symbol[..max_code_length]
1011 .iter_mut()
1012 .enumerate() {
1013 *next_symbol_mut = i as i32 - (max_code_length as i32);
1014 }
1015 for symbol_list in s.symbols_lists_array[..max_code_length].iter_mut() {
1016 *symbol_list = 0xFFFF;
1017 }
1018
1019 s.symbol = 0;
1020 s.prev_code_len = kDefaultCodeLength;
1021 s.repeat = 0;
1022 s.repeat_code_len = 0;
1023 s.space = 32768;
1024 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
1026 }
1027 BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS => {
1028 let table_size: u32;
1029 let mut result = ReadSymbolCodeLengths(max_symbol, s, input);
1030 if let BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT = result {
1031 result = SafeReadSymbolCodeLengths(max_symbol, s, input)
1032 }
1033 match result {
1034 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1035 _ => return result,
1036 }
1037
1038 if (s.space != 0) {
1039 BROTLI_LOG!("[ReadHuffmanCode] space = %d\n", s.space);
1040 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE;
1041 }
1042 table_size = huffman::BrotliBuildHuffmanTable(fast_mut!((table)[offset;]),
1046 HUFFMAN_TABLE_BITS as i32,
1047 &s.symbols_lists_array[..],
1048 s.symbol_lists_index,
1049 &mut s.code_length_histo);
1050 if table_size == 0 {
1051 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE;
1052 }
1053 if let Some(opt_table_size_ref) = opt_table_size {
1054 *opt_table_size_ref = table_size
1055 }
1056 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_NONE;
1057 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1058 }
1059 }
1060 }
1061}
1062
1063#[inline(always)]
1065fn ReadBlockLength(table: &[HuffmanCode],
1066 br: &mut bit_reader::BrotliBitReader,
1067 input: &[u8])
1068 -> u32 {
1069 let code = ReadSymbol(table, br, input);
1070 let p = &prefix::kBlockLengthPrefixCode[code as usize & 31];
1071 let nbits = p.nbits as u32; p.offset as u32 + bit_reader::BrotliReadBits(br, nbits, input)
1073}
1074
1075
1076fn SafeReadBlockLengthIndex(substate_read_block_length: &state::BrotliRunningReadBlockLengthState,
1079 block_length_index: u32,
1080 table: &[HuffmanCode],
1081 mut br: &mut bit_reader::BrotliBitReader,
1082 input: &[u8])
1083 -> (bool, u32) {
1084 match *substate_read_block_length {
1085 state::BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_NONE => {
1086 let mut index: u32 = 0;
1087 if (!SafeReadSymbol(table, &mut br, &mut index, input)) {
1088 return (false, 0);
1089 }
1090 (true, index)
1091 }
1092 _ => (true, block_length_index),
1093 }
1094}
1095fn SafeReadBlockLengthFromIndex<
1096 AllocHC : alloc::Allocator<HuffmanCode> >(s : &mut BlockTypeAndLengthState<AllocHC>,
1097 br : &mut bit_reader::BrotliBitReader,
1098 result : &mut u32,
1099 res_index : (bool, u32),
1100 input : &[u8]) -> bool{
1101 let (res, index) = res_index;
1102 if !res {
1103 return false;
1104 }
1105 let mut bits: u32 = 0;
1106 let p = &prefix::kBlockLengthPrefixCode[index as usize & 31];
1107 let nbits = p.nbits; if (!bit_reader::BrotliSafeReadBits(br, nbits as u32, &mut bits, input)) {
1109 s.block_length_index = index;
1110 s.substate_read_block_length =
1111 state::BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX;
1112 return false;
1113 }
1114 *result = p.offset as u32 + bits;
1115 s.substate_read_block_length =
1116 state::BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
1117 true
1118}
1119macro_rules! SafeReadBlockLength (
1120 ($state : expr, $result : expr , $table : expr) => {
1121 SafeReadBlockLengthFromIndex(&mut $state, &mut $result,
1122 SafeReadBlockLengthIndex($state.substate_read_block_length,
1123 $state.block_length_index,
1124 $table,
1125 &mut $state.br))
1126 };
1127);
1128
1129fn InverseMoveToFrontTransform(v: &mut [u8],
1145 v_len: u32,
1146 mtf: &mut [u8;256],
1147 mtf_upper_bound: &mut u32) {
1148 let upper_bound = (*mtf_upper_bound as usize).min(255);
1150 for (i, item) in mtf[..=upper_bound].iter_mut().enumerate() {
1151 *item = i as u8;
1152 }
1153
1154 let mut new_upper_bound: u32 = 0;
1156 for v_i in fast_mut!((v)[0usize ; (v_len as usize)]).iter_mut() {
1157 let mut index = (*v_i) as usize;
1158 let value = mtf[index];
1159 new_upper_bound |= index as u32;
1160 *v_i = value;
1161 while index > 0 {
1162 mtf[index & 0xff] = mtf[(index - 1) & 0xff];
1163 index -= 1;
1164 }
1165 mtf[0] = value;
1166 }
1167 *mtf_upper_bound = new_upper_bound;
1169}
1170fn HuffmanTreeGroupDecode<AllocU8: alloc::Allocator<u8>,
1172 AllocU32: alloc::Allocator<u32>,
1173 AllocHC: alloc::Allocator<HuffmanCode>>
1174 (group_index: i32,
1175 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1176 input: &[u8])
1177 -> BrotliDecoderErrorCode {
1178 let mut hcodes: AllocHC::AllocatedMemory;
1179 let mut htrees: AllocU32::AllocatedMemory;
1180 let alphabet_size: u16;
1181 let group_num_htrees: u16;
1182 let group_max_symbol;
1183 if group_index == 0 {
1184 hcodes = mem::replace(&mut s.literal_hgroup.codes,
1185 AllocHC::AllocatedMemory::default());
1186 htrees = mem::replace(&mut s.literal_hgroup.htrees,
1187 AllocU32::AllocatedMemory::default());
1188 group_num_htrees = s.literal_hgroup.num_htrees;
1189 alphabet_size = s.literal_hgroup.alphabet_size;
1190 group_max_symbol = s.literal_hgroup.max_symbol;
1191 } else if group_index == 1 {
1192 hcodes = mem::replace(&mut s.insert_copy_hgroup.codes,
1193 AllocHC::AllocatedMemory::default());
1194 htrees = mem::replace(&mut s.insert_copy_hgroup.htrees,
1195 AllocU32::AllocatedMemory::default());
1196 group_num_htrees = s.insert_copy_hgroup.num_htrees;
1197 alphabet_size = s.insert_copy_hgroup.alphabet_size;
1198 group_max_symbol = s.insert_copy_hgroup.max_symbol;
1199 } else {
1200 if group_index != 2 {
1201 let ret = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
1202 SaveErrorCode!(s, ret);
1203 return ret;
1204 }
1205 hcodes = mem::replace(&mut s.distance_hgroup.codes,
1206 AllocHC::AllocatedMemory::default());
1207 htrees = mem::replace(&mut s.distance_hgroup.htrees,
1208 AllocU32::AllocatedMemory::default());
1209 group_num_htrees = s.distance_hgroup.num_htrees;
1210 alphabet_size = s.distance_hgroup.alphabet_size;
1211 group_max_symbol = s.distance_hgroup.max_symbol;
1212 }
1213 match s.substate_tree_group {
1214 BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_NONE => {
1215 s.htree_next_offset = 0;
1216 s.htree_index = 0;
1217 s.substate_tree_group = BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_LOOP;
1218 }
1219 BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_LOOP => {}
1220 }
1221 let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1222 let max_table_size = huffman::BrotliHuffmanMaxTableSize(alphabet_size.max(group_max_symbol));
1226 for htree_iter in
1227 fast_mut!((htrees.slice_mut())[s.htree_index as usize ; (group_num_htrees as usize)])
1228 .iter_mut() {
1229 let room_needed = s.htree_next_offset as usize + max_table_size;
1232 if hcodes.slice().len() < room_needed && !EnsureBlockTrees(&mut s) {
1233 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES;
1234 break;
1235 }
1236 if !huffman::ensure_codes_room(&mut hcodes, &mut s.alloc_hc, s.htree_next_offset as usize,
1237 max_table_size) {
1238 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS;
1239 break;
1240 }
1241 let mut table_size: u32 = 0;
1242 result = ReadHuffmanCode(u32::from(alphabet_size), u32::from(group_max_symbol),
1243 hcodes.slice_mut(),
1244 s.htree_next_offset as usize,
1245 Some(&mut table_size),
1246 &mut s,
1247 input);
1248 match result {
1249 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1250 _ => break, }
1252 *htree_iter = s.htree_next_offset;
1253 s.htree_next_offset += table_size;
1254 s.htree_index += 1;
1255 }
1256 if group_index == 0 {
1257 let _ = mem::replace(&mut s.literal_hgroup.codes,
1258 mem::replace(&mut hcodes, AllocHC::AllocatedMemory::default()));
1259 let _ = mem::replace(&mut s.literal_hgroup.htrees,
1260 mem::replace(&mut htrees, AllocU32::AllocatedMemory::default()));
1261 } else if group_index == 1 {
1262 let _ = mem::replace(&mut s.insert_copy_hgroup.codes,
1263 mem::replace(&mut hcodes, AllocHC::AllocatedMemory::default()));
1264 let _ = mem::replace(&mut s.insert_copy_hgroup.htrees,
1265 mem::replace(&mut htrees, AllocU32::AllocatedMemory::default()));
1266 } else {
1267 let _ = mem::replace(&mut s.distance_hgroup.codes,
1268 mem::replace(&mut hcodes, AllocHC::AllocatedMemory::default()));
1269 let _ = mem::replace(&mut s.distance_hgroup.htrees,
1270 mem::replace(&mut htrees, AllocU32::AllocatedMemory::default()));
1271 }
1272 if let BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS = result {
1273 s.substate_tree_group = BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_NONE
1274 }
1275 result
1276}
1277#[allow(dead_code)]
1278pub fn lg_window_size(first_byte: u8, second_byte: u8) -> Result<(u8, u8), ()> {
1279 if first_byte & 1 == 0 {
1280 return Ok((16, 1));
1281 }
1282 match first_byte & 15 {
1283 0x3 => return Ok((18, 4)),
1284 0x5 => return Ok((19, 4)),
1285 0x7 => return Ok((20, 4)),
1286 0x9 => return Ok((21, 4)),
1287 0xb => return Ok((22, 4)),
1288 0xd => return Ok((23, 4)),
1289 0xf => return Ok((24, 4)),
1290 _ => match first_byte & 127 {
1291 0x71 => return Ok((15, 7)),
1292 0x61 => return Ok((14, 7)),
1293 0x51 => return Ok((13, 7)),
1294 0x41 => return Ok((12, 7)),
1295 0x31 => return Ok((11, 7)),
1296 0x21 => return Ok((10, 7)),
1297 0x1 => return Ok((17, 7)),
1298 _ => {},
1299 }
1300 }
1301 if (first_byte & 0x80) != 0 {
1302 return Err(());
1303 }
1304 let ret = second_byte & 0x3f;
1305 if ret < 10 || ret > 30 {
1306 return Err(());
1307 }
1308 Ok((ret, 14))
1309
1310}
1311
1312
1313fn bzero(data: &mut [u8]) {
1314 for iter in data.iter_mut() {
1315 *iter = 0;
1316 }
1317}
1318
1319
1320fn DecodeContextMapInner<AllocU8: alloc::Allocator<u8>,
1330 AllocU32: alloc::Allocator<u32>,
1331 AllocHC: alloc::Allocator<HuffmanCode>>
1332 (context_map_size: u32,
1333 num_htrees: &mut u32,
1334 context_map_arg: &mut AllocU8::AllocatedMemory,
1335 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1336 input: &[u8])
1337 -> BrotliDecoderErrorCode {
1338
1339 let mut result;
1340 loop {
1341 match s.substate_context_map {
1342 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_NONE => {
1343 result = DecodeVarLenUint8(&mut s.substate_decode_uint8, &mut s.br, num_htrees, input);
1344 match result {
1345 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1346 _ => return result,
1347 }
1348 (*num_htrees) += 1;
1349 s.context_index = 0;
1350 BROTLI_LOG_UINT!(context_map_size);
1351 BROTLI_LOG_UINT!(*num_htrees);
1352 if context_map_arg.slice().len() < context_map_size as usize {
1353 s.alloc_u8.free_cell(core::mem::take(context_map_arg));
1354 *context_map_arg = s.alloc_u8.alloc_cell(context_map_size as usize);
1355 if (context_map_arg.slice().len() < context_map_size as usize) {
1356 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP;
1357 }
1358 }
1359 if (*num_htrees <= 1) {
1360 bzero(&mut context_map_arg.slice_mut()[..context_map_size as usize]);
1361 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1362 }
1363 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_READ_PREFIX;
1364 }
1366 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_READ_PREFIX => {
1367 let mut bits: u32 = 0;
1368 if (!bit_reader::BrotliSafeGetBits(&mut s.br, 5, &mut bits, input)) {
1371 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1372 }
1373 if ((bits & 1) != 0) {
1374 s.max_run_length_prefix = (bits >> 1) + 1;
1376 bit_reader::BrotliDropBits(&mut s.br, 5);
1377 } else {
1378 s.max_run_length_prefix = 0;
1379 bit_reader::BrotliDropBits(&mut s.br, 1);
1380 }
1381 BROTLI_LOG_UINT!(s.max_run_length_prefix);
1382 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_HUFFMAN;
1383 }
1385 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_HUFFMAN => {
1386 if !EnsureContextMapTable(s) {
1387 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP;
1388 }
1389 let mut local_context_map_table = mem::replace(&mut s.context_map_table,
1390 AllocHC::AllocatedMemory::default());
1391 let alphabet_size = *num_htrees + s.max_run_length_prefix;
1392 result = ReadHuffmanCode(alphabet_size, alphabet_size,
1393 &mut local_context_map_table.slice_mut(),
1394 0,
1395 None,
1396 &mut s,
1397 input);
1398 let _ = mem::replace(&mut s.context_map_table,
1399 mem::replace(&mut local_context_map_table,
1400 AllocHC::AllocatedMemory::default()));
1401 match result {
1402 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1403 _ => return result,
1404 }
1405 s.code = 0xFFFF;
1406 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_DECODE;
1407 }
1409 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_DECODE => {
1410 let mut context_index: u32 = s.context_index;
1411 let max_run_length_prefix: u32 = s.max_run_length_prefix;
1412 let context_map = &mut context_map_arg.slice_mut()[..context_map_size as usize];
1413 let context_map_table = s.context_map_table.slice();
1414 let mut code: u32 = s.code;
1415 let mut rleCodeGoto = (code != 0xFFFF);
1416 while (rleCodeGoto || context_index < context_map_size) {
1417 if !rleCodeGoto {
1418 if (!SafeReadSymbol(context_map_table, &mut s.br, &mut code, input)) {
1419 s.code = 0xFFFF;
1420 s.context_index = context_index;
1421 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1422 }
1423 BROTLI_LOG_UINT!(code);
1424
1425 if code == 0 {
1426 fast_mut!((context_map)[context_index as usize]) = 0;
1427 BROTLI_LOG_ARRAY_INDEX!(context_map, context_index as usize);
1428 context_index += 1;
1429 continue;
1430 }
1431 if code > max_run_length_prefix {
1432 fast_mut!((context_map)[context_index as usize]) =
1433 (code - max_run_length_prefix) as u8;
1434 BROTLI_LOG_ARRAY_INDEX!(context_map, context_index as usize);
1435 context_index += 1;
1436 continue;
1437 }
1438 }
1439 rleCodeGoto = false; {
1442 let mut reps: u32 = 0;
1443 if (!bit_reader::BrotliSafeReadBits(&mut s.br, code, &mut reps, input)) {
1444 s.code = code;
1445 s.context_index = context_index;
1446 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1447 }
1448 reps += 1u32 << code;
1449 BROTLI_LOG_UINT!(reps);
1450 if (context_index + reps > context_map_size) {
1451 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT;
1452 }
1453 for slot in context_map[context_index as usize..(context_index + reps) as usize].iter_mut() {
1454 *slot = 0;
1455 }
1456 context_index += reps;
1457 }
1458 }
1459 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
1461 }
1462 BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_TRANSFORM => {
1463 let mut bits: u32 = 0;
1464 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 1, &mut bits, input)) {
1465 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
1466 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1467 }
1468 if (bits != 0) {
1469 if let Ok(ref mut mtf) = s.mtf_or_error_string {
1470 InverseMoveToFrontTransform(context_map_arg.slice_mut(),
1471 context_map_size,
1472 mtf,
1473 &mut s.mtf_upper_bound);
1474 } else {
1475 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
1477 }
1478 }
1479 s.substate_context_map = BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_NONE;
1480 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1481 }
1482 }
1483 }
1484 }
1486
1487fn DecodeContextMap<AllocU8: alloc::Allocator<u8>,
1488 AllocU32: alloc::Allocator<u32>,
1489 AllocHC: alloc::Allocator<HuffmanCode>>
1490 (context_map_size: usize,
1491 is_dist_context_map: bool,
1492 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1493 input: &[u8])
1494 -> BrotliDecoderErrorCode {
1495
1496 match s.state {
1497 BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1 if !is_dist_context_map => {},
1498 BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2 if is_dist_context_map => {},
1499 _ => return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE,
1500 }
1501 let (mut num_htrees, mut context_map_arg) = if is_dist_context_map {
1502 (s.num_dist_htrees, mem::replace(&mut s.dist_context_map, AllocU8::AllocatedMemory::default()))
1503 } else {
1504 (s.num_literal_htrees, mem::replace(&mut s.context_map, AllocU8::AllocatedMemory::default()))
1505 };
1506
1507 let retval = DecodeContextMapInner(context_map_size as u32,
1508 &mut num_htrees,
1509 &mut context_map_arg,
1510 &mut s,
1511 input);
1512 if is_dist_context_map {
1513 s.num_dist_htrees = num_htrees;
1514 let _ = mem::replace(&mut s.dist_context_map,
1515 mem::replace(&mut context_map_arg, AllocU8::AllocatedMemory::default()));
1516 } else {
1517 s.num_literal_htrees = num_htrees;
1518 let _ = mem::replace(&mut s.context_map,
1519 mem::replace(&mut context_map_arg, AllocU8::AllocatedMemory::default()));
1520 }
1521 retval
1522}
1523
1524#[inline(always)]
1531fn DecodeBlockTypeAndLength<
1532 AllocHC : alloc::Allocator<HuffmanCode>> (safe : bool,
1533 s : &mut BlockTypeAndLengthState<AllocHC>,
1534 br : &mut bit_reader::BrotliBitReader,
1535 tree_type : i32,
1536 input : &[u8]) -> BrotliDecoderErrorCode {
1537 let max_block_type = fast!((s.num_block_types)[tree_type as usize]);
1538 let type_tree_offset = tree_type as usize * huffman::BROTLI_HUFFMAN_MAX_SIZE_258 as usize;
1539 let len_tree_offset = tree_type as usize * huffman::BROTLI_HUFFMAN_MAX_SIZE_26 as usize;
1540
1541 let mut block_type: u32 = 0;
1542 if max_block_type <= 1 {
1543 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH;
1544 }
1545 if (!safe) {
1547 block_type = ReadSymbol(fast_slice!((s.block_type_trees)[type_tree_offset;]), br, input);
1548 fast_mut!((s.block_length)[tree_type as usize]) =
1549 ReadBlockLength(fast_slice!((s.block_len_trees)[len_tree_offset;]), br, input);
1550 } else {
1551 let memento = bit_reader::BrotliBitReaderSaveState(br);
1552 if (!SafeReadSymbol(fast_slice!((s.block_type_trees)[type_tree_offset;]),
1553 br,
1554 &mut block_type,
1555 input)) {
1556 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1557 }
1558 let mut block_length_out: u32 = 0;
1559
1560 let index_ret = SafeReadBlockLengthIndex(&s.substate_read_block_length,
1561 s.block_length_index,
1562 fast_slice!((s.block_len_trees)[len_tree_offset;]),
1563 br,
1564 input);
1565 if !SafeReadBlockLengthFromIndex(s, br, &mut block_length_out, index_ret, input) {
1566 s.substate_read_block_length =
1567 BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
1568 bit_reader::BrotliBitReaderRestoreState(br, &memento);
1569 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1570 }
1571 fast_mut!((s.block_length)[tree_type as usize]) = block_length_out;
1572 }
1573 let rb_idx = (tree_type as usize & 3) * 2;
1574 let rb0 = s.block_type_rb[rb_idx];
1575 let rb1 = s.block_type_rb[rb_idx + 1];
1576 if (block_type == 1) {
1577 block_type = rb1 + 1;
1578 } else if (block_type == 0) {
1579 block_type = rb0;
1580 } else {
1581 block_type -= 2;
1582 }
1583 if (block_type >= max_block_type) {
1584 block_type -= max_block_type;
1585 }
1586 s.block_type_rb[rb_idx] = rb1;
1587 s.block_type_rb[rb_idx + 1] = block_type;
1588 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
1589}
1590fn DetectTrivialLiteralBlockTypes<AllocU8: alloc::Allocator<u8>,
1591 AllocU32: alloc::Allocator<u32>,
1592 AllocHC: alloc::Allocator<HuffmanCode>>
1593 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>) {
1594 for current in s.trivial_literal_contexts.iter_mut() {
1595 *current = 0;
1596 }
1597 let num_block_types = fast!((s.block_type_length_state.num_block_types)[0]) as usize;
1598 let context_map = s.context_map.slice();
1599 for i in 0..num_block_types {
1600 let offset = i << kLiteralContextBits;
1601 if let Some(chunk) = context_map.get(offset..offset + (1usize << kLiteralContextBits)) {
1602 let sample = chunk[0];
1603 if chunk.iter().all(|&b| b == sample) {
1604 s.trivial_literal_contexts[i >> 5] |= 1u32 << (i & 31);
1605 }
1606 }
1607 }
1608}
1609#[inline(always)]
1610fn update_literal_block_state(
1611 block_type_rb: &[u32; 6],
1612 trivial_literal_contexts: &[u32; 8],
1613 context_map: &[u8],
1614 context_modes: &[u8],
1615 context_map_slice_index: &mut usize,
1616 trivial_literal_context: &mut i32,
1617 literal_htree_index: &mut u8,
1618 context_lookup: &mut &'static [u8; 512],
1619) {
1620 let block_type = fast!((block_type_rb)[1]) as usize;
1621 let context_offset = block_type << kLiteralContextBits;
1622 *context_map_slice_index = context_offset;
1623 let trivial = fast!((trivial_literal_contexts)[(block_type >> 5) & 7]);
1624 *trivial_literal_context = ((trivial >> (block_type & 31)) & 1) as i32;
1625 *literal_htree_index = fast!((context_map)[context_offset]);
1626 let context_mode_index = fast!((context_modes)[block_type]) & 3;
1627 *context_lookup = &kContextLookup[context_mode_index as usize];
1628}
1629
1630#[inline(always)]
1631fn PrepareLiteralDecoding<AllocU8: alloc::Allocator<u8>,
1632 AllocU32: alloc::Allocator<u32>,
1633 AllocHC: alloc::Allocator<HuffmanCode>>
1634 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>) {
1635 update_literal_block_state(
1636 &s.block_type_length_state.block_type_rb,
1637 &s.trivial_literal_contexts,
1638 s.context_map.slice(),
1639 s.context_modes.slice(),
1640 &mut s.context_map_slice_index,
1641 &mut s.trivial_literal_context,
1642 &mut s.literal_htree_index,
1643 &mut s.context_lookup,
1644 );
1645}
1646
1647fn UnwrittenBytes<AllocU8: alloc::Allocator<u8>,
1650 AllocU32: alloc::Allocator<u32>,
1651 AllocHC: alloc::Allocator<HuffmanCode>> (
1652 s: &BrotliState<AllocU8, AllocU32, AllocHC>,
1653 wrap: bool,
1654) -> u64 {
1655 debug_assert!(s.pos >= 0 && s.ringbuffer_size > 0);
1656 let ringbuffer_size = s.ringbuffer_size as u64;
1657 let pos = if wrap && s.pos > s.ringbuffer_size {
1658 ringbuffer_size
1659 } else {
1660 s.pos as u64
1661 };
1662 let partial_pos_rb = s.rb_roundtrips * ringbuffer_size + pos;
1663 debug_assert!(partial_pos_rb >= s.partial_pos_out);
1664 partial_pos_rb - s.partial_pos_out
1665}
1666
1667fn CheckRingBufferConsistency<AllocU8: alloc::Allocator<u8>,
1672 AllocU32: alloc::Allocator<u32>,
1673 AllocHC: alloc::Allocator<HuffmanCode>>(
1674 s: &BrotliState<AllocU8, AllocU32, AllocHC>,
1675) -> bool {
1676 s.pos >= 0 && s.ringbuffer_size > 0 && s.ringbuffer_mask >= 0 &&
1677 s.ringbuffer_mask as i64 + 1 == s.ringbuffer_size as i64 &&
1678 s.ringbuffer_size as usize <= s.ringbuffer.slice().len()
1679}
1680fn WriteRingBuffer<'a,
1681 AllocU8: alloc::Allocator<u8>,
1682 AllocU32: alloc::Allocator<u32>,
1683 AllocHC: alloc::Allocator<HuffmanCode>>(
1684 available_out: &mut usize,
1685 opt_output: Option<&mut [u8]>,
1686 output_offset: &mut usize,
1687 total_out: &mut usize,
1688 force: bool,
1689 s: &'a mut BrotliState<AllocU8, AllocU32, AllocHC>,
1690) -> (BrotliDecoderErrorCode, &'a [u8]) {
1691 if s.meta_block_remaining_len < 0 {
1692 return (BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1, &[]);
1693 }
1694 if !CheckRingBufferConsistency(s) {
1695 return (BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE, &[]);
1696 }
1697 debug_assert!(s.window_bits < 64);
1700 let window_size = 1i64 << (s.window_bits & 63);
1701 let to_write = UnwrittenBytes(s, true);
1702 let num_written = core::cmp::min(*available_out as u64, to_write) as usize;
1703 let start_index = (s.partial_pos_out & s.ringbuffer_mask as u64) as usize;
1704 let start = match s.ringbuffer.slice().get(start_index..start_index + num_written) {
1705 Some(start) => start,
1706 None => return (BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE, &[]),
1707 };
1708 let output_end = match (*output_offset).checked_add(num_written) {
1710 Some(output_end) => output_end,
1711 None => return (BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS, &[]),
1712 };
1713 if let Some(output) = opt_output {
1714 match output.get_mut(*output_offset..output_end) {
1715 Some(output_slice) => output_slice.clone_from_slice(start),
1716 None => return (BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS, &[]),
1717 }
1718 }
1719 *output_offset = output_end;
1720 *available_out -= num_written;
1721 BROTLI_LOG_UINT!(to_write);
1722 BROTLI_LOG_UINT!(num_written);
1723 s.partial_pos_out += num_written as u64;
1724 *total_out = s.partial_pos_out as usize;
1727 if (num_written as u64) < to_write {
1728 if s.ringbuffer_size as i64 == window_size || force {
1729 return (BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT, start);
1731 } else {
1732 return (BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS, start);
1733 }
1734 }
1735 if (s.ringbuffer_size as i64 == window_size &&
1736 s.pos >= s.ringbuffer_size) {
1737 s.pos -= s.ringbuffer_size;
1738 s.rb_roundtrips += 1;
1739 s.should_wrap_ringbuffer = s.pos != 0;
1740 }
1741 (BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS, start)
1742 }
1743
1744fn WrapRingBuffer<AllocU8: alloc::Allocator<u8>,
1745 AllocU32: alloc::Allocator<u32>,
1746 AllocHC: alloc::Allocator<HuffmanCode>>(
1747 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1748) -> bool {
1749 if s.should_wrap_ringbuffer {
1750 if s.ringbuffer_size < 0 || s.pos < 0 {
1751 return false;
1752 }
1753 let ringbuffer_size = s.ringbuffer_size as usize;
1754 let pos = s.pos as usize;
1755 let ringbuffer_len = s.ringbuffer.slice().len();
1756 if ringbuffer_size > ringbuffer_len ||
1763 pos > ringbuffer_size ||
1764 pos > ringbuffer_len - ringbuffer_size {
1765 return false;
1766 }
1767 let (ring_buffer_start, ring_buffer_end) =
1768 s.ringbuffer.slice_mut().split_at_mut(ringbuffer_size);
1769 ring_buffer_start[..pos].clone_from_slice(&ring_buffer_end[..pos]);
1770 s.should_wrap_ringbuffer = false;
1771 }
1772 true
1773}
1774
1775fn CopyUncompressedBlockToOutput<AllocU8: alloc::Allocator<u8>,
1776 AllocU32: alloc::Allocator<u32>,
1777 AllocHC: alloc::Allocator<HuffmanCode>>
1778 (mut available_out: &mut usize,
1779 mut output: &mut [u8],
1780 mut output_offset: &mut usize,
1781 mut total_out: &mut usize,
1782 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1783 input: &[u8])
1784 -> BrotliDecoderErrorCode {
1785 match BrotliEnsureRingBuffer(s,
1788 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1) {
1789 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1790 error => return error,
1791 }
1792 loop {
1794 match s.substate_uncompressed {
1795 BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_NONE => {
1796 let remaining = bit_reader::BrotliGetRemainingBytes(&s.br);
1797 let mut nbytes = core::cmp::min(remaining, s.meta_block_remaining_len as u32);
1798 nbytes = core::cmp::min(nbytes, (s.ringbuffer_size - s.pos) as u32);
1799 bit_reader::BrotliCopyBytes(fast_mut!((s.ringbuffer.slice_mut())[s.pos as usize;]),
1801 &mut s.br,
1802 nbytes,
1803 input);
1804 s.pos += nbytes as i32;
1805 s.meta_block_remaining_len -= nbytes as i32;
1806 if s.pos < (1 << s.window_bits) {
1807 if (s.meta_block_remaining_len == 0) {
1808 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
1809 }
1810 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
1811 }
1812 s.substate_uncompressed = BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_WRITE;
1813 }
1816 BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_WRITE => {
1817 let (result, _) = WriteRingBuffer(&mut available_out,
1818 Some(&mut output),
1819 &mut output_offset,
1820 &mut total_out,
1821 false,
1822 &mut s);
1823 match result {
1824 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1825 _ => return result,
1826 }
1827 if s.ringbuffer_size == 1 << s.window_bits {
1828 s.max_distance = s.max_backward_distance;
1829 }
1830 s.substate_uncompressed = BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_NONE;
1831 }
1832 }
1833 }
1834}
1835
1836const kRingBufferWriteAheadSlack: i32 =
1845 SHARED_BROTLI_MAX_TRANSFORM_AFFIX_LENGTH as i32 + (SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH as i32 + 1) + SHARED_BROTLI_MAX_TRANSFORM_AFFIX_LENGTH as i32; const _RING_BUFFER_SLACK_MATCHES_C: [(); 542] = [(); kRingBufferWriteAheadSlack as usize];
1850const kRingBufferAllocationSlack: usize =
1853 kRingBufferWriteAheadSlack as usize + kBrotliMaxDictionaryWordLength as usize;
1854const kRingBufferMinSize: i64 = 1024;
1858const kOneShotRingBufferGrowthFactor: i64 = 4;
1861const kSmallRingBufferMinSize: i64 = 32;
1868
1869fn BrotliCalculateRingBufferSize<AllocU8: alloc::Allocator<u8>,
1902 AllocU32: alloc::Allocator<u32>,
1903 AllocHC: alloc::Allocator<HuffmanCode>>
1904 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1905 input: &[u8]) {
1906 let window_size = 1i64 << (s.window_bits & 63);
1909 let mut new_ringbuffer_size = window_size;
1910 let fixed_pool = s.u8_pool_size != 0;
1911 let mut is_last = s.is_last_metablock != 0;
1913 if s.is_uncompressed != 0 && s.ringbuffer.slice().len() == 0 {
1914 let next_block_header =
1915 bit_reader::BrotliPeekByte(&mut s.br, s.meta_block_remaining_len as u32, input);
1916 if next_block_header != -1 && (next_block_header & 3) == 3 {
1919 is_last = true;
1920 }
1921 }
1922 let mut min_size = if s.ringbuffer_size != 0 {
1925 s.ringbuffer_size as i64
1926 } else if is_last {
1927 kSmallRingBufferMinSize
1928 } else if s.initial_ringbuffer_size != 0 {
1929 core::cmp::max(s.initial_ringbuffer_size as i64, kSmallRingBufferMinSize)
1932 } else if fixed_pool {
1933 kSmallRingBufferMinSize
1934 } else {
1935 kRingBufferMinSize
1936 };
1937
1938 if s.ringbuffer_size as i64 == window_size {
1940 return;
1941 }
1942
1943 if s.is_metadata != 0 {
1945 return;
1946 }
1947
1948 let mut output_size = if s.ringbuffer.slice().len() == 0 {
1951 0
1952 } else {
1953 s.pos as i64
1954 };
1955 output_size += s.meta_block_remaining_len as i64;
1956 if min_size < output_size {
1957 min_size = output_size;
1958 }
1959 if !is_last && s.one_shot_output_size != 0 {
1960 let hinted_size = core::cmp::min(s.one_shot_output_size as i64,
1961 output_size.saturating_mul(kOneShotRingBufferGrowthFactor));
1962 min_size = core::cmp::max(min_size, hinted_size);
1963 }
1964
1965 let pool_holds_window = fixed_pool &&
1968 s.u8_pool_size as u64 >= window_size as u64 + kRingBufferAllocationSlack as u64;
1969 if s.canny_ringbuffer_allocation && !(pool_holds_window && !is_last) {
1970 let min_size = core::cmp::max(min_size, 1);
1975 while (new_ringbuffer_size >> 1) >= min_size {
1976 new_ringbuffer_size >>= 1;
1977 }
1978 }
1979
1980 s.new_ringbuffer_size = if new_ringbuffer_size > 0 &&
1983 new_ringbuffer_size <= i32::MAX as i64 {
1984 new_ringbuffer_size as i32
1985 } else {
1986 0
1987 };
1988}
1989
1990fn BrotliEnsureRingBuffer<AllocU8: alloc::Allocator<u8>,
2004 AllocU32: alloc::Allocator<u32>,
2005 AllocHC: alloc::Allocator<HuffmanCode>>
2006 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2007 alloc_error: BrotliDecoderErrorCode)
2008 -> BrotliDecoderErrorCode {
2009 let new_size = s.new_ringbuffer_size;
2010 if s.ringbuffer_size == new_size && s.ringbuffer.slice().len() != 0 {
2011 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2012 }
2013 let pos = s.pos;
2020 if new_size < 2 || (new_size & (new_size - 1)) != 0 || pos < 0 || pos > new_size ||
2021 pos as usize > s.ringbuffer.slice().len() || s.rb_roundtrips != 0 {
2022 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
2023 }
2024 let size = new_size as usize;
2025 let decoded = pos as usize;
2026 let alloc_size = size + kRingBufferAllocationSlack;
2027
2028 let mut new_ringbuffer = s.alloc_u8.alloc_cell(alloc_size);
2029 if new_ringbuffer.slice().len() < alloc_size {
2030 s.alloc_u8.free_cell(new_ringbuffer);
2033 return alloc_error;
2034 }
2035 {
2036 let new_slice = new_ringbuffer.slice_mut();
2037 new_slice[size - 2] = 0;
2038 new_slice[size - 1] = 0;
2039 new_slice[..decoded].clone_from_slice(&s.ringbuffer.slice()[..decoded]);
2040 }
2041 let old_ringbuffer = mem::replace(&mut s.ringbuffer, new_ringbuffer);
2042 s.alloc_u8.free_cell(old_ringbuffer);
2043
2044 s.ringbuffer_size = new_size;
2045 s.ringbuffer_mask = new_size - 1;
2046 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
2047}
2048
2049fn EnsureCompoundDictionaryInitialized<AllocU8: alloc::Allocator<u8>>(
2052 addon: &mut state::BrotliDecoderCompoundDictionary<AllocU8>,
2053) {
2054 let mut block_bits: u32 = 8;
2056 let maximal_address = addon.total_size as u32 - 1;
2057 if addon.block_bits != COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED {
2058 return;
2059 }
2060 while (maximal_address >> block_bits) != 0 {
2061 block_bits += 1;
2062 }
2063 block_bits -= 8;
2064 addon.block_bits = block_bits;
2065 let mut cursor: u32 = 0;
2066 let mut index: usize = 0;
2067 while cursor <= maximal_address {
2068 while fast!((addon.chunk_offsets)[index + 1]) < cursor {
2070 index += 1;
2071 }
2072 fast_mut!((addon.block_map)[(cursor >> block_bits) as usize]) = index as u8;
2073 match cursor.checked_add(1 << block_bits) {
2074 Some(next) => cursor = next,
2075 None => break,
2076 }
2077 }
2078 }
2081
2082#[cold]
2086#[inline(never)]
2087fn InitializeCompoundDictionaryCopy<AllocU8: alloc::Allocator<u8>>(
2088 addon: &mut state::BrotliDecoderCompoundDictionary<AllocU8>,
2089 address: usize,
2090 length: usize,
2091) -> bool {
2092 EnsureCompoundDictionaryInitialized(addon);
2093 if length > addon.total_size - address {
2094 return false;
2095 }
2096 let mut index = fast!((addon.block_map)[address >> addon.block_bits]) as usize;
2097 while address as u32 >= fast!((addon.chunk_offsets)[index + 1]) {
2099 index += 1;
2100 }
2101 addon.br_index = index;
2102 addon.br_offset = address - fast!((addon.chunk_offsets)[index]) as usize;
2103 addon.br_length = length;
2104 addon.br_copied = 0;
2105 true
2106}
2107
2108#[cold]
2114#[inline(never)]
2115fn CopyFromCompoundDictionary<AllocU8: alloc::Allocator<u8>>(
2116 addon: &mut state::BrotliDecoderCompoundDictionary<AllocU8>,
2117 ringbuffer: &mut [u8],
2118 ringbuffer_size: i32,
2119 pos: i32,
2120 external: &[u8],
2121) -> i32 {
2122 let ringbuffer_size = ringbuffer_size as usize;
2123 let mut pos = pos as usize;
2124 let orig_pos = pos;
2125 while addon.br_length != addon.br_copied {
2126 let chunk = match addon.chunks[addon.br_index] {
2127 state::MaybeOwnedSlice::External(_) => external,
2128 ref chunk => chunk.slice(),
2129 };
2130 let space = ringbuffer_size - pos;
2131 let rem_chunk_length = chunk.len() - addon.br_offset;
2132 let mut length = addon.br_length - addon.br_copied;
2133 if length > rem_chunk_length {
2134 length = rem_chunk_length;
2135 }
2136 if length > space {
2137 length = space;
2138 }
2139 fast_mut!((ringbuffer)[pos ; pos + length])
2140 .clone_from_slice(fast!((chunk)[addon.br_offset ; addon.br_offset + length]));
2141 pos += length;
2142 addon.br_offset += length;
2143 addon.br_copied += length;
2144 if length == rem_chunk_length {
2145 addon.br_index += 1;
2146 addon.br_offset = 0;
2147 }
2148 if pos == ringbuffer_size {
2149 break;
2150 }
2151 }
2152 (pos - orig_pos) as i32
2153}
2154
2155#[cfg(all(test, feature="std"))]
2156mod tests {
2157 use super::*;
2158
2159 struct CountingAlloc {
2163 fail_at: usize,
2164 short: bool,
2165 requests: std::vec::Vec<usize>,
2166 allocated: usize,
2167 freed: usize,
2168 }
2169
2170 impl Default for CountingAlloc {
2171 fn default() -> Self {
2172 CountingAlloc {
2173 fail_at: usize::MAX,
2174 short: false,
2175 requests: std::vec::Vec::new(),
2176 allocated: 0,
2177 freed: 0,
2178 }
2179 }
2180 }
2181
2182 impl Allocator<u8> for CountingAlloc {
2183 type AllocatedMemory = <::StandardAlloc as Allocator<u8>>::AllocatedMemory;
2184 fn alloc_cell(&mut self, len: usize) -> Self::AllocatedMemory {
2185 self.requests.push(len);
2186 if len >= self.fail_at {
2187 return Self::AllocatedMemory::default();
2188 }
2189 let len = if self.short && len != 0 { len - 1 } else { len };
2190 if len != 0 {
2191 self.allocated += 1;
2192 }
2193 ::StandardAlloc::default().alloc_cell(len)
2194 }
2195 fn free_cell(&mut self, data: Self::AllocatedMemory) {
2196 if data.slice().len() != 0 {
2197 self.freed += 1;
2198 }
2199 }
2200 }
2201
2202 type CountingState = BrotliState<CountingAlloc, ::StandardAlloc, ::StandardAlloc>;
2203
2204 fn counting_state(window_bits: u32) -> CountingState {
2205 let mut s = BrotliState::new(CountingAlloc::default(),
2206 ::StandardAlloc::default(),
2207 ::StandardAlloc::default());
2208 s.window_bits = window_bits;
2209 s
2210 }
2211
2212 fn start_metablock(s: &mut CountingState, mlen: i32) -> BrotliDecoderErrorCode {
2215 s.meta_block_remaining_len = mlen;
2216 BrotliCalculateRingBufferSize(s, &[]);
2217 BrotliEnsureRingBuffer(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2)
2218 }
2219
2220 fn finish_metablock(s: &mut CountingState) {
2222 let (pos, mlen) = (s.pos as usize, s.meta_block_remaining_len as usize);
2223 for (i, byte) in s.ringbuffer.slice_mut()[pos..pos + mlen].iter_mut().enumerate() {
2224 *byte = ((pos + i) % 251) as u8 + 1;
2225 }
2226 s.pos += s.meta_block_remaining_len;
2227 s.meta_block_remaining_len = 0;
2228 }
2229
2230 fn assert_holds_decoded_bytes(s: &CountingState) {
2231 let ringbuffer = s.ringbuffer.slice();
2232 for i in 0..s.pos as usize {
2233 assert_eq!(ringbuffer[i], (i % 251) as u8 + 1, "byte {}", i);
2234 }
2235 }
2236
2237 fn assert_success(result: BrotliDecoderErrorCode) {
2238 assert_eq!(result as i32, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS as i32);
2239 }
2240
2241 fn assert_ring_buffer(s: &CountingState, size: i32) {
2242 assert_eq!(s.ringbuffer_size, size);
2243 assert_eq!(s.ringbuffer_mask, size - 1);
2244 assert_eq!(s.new_ringbuffer_size, size);
2245 assert_eq!(s.ringbuffer.slice().len(), size as usize + kRingBufferAllocationSlack);
2246 }
2247
2248 #[test]
2249 fn ring_buffer_starts_small_and_grows_on_demand() {
2250 let mut s = counting_state(22);
2251 assert_success(start_metablock(&mut s, 10));
2252 assert_ring_buffer(&s, 1024);
2253 assert_eq!(&s.ringbuffer.slice()[1022..1024], &[0, 0]);
2255 finish_metablock(&mut s);
2256 assert_success(start_metablock(&mut s, 1014));
2258 assert_ring_buffer(&s, 1024);
2259 finish_metablock(&mut s);
2260 assert_eq!(s.alloc_u8.allocated, 1);
2261 assert_success(start_metablock(&mut s, 1));
2263 assert_ring_buffer(&s, 2048);
2264 assert_holds_decoded_bytes(&s);
2265 assert_eq!(&s.ringbuffer.slice()[2046..2048], &[0, 0]);
2266 finish_metablock(&mut s);
2267 assert_success(start_metablock(&mut s, 5000));
2269 assert_ring_buffer(&s, 8192);
2270 assert_holds_decoded_bytes(&s);
2271 finish_metablock(&mut s);
2272 assert_success(start_metablock(&mut s, 3 << 20));
2274 assert_ring_buffer(&s, 1 << 22);
2275 assert_holds_decoded_bytes(&s);
2276 finish_metablock(&mut s);
2277 assert_success(start_metablock(&mut s, 3 << 20));
2279 assert_ring_buffer(&s, 1 << 22);
2280 let slack = kRingBufferAllocationSlack;
2281 assert_eq!(s.alloc_u8.requests,
2282 [1024 + slack, 2048 + slack, 8192 + slack, (1 << 22) + slack]);
2283 assert_eq!(s.alloc_u8.allocated, 4);
2285 assert_eq!(s.alloc_u8.freed, 3);
2286 }
2287
2288 #[test]
2289 fn ring_buffer_sizing_matches_the_c_decoder() {
2290 let first_size = |window_bits: u32, mlen: i32, canny: bool, is_last: bool| {
2291 let mut s = counting_state(window_bits);
2292 s.canny_ringbuffer_allocation = canny;
2293 s.is_last_metablock = is_last as u8;
2294 assert_success(start_metablock(&mut s, mlen));
2295 s.ringbuffer_size
2296 };
2297 assert_eq!(first_size(16, 1, true, false), 1024);
2300 assert_eq!(first_size(24, 1024, true, false), 1024);
2301 assert_eq!(first_size(30, 1, true, false), 1024);
2302 assert_eq!(first_size(24, 1025, true, false), 2048);
2303 assert_eq!(first_size(16, 1 << 24, true, false), 1 << 16);
2304 assert_eq!(first_size(10, 1, true, false), 1024);
2306 assert_eq!(first_size(16, 1, false, false), 1 << 16);
2308 assert_eq!(first_size(24, 1, false, false), 1 << 24);
2309 assert_eq!(first_size(24, 1, false, true), 1 << 24);
2310 assert_eq!(first_size(22, 1, true, true), 32);
2313 assert_eq!(first_size(10, 17, true, true), 32);
2314 assert_eq!(first_size(22, 40, true, true), 64);
2315 assert_eq!(first_size(22, 513, true, true), 1024);
2316 assert_eq!(first_size(22, 1025, true, true), 2048);
2317
2318 let mut s = counting_state(22);
2320 s.is_metadata = 1;
2321 s.meta_block_remaining_len = 100;
2322 BrotliCalculateRingBufferSize(&mut s, &[]);
2323 assert_eq!(s.new_ringbuffer_size, 0);
2324 assert!(s.alloc_u8.requests.is_empty());
2325 }
2326
2327 #[test]
2331 fn fixed_pool_ring_buffer_needs_no_more_than_before_growth() {
2332 let slack = kRingBufferAllocationSlack;
2333 let window = 1usize << 16;
2334 let mut s = counting_state(16);
2336 s.u8_pool_size = window + slack;
2337 assert_success(start_metablock(&mut s, 10));
2338 assert_ring_buffer(&s, window as i32);
2339 assert_eq!(&s.ringbuffer.slice()[window - 2..window], &[0, 0]);
2340 finish_metablock(&mut s);
2341 assert_success(start_metablock(&mut s, 50000));
2342 assert_ring_buffer(&s, window as i32);
2343 assert_eq!(s.alloc_u8.requests, [window + slack]);
2344 let mut s = counting_state(16);
2346 s.u8_pool_size = window + slack;
2347 s.is_last_metablock = 1;
2348 assert_success(start_metablock(&mut s, 40));
2349 assert_ring_buffer(&s, 64);
2350 let mut s = counting_state(16);
2353 s.u8_pool_size = window + slack - 1;
2354 assert_success(start_metablock(&mut s, 1));
2355 assert_ring_buffer(&s, 32);
2356 finish_metablock(&mut s);
2357 assert_success(start_metablock(&mut s, 100));
2358 assert_ring_buffer(&s, 128);
2359 assert_holds_decoded_bytes(&s);
2360 finish_metablock(&mut s);
2361 assert_success(start_metablock(&mut s, 40000));
2362 assert_ring_buffer(&s, window as i32);
2363 assert_holds_decoded_bytes(&s);
2364 assert_eq!(s.alloc_u8.requests, [32 + slack, 128 + slack, window + slack]);
2365 assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (3, 2));
2366 let mut s = counting_state(16);
2368 s.u8_pool_size = 1;
2369 s.canny_ringbuffer_allocation = false;
2370 s.is_last_metablock = 1;
2371 assert_success(start_metablock(&mut s, 1));
2372 assert_ring_buffer(&s, window as i32);
2373 }
2374
2375 #[test]
2376 fn failed_ring_buffer_growth_keeps_the_current_one() {
2377 let mut s = counting_state(24);
2378 s.alloc_u8.fail_at = 1 << 20;
2379 assert_success(start_metablock(&mut s, 700));
2380 finish_metablock(&mut s);
2381 assert_eq!(start_metablock(&mut s, 3 << 20) as i32,
2383 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2 as i32);
2384 assert_eq!(s.ringbuffer_size, 1024);
2385 assert_eq!(s.ringbuffer_mask, 1023);
2386 assert_eq!(s.ringbuffer.slice().len(), 1024 + kRingBufferAllocationSlack);
2387 assert_eq!(s.pos, 700);
2388 assert_holds_decoded_bytes(&s);
2389 assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (1, 0));
2390 s.alloc_u8.fail_at = usize::MAX;
2392 assert_success(BrotliEnsureRingBuffer(
2393 &mut s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2));
2394 assert_ring_buffer(&s, 4 << 20);
2395 assert_holds_decoded_bytes(&s);
2396 assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (2, 1));
2397 }
2398
2399 #[test]
2400 fn short_ring_buffer_allocation_is_returned_and_reported() {
2401 let mut s = counting_state(22);
2402 s.alloc_u8.short = true;
2403 assert_eq!(start_metablock(&mut s, 10) as i32,
2404 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2 as i32);
2405 assert_eq!(s.ringbuffer.slice().len(), 0);
2406 assert_eq!(s.ringbuffer_size, 0);
2407 assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (1, 1));
2408 }
2409
2410 #[test]
2411 fn ensure_ring_buffer_rejects_states_the_decoder_cannot_produce() {
2412 let unreachable = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE as i32;
2413 let ensure = |s: &mut CountingState| {
2414 BrotliEnsureRingBuffer(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1)
2415 as i32
2416 };
2417 let mut s = counting_state(16);
2418 assert_eq!(ensure(&mut s), unreachable);
2420 s.new_ringbuffer_size = 1000;
2422 assert_eq!(ensure(&mut s), unreachable);
2423 s.new_ringbuffer_size = 1024;
2425 s.pos = 1025;
2426 assert_eq!(ensure(&mut s), unreachable);
2427 s.pos = 1;
2428 assert_eq!(ensure(&mut s), unreachable);
2429 s.pos = -1;
2430 assert_eq!(ensure(&mut s), unreachable);
2431 s.pos = 0;
2433 s.rb_roundtrips = 1;
2434 assert_eq!(ensure(&mut s), unreachable);
2435 assert!(s.alloc_u8.requests.is_empty());
2436 s.rb_roundtrips = 0;
2437 assert_eq!(ensure(&mut s), BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS as i32);
2438 }
2439
2440 struct BitWriter {
2442 bytes: std::vec::Vec<u8>,
2443 bits: usize,
2444 }
2445
2446 impl BitWriter {
2447 fn put(&mut self, count: usize, value: u32) {
2448 for i in 0..count {
2449 if self.bits % 8 == 0 {
2450 self.bytes.push(0);
2451 }
2452 let last = self.bytes.len() - 1;
2453 self.bytes[last] |= (((value >> i) & 1) as u8) << (self.bits % 8);
2454 self.bits += 1;
2455 }
2456 }
2457
2458 fn raw(&mut self, data: &[u8]) {
2460 self.bytes.extend_from_slice(data);
2461 self.bits = self.bytes.len() * 8;
2462 }
2463 }
2464
2465 fn uncompressed_stream(lengths: &[usize]) -> (std::vec::Vec<u8>, std::vec::Vec<u8>) {
2468 let mut writer = BitWriter { bytes: std::vec::Vec::new(), bits: 0 };
2469 writer.put(1, 0); let mut data = std::vec::Vec::new();
2471 let mut seed = 1u32;
2472 for &length in lengths {
2473 let block: std::vec::Vec<u8> = (0..length).map(|_| {
2474 seed = seed.wrapping_mul(1103515245).wrapping_add(12345);
2475 (seed >> 16) as u8
2476 }).collect();
2477 writer.put(1, 0);
2479 writer.put(2, 0);
2480 writer.put(16, length as u32 - 1);
2481 writer.put(1, 1);
2482 writer.raw(&block);
2483 data.extend_from_slice(&block);
2484 }
2485 writer.put(2, 3); (writer.bytes, data)
2487 }
2488
2489 fn decode_in_chunks(s: &mut CountingState, input: &[u8], in_chunk: usize, out_chunk: usize)
2492 -> std::vec::Vec<u8> {
2493 let mut output = std::vec::Vec::new();
2494 let mut buffer = vec![0u8; core::cmp::min(out_chunk, 1 << 20)];
2495 let mut input_offset = 0;
2496 loop {
2497 let mut available_in = core::cmp::min(in_chunk, input.len() - input_offset);
2498 let mut available_out = buffer.len();
2499 let mut output_offset = 0;
2500 let mut total_out = 0;
2501 let result = BrotliDecompressStream(&mut available_in, &mut input_offset, input,
2502 &mut available_out, &mut output_offset, &mut buffer,
2503 &mut total_out, s);
2504 output.extend_from_slice(&buffer[..output_offset]);
2505 match result {
2506 BrotliResult::ResultSuccess => return output,
2507 BrotliResult::NeedsMoreInput => assert!(input_offset < input.len(), "truncated"),
2508 BrotliResult::NeedsMoreOutput => {}
2509 BrotliResult::ResultFailure => panic!("decoding failed: {:?}", s.error_code),
2510 }
2511 }
2512 }
2513
2514 #[test]
2515 fn ring_buffer_grows_across_metablocks_then_wraps() {
2516 let (input, expected) = uncompressed_stream(&[10, 1000, 1500, 3000, 30000, 40000, 5000]);
2519 let slack = kRingBufferAllocationSlack;
2520 for &(in_chunk, out_chunk) in &[(usize::MAX, usize::MAX), (1, 1), (1, 4099), (4099, 1),
2521 (333, 777)] {
2522 let mut s = counting_state(0);
2523 let output = decode_in_chunks(&mut s, &input, in_chunk, out_chunk);
2524 assert!(output == expected, "chunks of {} and {}", in_chunk, out_chunk);
2525 assert_eq!(s.alloc_u8.requests, [1024 + slack, 4096 + slack, 8192 + slack, 65536 + slack]);
2526 assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (4, 3));
2527 }
2528 }
2529
2530 #[test]
2531 fn set_parameter_disables_growth_only_before_decoding() {
2532 use state::BrotliDecoderParameter::{BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION,
2533 BROTLI_DECODER_PARAM_LARGE_WINDOW};
2534 let (input, expected) = uncompressed_stream(&[10, 1000, 1500, 3000, 30000, 40000, 5000]);
2535 let mut s = counting_state(0);
2536 assert!(s.set_parameter(BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION, 1));
2537 assert!(decode_in_chunks(&mut s, &input, usize::MAX, usize::MAX) == expected);
2538 assert_eq!(s.alloc_u8.requests, [65536 + kRingBufferAllocationSlack]);
2540 let large_window = s.large_window;
2542 for &value in &[0, 1] {
2543 assert!(!s.set_parameter(BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION, value));
2544 assert!(!s.set_parameter(BROTLI_DECODER_PARAM_LARGE_WINDOW, value));
2545 }
2546 assert!(!s.canny_ringbuffer_allocation);
2547 assert_eq!(s.large_window, large_window);
2548 }
2549
2550 #[test]
2551 fn initial_ring_buffer_size_sets_the_first_ring_buffer() {
2552 let first_size = |initial: u32, mlen: i32, is_last: bool| {
2553 let mut s = counting_state(22);
2554 assert!(s.set_initial_ring_buffer_size(initial));
2555 s.is_last_metablock = is_last as u8;
2556 assert_success(start_metablock(&mut s, mlen));
2557 s.ringbuffer_size
2558 };
2559 assert_eq!(first_size(0, 10, false), 1024);
2560 assert_eq!(first_size(4096, 10, false), 4096);
2562 assert_eq!(first_size(5000, 10, false), 8192);
2563 assert_eq!(first_size(1, 10, false), 32);
2564 assert_eq!(first_size(4096, 5000, false), 8192);
2566 assert_eq!(first_size(u32::MAX, 10, false), 1 << 22);
2568 assert_eq!(first_size(u32::MAX, 10, true), 32);
2570 let mut s = counting_state(22);
2572 assert!(s.set_initial_ring_buffer_size(4096));
2573 s.canny_ringbuffer_allocation = false;
2574 assert_success(start_metablock(&mut s, 10));
2575 assert_eq!(s.ringbuffer_size, 1 << 22);
2576 }
2577
2578 #[test]
2579 fn one_shot_output_hint_grows_in_bounded_steps() {
2580 let mut tiny = counting_state(22);
2581 tiny.one_shot_output_size = 1 << 20;
2582 assert_success(start_metablock(&mut tiny, 16));
2583 assert_ring_buffer(&tiny, 1024);
2584
2585 let mut small = counting_state(22);
2586 small.one_shot_output_size = 1 << 20;
2587 assert_success(start_metablock(&mut small, 300));
2588 assert_ring_buffer(&small, 2048);
2589
2590 let mut s = counting_state(22);
2591 s.one_shot_output_size = 1 << 20;
2592 let slack = kRingBufferAllocationSlack;
2593
2594 assert_success(start_metablock(&mut s, 10));
2595 assert_ring_buffer(&s, 1024);
2596 finish_metablock(&mut s);
2597
2598 assert_success(start_metablock(&mut s, (64 << 10) - 10));
2601 assert_ring_buffer(&s, 256 << 10);
2602 assert_holds_decoded_bytes(&s);
2603 finish_metablock(&mut s);
2604
2605 assert_success(start_metablock(&mut s, 192 << 10));
2606 assert_ring_buffer(&s, 1 << 20);
2607 assert_holds_decoded_bytes(&s);
2608 assert_eq!(s.alloc_u8.requests, [1024 + slack, (256 << 10) + slack,
2609 (1 << 20) + slack]);
2610
2611 let mut oversized = counting_state(30);
2614 oversized.one_shot_output_size = 1 << 30;
2615 assert_success(start_metablock(&mut oversized, 10));
2616 assert_ring_buffer(&oversized, 1024);
2617 finish_metablock(&mut oversized);
2618 assert_success(start_metablock(&mut oversized, (64 << 10) - 10));
2619 assert_ring_buffer(&oversized, 256 << 10);
2620 }
2621
2622 #[test]
2623 fn initial_ring_buffer_size_is_only_set_before_decoding() {
2624 let (input, expected) = uncompressed_stream(&[10, 1000, 1500, 3000, 30000, 40000, 5000]);
2625 let mut s = counting_state(0);
2626 assert!(s.set_initial_ring_buffer_size(4096));
2627 assert!(s.set_initial_ring_buffer_size(u32::MAX));
2628 let (mut available_in, mut input_offset) = (1, 0);
2630 let (mut available_out, mut output_offset, mut total_out) = (0, 0, 0);
2631 match BrotliDecompressStream(&mut available_in, &mut input_offset, &input,
2632 &mut available_out, &mut output_offset, &mut [],
2633 &mut total_out, &mut s) {
2634 BrotliResult::NeedsMoreInput => {}
2635 _ => panic!("expected NeedsMoreInput"),
2636 }
2637 assert!(s.alloc_u8.requests.is_empty());
2638 assert!(!s.set_initial_ring_buffer_size(0));
2640 assert!(decode_in_chunks(&mut s, &input[1..], 333, 777) == expected);
2641 assert_eq!(s.alloc_u8.requests, [65536 + kRingBufferAllocationSlack]);
2644 }
2645
2646 #[test]
2650 fn uncompressed_metablock_before_an_empty_last_one_is_sized_to_fit() {
2651 let (input, expected) = uncompressed_stream(&[10]);
2652 let requests = |initial: u32, canny: bool, in_chunk: usize| {
2653 let mut s = counting_state(0);
2654 assert!(s.set_initial_ring_buffer_size(initial));
2655 s.canny_ringbuffer_allocation = canny;
2656 assert!(decode_in_chunks(&mut s, &input, in_chunk, usize::MAX) == expected);
2657 s.alloc_u8.requests.clone()
2658 };
2659 let slack = kRingBufferAllocationSlack;
2660 assert_eq!(requests(0, true, usize::MAX), [32 + slack]);
2662 assert_eq!(requests(u32::MAX, true, usize::MAX), [32 + slack]);
2663 assert_eq!(requests(0, false, usize::MAX), [65536 + slack]);
2665 assert_eq!(requests(0, true, 1), [1024 + slack]);
2667 assert_eq!(requests(u32::MAX, true, 1), [65536 + slack]);
2668 }
2669
2670 #[test]
2671 fn take_output_returns_every_consumed_byte() {
2672 let input = [0x1b, 0x13, 0x00, 0x00, 0xa4, 0xb0, 0xb2, 0xea, 0x81, 0x47, 0x02, 0x8a];
2674 let expected = b"XXXXXXXXXXYYYYYYYYYY";
2675 let mut state = BrotliState::new(::StandardAlloc::default(),
2676 ::StandardAlloc::default(),
2677 ::StandardAlloc::default());
2678 let mut available_in = input.len();
2679 let mut input_offset = 0usize;
2680 let mut available_out = 0usize;
2681 let mut output_offset = 0usize;
2682 let mut total_out = 0usize;
2683 let result = BrotliDecompressStream(&mut available_in, &mut input_offset, &input,
2684 &mut available_out, &mut output_offset, &mut [],
2685 &mut total_out, &mut state);
2686 assert_eq!(result as i32, BrotliResult::NeedsMoreOutput as i32);
2687 assert_eq!(total_out, 0);
2688
2689 let mut consumed = 0usize;
2690 for &limit in &[1usize, 3, 7, 0] {
2691 assert!(BrotliDecoderHasMoreOutput(&state));
2692 let mut size = limit;
2693 {
2694 let output = BrotliDecoderTakeOutput(&mut state, &mut size);
2695 assert_eq!(size, if limit == 0 { expected.len() - consumed } else { limit });
2696 assert_eq!(output.len(), size);
2697 assert_eq!(output, &expected[consumed..consumed + size]);
2698 }
2699 consumed += size;
2700 assert_eq!(state.partial_pos_out, consumed as u64);
2701 }
2702 assert_eq!(consumed, expected.len());
2703 assert!(!BrotliDecoderHasMoreOutput(&state));
2704 for &limit in &[1usize, 0] {
2705 let mut size = limit;
2706 assert!(BrotliDecoderTakeOutput(&mut state, &mut size).is_empty());
2707 assert_eq!(size, 0);
2708 }
2709 }
2710
2711 fn assert_large_remaining_copy_is_clamped(meta_block_remaining_len: i32,
2712 pos: i32,
2713 expected_result: BrotliDecoderErrorCode) {
2714 let mut s = BrotliState::new(::StandardAlloc::default(),
2715 ::StandardAlloc::default(),
2716 ::StandardAlloc::default());
2717 s.ringbuffer_size = 16;
2718 s.new_ringbuffer_size = 16;
2719 s.window_bits = 5;
2720 s.ringbuffer = s.alloc_u8.alloc_cell(s.ringbuffer_size as usize);
2721 s.meta_block_remaining_len = meta_block_remaining_len;
2722 s.pos = pos;
2723 s.br.avail_in = 1u32 << 31;
2724
2725 let input = [0x5au8];
2726 let mut available_out = 0usize;
2727 let mut output = [0u8; 0];
2728 let mut output_offset = 0usize;
2729 let mut total_out = 0usize;
2730 let result = CopyUncompressedBlockToOutput(&mut available_out,
2731 &mut output,
2732 &mut output_offset,
2733 &mut total_out,
2734 &mut s,
2735 &input);
2736
2737 assert_eq!(result as i32, expected_result as i32);
2738 assert_eq!(s.br.avail_in, (1u32 << 31) - 1);
2739 assert_eq!(s.meta_block_remaining_len, meta_block_remaining_len - 1);
2740 assert_eq!(s.pos, pos + 1);
2741 assert_eq!(s.ringbuffer.slice()[pos as usize], input[0]);
2742 }
2743
2744 #[test]
2745 fn uncompressed_copy_clamps_unsigned_remaining_bytes() {
2746 assert_large_remaining_copy_is_clamped(
2747 1, 0, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS);
2748 assert_large_remaining_copy_is_clamped(
2749 16, 15, BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT);
2750 }
2751
2752 #[test]
2753 fn stream_rejects_wrapping_output_range() {
2754 let mut state = BrotliState::new(::StandardAlloc::default(),
2755 ::StandardAlloc::default(),
2756 ::StandardAlloc::default());
2757 let input = [0x06u8];
2758 let mut output = [0u8; 1];
2759 let mut available_in = input.len();
2760 let mut input_offset = 0usize;
2761 let mut available_out = usize::MAX;
2762 let mut output_offset = 1usize;
2763 let mut total_out = 0usize;
2764
2765 let result = BrotliDecompressStream(&mut available_in,
2766 &mut input_offset,
2767 &input,
2768 &mut available_out,
2769 &mut output_offset,
2770 &mut output,
2771 &mut total_out,
2772 &mut state);
2773
2774 assert_eq!(result as i32, BrotliResult::ResultFailure as i32);
2775 assert_eq!(state.error_code as i32,
2776 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS as i32);
2777 }
2778
2779 #[test]
2780 fn stream_rejects_wrapping_input_range() {
2781 let mut state = BrotliState::new(::StandardAlloc::default(),
2782 ::StandardAlloc::default(),
2783 ::StandardAlloc::default());
2784 let input = [0x06u8];
2785 let mut output = [0u8; 1];
2786 let mut available_in = u32::MAX as usize;
2788 let mut input_offset = 1usize;
2789 let mut available_out = output.len();
2790 let mut output_offset = 0usize;
2791 let mut total_out = 0usize;
2792
2793 let result = BrotliDecompressStream(&mut available_in,
2794 &mut input_offset,
2795 &input,
2796 &mut available_out,
2797 &mut output_offset,
2798 &mut output,
2799 &mut total_out,
2800 &mut state);
2801
2802 assert_eq!(result as i32, BrotliResult::ResultFailure as i32);
2803 assert_eq!(state.error_code as i32,
2804 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS as i32);
2805 }
2806
2807 #[test]
2808 fn format_distance_error_restores_huffman_tree_groups() {
2809 let mut state = BrotliState::new(::StandardAlloc::default(),
2810 ::StandardAlloc::default(),
2811 ::StandardAlloc::default());
2812 state.BrotliHuffmanTreeGroupInit(state::WhichTreeGroup::LITERAL,
2815 kNumLiteralCodes, kNumLiteralCodes, 1);
2816 state.BrotliHuffmanTreeGroupInit(state::WhichTreeGroup::INSERT_COPY,
2817 kNumInsertAndCopyCodes, kNumInsertAndCopyCodes, 2);
2818 state.BrotliHuffmanTreeGroupInit(state::WhichTreeGroup::DISTANCE, 64, 64, 3);
2819 let expected_code_lengths = [
2820 state.literal_hgroup.codes.slice().len(),
2821 state.insert_copy_hgroup.codes.slice().len(),
2822 state.distance_hgroup.codes.slice().len(),
2823 ];
2824
2825 state.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2826 state.distance_code = 1;
2827 state.dist_rb_idx = 1;
2828 state.dist_rb[0] = i32::MAX;
2829 state.max_distance = 0;
2830 state.max_backward_distance = 0;
2831
2832 let result = SafeProcessCommands(&mut state, &[], &[]);
2833
2834 assert_eq!(result as i32,
2835 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE as i32);
2836 assert_eq!(state.literal_hgroup.codes.slice().len(), expected_code_lengths[0]);
2837 assert_eq!(state.insert_copy_hgroup.codes.slice().len(), expected_code_lengths[1]);
2838 assert_eq!(state.distance_hgroup.codes.slice().len(), expected_code_lengths[2]);
2839 }
2840}
2841
2842fn EnsureContextMapTable<AllocU8: alloc::Allocator<u8>,
2845 AllocU32: alloc::Allocator<u32>,
2846 AllocHC: alloc::Allocator<HuffmanCode>>
2847 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
2848 -> bool {
2849 if s.context_map_table.slice().len() == 0 {
2850 s.context_map_table = s.alloc_hc.alloc_cell(huffman::BROTLI_HUFFMAN_MAX_SIZE_272 as usize);
2851 }
2852 s.context_map_table.slice().len() != 0
2853}
2854
2855fn EnsureBlockTrees<AllocU8: alloc::Allocator<u8>,
2860 AllocU32: alloc::Allocator<u32>,
2861 AllocHC: alloc::Allocator<HuffmanCode>>
2862 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
2863 -> bool {
2864 if !EnsureContextMapTable(s) {
2865 return false;
2866 }
2867 if s.block_type_length_state.block_type_trees.slice().len() == 0 {
2868 s.block_type_length_state.block_type_trees =
2869 s.alloc_hc.alloc_cell(3 * huffman::BROTLI_HUFFMAN_MAX_SIZE_258 as usize);
2870 if s.block_type_length_state.block_type_trees.slice().len() == 0 {
2871 return false;
2872 }
2873 }
2874 if s.block_type_length_state.block_len_trees.slice().len() == 0 {
2875 s.block_type_length_state.block_len_trees =
2876 s.alloc_hc.alloc_cell(3 * huffman::BROTLI_HUFFMAN_MAX_SIZE_26 as usize);
2877 if s.block_type_length_state.block_len_trees.slice().len() == 0 {
2878 return false;
2879 }
2880 }
2881 true
2882}
2883
2884pub fn ReadContextModes<AllocU8: alloc::Allocator<u8>,
2886 AllocU32: alloc::Allocator<u32>,
2887 AllocHC: alloc::Allocator<HuffmanCode>>
2888 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2889 input: &[u8])
2890 -> BrotliDecoderErrorCode {
2891
2892 let mut i: i32 = s.loop_counter;
2893
2894 for context_mode_iter in fast_mut!((s.context_modes.slice_mut())[i as usize ;
2895 (s.block_type_length_state.num_block_types[0]
2896 as usize)])
2897 .iter_mut() {
2898 let mut bits: u32 = 0;
2899 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut bits, input)) {
2900 mark_unlikely();
2901 s.loop_counter = i;
2902 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2903 }
2904 *context_mode_iter = bits as u8;
2905 BROTLI_LOG_UINT!(i);
2906 i += 1;
2907 }
2908 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
2909}
2910
2911#[inline(always)]
2912fn TakeDistanceFromRingBuffer(
2913 distance_code: &mut i32,
2914 dist_rb_idx: &mut i32,
2915 dist_rb: &[i32; 4],
2916 distance_context: &mut i32,
2917) {
2918 if *distance_code == 0 {
2919 *dist_rb_idx -= 1;
2920 *distance_code = fast!((dist_rb)[(*dist_rb_idx & 3) as usize]);
2921 *distance_context = 1;
2922 } else {
2923 let dcode = *distance_code << 1;
2924 const kDistanceShortCodeIndexOffset: u32 = 0xaaafff1b;
2927 const kDistanceShortCodeValueOffset: u32 = 0xfa5fa500;
2930 let mut v = (*dist_rb_idx + (kDistanceShortCodeIndexOffset as i32 >> dcode)) & 0x3;
2931 *distance_code = fast!((dist_rb)[v as usize]);
2932 v = (kDistanceShortCodeValueOffset >> dcode) as i32 & 0x3;
2933 if (dcode & 0x3) != 0 {
2934 *distance_code += v;
2935 } else {
2936 *distance_code -= v;
2937 if *distance_code <= 0 {
2938 *distance_code = 0x7fffffff;
2941 }
2942 }
2943 }
2944}
2945
2946pub fn SafeReadBits(br: &mut bit_reader::BrotliBitReader,
2947 n_bits: u32,
2948 val: &mut u32,
2949 input: &[u8])
2950 -> bool {
2951 if (n_bits != 0) {
2952 bit_reader::BrotliSafeReadBits(br, n_bits, val, input)
2953 } else {
2954 *val = 0;
2955 true
2956 }
2957}
2958
2959trait CommandLoopMode {
2962 const SAFE: bool;
2963}
2964struct FastCommandLoop;
2965struct SafeCommandLoop;
2966impl CommandLoopMode for FastCommandLoop { const SAFE: bool = false; }
2967impl CommandLoopMode for SafeCommandLoop { const SAFE: bool = true; }
2968
2969#[cold]
2974#[inline(never)]
2975fn decode_distance_subtable<
2976 AllocU32: alloc::Allocator<u32>,
2977 AllocHC: alloc::Allocator<HuffmanCode>,
2978>(
2979 bits: u32,
2980 table_index: usize,
2981 root: HuffmanCode,
2982 distance_hgroup: &HuffmanTreeGroup<AllocU32, AllocHC>,
2983 dist_context_map: &[u8],
2984 dist_context_map_slice_index: usize,
2985 distance_context: i32,
2986) -> (usize, u32) {
2987 let tree_idx = dist_context_map
2988 .get(dist_context_map_slice_index + (distance_context as usize & 3))
2989 .copied()
2990 .unwrap_or(0) as usize;
2991 let distance_tree = huffman_tree(distance_hgroup, tree_idx);
2992 let sub_idx = table_index
2993 + root.value as usize
2994 + (((bits & bit_reader::BitMask(root.bits as u32)) >> HUFFMAN_TABLE_BITS) as usize);
2995 let sub = distance_tree.entry(sub_idx);
2996 (sub.value as usize, HUFFMAN_TABLE_BITS + (sub.bits as u32 & 7))
2997}
2998
2999#[inline(always)]
3005fn read_distance<M: CommandLoopMode>(
3006 code: usize,
3007 memento: &bit_reader::BrotliBitReaderState,
3008 fbr: &mut bit_reader::BitReaderSlice,
3009 br: &mut bit_reader::BrotliBitReader,
3010 input: &[u8],
3011 distance_code: &mut i32,
3012 distance_context: &mut i32,
3013 dist_rb_idx: &mut i32,
3014 dist_rb: &[i32; 4],
3015 block_len_2: &mut u32,
3016 distance_postfix_bits: u32,
3017 distance_postfix_mask: i32,
3018 num_direct_distance_codes: u32,
3019) -> bool {
3020 if (code & !0xfusize) == 0 {
3021 *distance_code = code as i32;
3022 *distance_context = 0;
3023 TakeDistanceFromRingBuffer(distance_code, dist_rb_idx, dist_rb, distance_context);
3024 *block_len_2 -= 1;
3025 return true;
3026 }
3027 if !M::SAFE {
3028 if distance_postfix_bits == 0 {
3029 let ndirect = num_direct_distance_codes;
3035 let code = code as u32;
3036 *distance_code = match code.checked_sub(ndirect) {
3037 Some(distval) => {
3038 let nbits = (distval >> 1) + 1;
3039 let bits = fbr.read_bits(nbits);
3040 ((2 + (distval & 1)).wrapping_shl(nbits))
3041 .wrapping_add(ndirect)
3042 .wrapping_sub(4 + NUM_DISTANCE_SHORT_CODES as u32 - 1)
3043 .wrapping_add(bits) as i32
3044 }
3045 None => code.wrapping_sub(NUM_DISTANCE_SHORT_CODES as u32 - 1) as i32,
3046 };
3047 } else {
3048 let num_direct = num_direct_distance_codes as i32;
3055 let distval = code as i32 - num_direct;
3056 let mask = !(distval >> 31) as u32;
3057 let d = (distval as u32) & mask;
3058 let postfix_bits = distance_postfix_bits & 3;
3059 let postfix = d & (distance_postfix_mask as u32);
3060 let hcode = d >> postfix_bits;
3061 let nbits = ((hcode >> 1) + 1) & mask;
3062 let bits = fbr.read_bits(nbits);
3063 let offset = (((2u32 + (hcode & 1)).wrapping_shl(nbits)).wrapping_sub(4)) & mask;
3064 *distance_code = ((offset.wrapping_add(bits).wrapping_shl(postfix_bits))
3065 .wrapping_add(postfix) & mask)
3066 .wrapping_add((code as u32) & !mask)
3067 .wrapping_add((num_direct as u32) & mask)
3068 .wrapping_sub(NUM_DISTANCE_SHORT_CODES as u32 - 1) as i32;
3069 }
3070 *distance_context = 0;
3071 *block_len_2 -= 1;
3072 return true;
3073 }
3074 let num_direct = num_direct_distance_codes as usize;
3075 if code < num_direct {
3076 *distance_code = (code - (NUM_DISTANCE_SHORT_CODES as usize - 1)) as i32;
3077 *distance_context = 0;
3078 *block_len_2 -= 1;
3079 return true;
3080 }
3081 let distval = (code - num_direct) as u32;
3082 let postfix_bits = distance_postfix_bits & 3;
3083 let postfix = distval & (distance_postfix_mask as u32);
3084 let hcode = distval >> postfix_bits;
3085 let nbits = (hcode >> 1) + 1;
3086 if nbits > 29 {
3087 *distance_code = 0x7fffffff;
3088 *distance_context = 0;
3089 *block_len_2 -= 1;
3090 return true;
3091 }
3092 let mut bits: u32 = 0;
3093 if !SafeReadBits(br, nbits, &mut bits, input) {
3094 bit_reader::BrotliBitReaderRestoreState(br, memento);
3095 return false;
3096 }
3097 #[cfg(target_pointer_width = "64")]
3098 {
3099 let offset = ((2u64 + (hcode & 1) as u64) << (nbits & 63)).wrapping_sub(4);
3100 *distance_code = ((offset.wrapping_add(bits as u64) << postfix_bits)
3101 .wrapping_add(postfix as u64)
3102 .wrapping_add(num_direct as u64) as i32)
3103 .wrapping_sub(NUM_DISTANCE_SHORT_CODES as i32)
3104 .wrapping_add(1);
3105 }
3106 #[cfg(not(target_pointer_width = "64"))]
3109 {
3110 let offset = (2u32 + (hcode & 1)).wrapping_shl(nbits).wrapping_sub(4);
3111 *distance_code = (offset.wrapping_add(bits).wrapping_shl(postfix_bits)
3112 .wrapping_add(postfix)
3113 .wrapping_add(num_direct as u32) as i32)
3114 .wrapping_sub(NUM_DISTANCE_SHORT_CODES as i32)
3115 .wrapping_add(1);
3116 }
3117 *distance_context = 0;
3118 *block_len_2 -= 1;
3119 true
3120}
3121
3122#[inline(always)]
3123fn read_command<M: CommandLoopMode>(
3124 fbr: &mut bit_reader::BitReaderSlice,
3125 br: &mut bit_reader::BrotliBitReader,
3126 input: &[u8],
3127 distance_code: &mut i32,
3128 distance_context: &mut i32,
3129 copy_len_out: &mut i32,
3130 block_len_1: &mut u32,
3131 insert_length: &mut i32,
3132 insert_copy_tree: &InsertCopyTable,
3133) -> bool {
3134 let memento = if M::SAFE {
3135 bit_reader::BrotliBitReaderSaveState(br)
3136 } else {
3137 bit_reader::BrotliBitReaderState::default()
3138 };
3139 let cmd_code = if !M::SAFE {
3140 *block_len_1 -= 1;
3141 read_symbol_slice(fbr, insert_copy_tree) as usize
3142 } else {
3143 let mut sym: u32 = 0;
3144 if !SafeReadSymbol(insert_copy_tree, br, &mut sym, input) {
3145 return false;
3146 }
3147 sym as usize
3148 };
3149 let v = &prefix::kCmdLut[cmd_code & 1023];
3153 *distance_code = v.distance_code as i32;
3154 *distance_context = v.context as i32;
3155 if !M::SAFE {
3156 let mut insert_len = v.insert_len_offset as i32;
3157 if v.insert_len_extra_bits != 0 {
3158 mark_unlikely();
3159 insert_len += fbr.read_bits(v.insert_len_extra_bits as u32) as i32;
3160 }
3161 let copy_offset = v.copy_len_offset as i32;
3162 let copy_extra = fbr.read_bits(v.copy_len_extra_bits as u32) as i32;
3163 *insert_length = insert_len;
3164 *copy_len_out = copy_offset + copy_extra;
3165 } else {
3166 let mut insert_len = v.insert_len_offset as i32;
3167 let insert_extra_bits = v.insert_len_extra_bits as u32;
3168 if insert_extra_bits != 0 {
3169 let mut bits = 0u32;
3170 if !bit_reader::BrotliSafeReadBits(br, insert_extra_bits, &mut bits, input) {
3171 bit_reader::BrotliBitReaderRestoreState(br, &memento);
3172 return false;
3173 }
3174 insert_len += bits as i32;
3175 }
3176 let copy_extra_bits = v.copy_len_extra_bits as u32;
3177 let mut copy_bits = 0u32;
3178 if !SafeReadBits(br, copy_extra_bits, &mut copy_bits, input) {
3179 bit_reader::BrotliBitReaderRestoreState(br, &memento);
3180 return false;
3181 }
3182 *insert_length = insert_len;
3183 *copy_len_out = v.copy_len_offset as i32 + copy_bits as i32;
3184 *block_len_1 -= 1;
3185 }
3186 true
3187}
3188
3189
3190#[inline(always)]
3191fn WarmupBitReader(safe: bool, br: &mut bit_reader::BrotliBitReader, input: &[u8]) -> bool {
3192 safe || bit_reader::BrotliWarmupBitReader(br, input)
3193}
3194
3195#[inline(always)]
3196fn CheckInputAmount(safe: bool, br: &bit_reader::BrotliBitReader, num: u32) -> bool {
3197 safe || bit_reader::BrotliCheckInputAmount(br, num)
3198}
3199
3200#[inline(always)]
3207fn memmove16_from_ringbuffer(data: &mut [u8], u32off_dst: u32, u32off_src: u32) -> bool {
3208 let off_dst = u32off_dst as usize;
3209 let off_src = u32off_src as usize;
3210 let len = data.len();
3211 if len < 32 || core::cmp::max(off_dst, off_src) > len - 32 {
3212 return false;
3213 }
3214 #[cfg(target_pointer_width = "64")]
3215 {
3216 let dst_end = off_dst + 16;
3217 let src_end = off_src + 16;
3218 let mut local_array: [u8; 16] = fast_uninitialized!(16);
3219 local_array.clone_from_slice(&data[off_src..src_end]);
3220 data[off_dst..dst_end].clone_from_slice(&local_array);
3221 true
3222 }
3223 #[cfg(not(target_pointer_width = "64"))]
3227 {
3228 let local_array: [u8; 16] = match data.get(off_src..) {
3229 Some(&[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, ..]) => {
3230 [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15]
3231 }
3232 _ => return false,
3233 };
3234 match data.get_mut(off_dst..) {
3235 Some([d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, ..]) => {
3236 *d0 = local_array[0];
3237 *d1 = local_array[1];
3238 *d2 = local_array[2];
3239 *d3 = local_array[3];
3240 *d4 = local_array[4];
3241 *d5 = local_array[5];
3242 *d6 = local_array[6];
3243 *d7 = local_array[7];
3244 *d8 = local_array[8];
3245 *d9 = local_array[9];
3246 *d10 = local_array[10];
3247 *d11 = local_array[11];
3248 *d12 = local_array[12];
3249 *d13 = local_array[13];
3250 *d14 = local_array[14];
3251 *d15 = local_array[15];
3252 true
3253 }
3254 _ => false,
3255 }
3256 }
3257}
3258
3259#[inline(always)]
3265fn memmove16_offset16(data: &mut [u8], u32off_dst: u32, u32off_src: u32) -> bool {
3266 let off_dst = u32off_dst as usize;
3267 let off_src = u32off_src as usize;
3268 let len = data.len();
3269 if len < 32 || core::cmp::max(off_dst, off_src) > len - 32 {
3270 return false;
3271 }
3272 #[cfg(target_pointer_width = "64")]
3273 {
3274 let mut local_array: [u8; 16] = fast_uninitialized!(16);
3275 local_array.clone_from_slice(&data[off_src + 16..off_src + 32]);
3276 data[off_dst + 16..off_dst + 32].clone_from_slice(&local_array);
3277 true
3278 }
3279 #[cfg(not(target_pointer_width = "64"))]
3280 {
3281 let local_array: [u8; 16] = match data.get(off_src..) {
3282 Some(
3283 &[
3284 _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,
3285 a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,
3286 ..,
3287 ],
3288 ) => [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15],
3289 _ => return false,
3290 };
3291 match data.get_mut(off_dst..) {
3292 Some(
3293 [
3294 _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,
3295 d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15,
3296 ..,
3297 ],
3298 ) => {
3299 *d0 = local_array[0];
3300 *d1 = local_array[1];
3301 *d2 = local_array[2];
3302 *d3 = local_array[3];
3303 *d4 = local_array[4];
3304 *d5 = local_array[5];
3305 *d6 = local_array[6];
3306 *d7 = local_array[7];
3307 *d8 = local_array[8];
3308 *d9 = local_array[9];
3309 *d10 = local_array[10];
3310 *d11 = local_array[11];
3311 *d12 = local_array[12];
3312 *d13 = local_array[13];
3313 *d14 = local_array[14];
3314 *d15 = local_array[15];
3315 true
3316 }
3317 _ => false,
3318 }
3319 }
3320}
3321
3322#[inline(always)]
3323fn copy_overlapping_backreference(data: &mut [u8], dst: usize, distance: usize,
3324 size: usize) -> bool {
3325 if distance == 0 || distance > dst || dst > data.len() || size > data.len() - dst {
3326 return false;
3327 }
3328 let seed = core::cmp::min(distance, size);
3329 data.copy_within(dst - distance..dst - distance + seed, dst);
3330 let mut copied = seed;
3331 while copied < size {
3332 let step = core::cmp::min(copied, size - copied);
3333 data.copy_within(dst..dst + step, dst + copied);
3334 copied += step;
3335 }
3336 true
3337}
3338
3339#[cfg_attr(target_pointer_width = "64", inline(always))]
3340#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3341fn memcpy_within_slice(data: &mut [u8], off_dst: usize, off_src: usize, size: usize) -> bool {
3342 let len = data.len();
3346 let apart = if off_dst > off_src { off_dst - off_src } else { off_src - off_dst };
3347 if size > len || off_dst > len - size || off_src > len - size || apart < size {
3348 return false;
3349 }
3350
3351 #[cfg(not(feature="unsafe"))]
3352 {
3353 if off_dst > off_src {
3354 let (src, dst) = data.split_at_mut(off_dst);
3355 let src_slice = fast!((src)[off_src ; off_src + size]);
3356 fast_mut!((dst)[0;size]).clone_from_slice(src_slice);
3357 } else {
3358 let (dst, src) = data.split_at_mut(off_src);
3359 let src_slice = fast!((src)[0;size]);
3360 fast_mut!((dst)[off_dst;off_dst + size]).clone_from_slice(src_slice);
3361 }
3362 }
3363
3364 #[cfg(feature="unsafe")]
3365 unsafe {
3366 let ptr = data.as_mut_ptr();
3367 let dst = ptr.add(off_dst);
3368 let src = ptr.add(off_src);
3369 core::ptr::copy_nonoverlapping(src, dst, size);
3370 }
3371 true
3372}
3373
3374pub fn BrotliDecoderHasMoreOutput<AllocU8: alloc::Allocator<u8>,
3375 AllocU32: alloc::Allocator<u32>,
3376 AllocHC: alloc::Allocator<HuffmanCode>>
3377 (s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
3378 if is_fatal(s.error_code) {
3380 return false;
3381 }
3382 s.ringbuffer.len() != 0 && CheckRingBufferConsistency(s) && UnwrittenBytes(s, false) != 0
3383}
3384pub fn BrotliDecoderTakeOutput<'a,
3385 AllocU8: alloc::Allocator<u8>,
3386 AllocU32: alloc::Allocator<u32>,
3387 AllocHC: alloc::Allocator<HuffmanCode>>(
3388 s: &'a mut BrotliState<AllocU8, AllocU32, AllocHC>,
3389 size: &mut usize,
3390) -> &'a [u8] {
3391 let one:usize = 1;
3392 let mut available_out = if *size != 0 { *size } else { one << 24 };
3393 let requested_out = available_out;
3394 if (s.ringbuffer.len() == 0) || is_fatal(s.error_code) {
3395 *size = 0;
3396 return &[];
3397 }
3398 if !WrapRingBuffer(s) {
3399 s.error_code = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3400 *size = 0;
3401 return &[];
3402 }
3403 let mut ign = 0usize;
3404 let mut ign2 = 0usize;
3405 let (status, result) = WriteRingBuffer(&mut available_out, None, &mut ign,&mut ign2, true, s);
3406 match status {
3408 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS | BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT => {
3409 *size = requested_out - available_out;
3410 },
3411 _ => {
3412 if is_fatal(status) {
3415 }
3418 *size = 0;
3419 return &[];
3420 }
3421 }
3422 return result;
3423}
3424
3425#[cfg(feature="ffi-api")]
3426pub fn BrotliDecoderIsUsed<AllocU8: alloc::Allocator<u8>,
3427 AllocU32: alloc::Allocator<u32>,
3428 AllocHC: alloc::Allocator<HuffmanCode>>(
3429 s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
3430 !matches!(s.state, BrotliRunningState::BROTLI_STATE_UNINITED)
3431 || bit_reader::BrotliGetAvailableBits(&s.br) != 0
3432}
3433
3434pub fn BrotliDecoderIsFinished<AllocU8: alloc::Allocator<u8>,
3435 AllocU32: alloc::Allocator<u32>,
3436 AllocHC: alloc::Allocator<HuffmanCode>>(
3437 s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
3438 if let BrotliRunningState::BROTLI_STATE_DONE = s.state {
3439 !BrotliDecoderHasMoreOutput(s)
3440 } else {
3441 false
3442 }
3443}
3444
3445pub fn BrotliDecoderGetErrorCode<AllocU8: alloc::Allocator<u8>,
3446 AllocU32: alloc::Allocator<u32>,
3447 AllocHC: alloc::Allocator<HuffmanCode>>(
3448 s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> BrotliDecoderErrorCode {
3449 s.error_code
3450}
3451
3452#[inline(always)]
3455fn huffman_tree<AllocU32: alloc::Allocator<u32>, AllocHC: alloc::Allocator<HuffmanCode>>(
3456 group: &HuffmanTreeGroup<AllocU32, AllocHC>,
3457 index: usize,
3458) -> &[HuffmanCode] {
3459 match group.htrees.slice().get(index) {
3460 Some(offset) => group.codes.slice().get(*offset as usize..).unwrap_or(&[]),
3461 None => &[],
3462 }
3463}
3464
3465#[cfg_attr(target_pointer_width = "64", inline(always))]
3470#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3471fn huffman_window<AllocU32: alloc::Allocator<u32>, AllocHC: alloc::Allocator<HuffmanCode>,
3472 T: huffman::TableWindow>(
3473 group: &HuffmanTreeGroup<AllocU32, AllocHC>,
3474 index: usize,
3475) -> &T {
3476 let offset = group.htrees.slice().get(index).map(|o| *o as usize);
3477 huffman::table_window(group.codes.slice(), offset)
3478}
3479
3480type LiteralTable = [HuffmanCode; LITERAL_TABLE_WINDOW];
3481type InsertCopyTable = [HuffmanCode; INSERT_COPY_TABLE_WINDOW];
3482type DistanceRootTable = [HuffmanCode; DISTANCE_ROOT_WINDOW];
3483
3484#[cfg_attr(target_pointer_width = "64", inline(always))]
3489#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3490fn load_distance_roots<'a, AllocU32: alloc::Allocator<u32>, AllocHC: alloc::Allocator<HuffmanCode>>(
3491 group: &'a HuffmanTreeGroup<AllocU32, AllocHC>,
3492 map: &[u8],
3493 slice_index: usize,
3494) -> [&'a DistanceRootTable; 4] {
3495 let idx: [u8; 4] = match map.get(slice_index..).and_then(|m| m.get(..4)) {
3496 Some(m) => [m[0], m[1], m[2], m[3]],
3497 None => return EMPTY_DISTANCE_ROOTS,
3498 };
3499 let htrees = group.htrees.slice();
3500 let codes = group.codes.slice();
3501 let t0: &DistanceRootTable =
3502 huffman::table_window(codes, htrees.get(idx[0] as usize).map(|&o| o as usize));
3503 let t1 = if idx[1] == idx[0] {
3504 t0
3505 } else {
3506 huffman::table_window(codes, htrees.get(idx[1] as usize).map(|&o| o as usize))
3507 };
3508 let t2 = if idx[2] == idx[1] {
3509 t1
3510 } else if idx[2] == idx[0] {
3511 t0
3512 } else {
3513 huffman::table_window(codes, htrees.get(idx[2] as usize).map(|&o| o as usize))
3514 };
3515 let t3 = if idx[3] == idx[2] {
3516 t2
3517 } else if idx[3] == idx[1] {
3518 t1
3519 } else if idx[3] == idx[0] {
3520 t0
3521 } else {
3522 huffman::table_window(codes, htrees.get(idx[3] as usize).map(|&o| o as usize))
3523 };
3524 [t0, t1, t2, t3]
3525}
3526
3527#[inline(never)]
3530fn fill_context_trees<'a, AllocU32: alloc::Allocator<u32>, AllocHC: alloc::Allocator<HuffmanCode>>(
3531 trees: &mut [&'a LiteralTable; 64],
3532 group: &'a HuffmanTreeGroup<AllocU32, AllocHC>,
3533 context_map: &[u8],
3534 slice_index: usize,
3535) {
3536 match context_map.get(slice_index..).and_then(|map| map.get(..64)) {
3537 Some(map) => {
3538 let htrees = group.htrees.slice();
3542 let codes = group.codes.slice();
3543 let mut prev_index = usize::MAX;
3544 let mut prev_tree: &'a LiteralTable = &EMPTY_LITERAL_TABLE;
3545 for (tree, &index) in trees.iter_mut().zip(map.iter()) {
3546 let idx = index as usize;
3547 if idx != prev_index {
3548 prev_index = idx;
3549 prev_tree = huffman::table_window(codes, htrees.get(idx).map(|&o| o as usize));
3550 }
3551 *tree = prev_tree;
3552 }
3553 }
3554 None => *trees = EMPTY_CONTEXT_TREES,
3555 }
3556}
3557
3558#[cfg_attr(target_pointer_width = "64", inline(always))]
3562#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3563fn decode_block_type_and_length_slice<'a, AllocHC: alloc::Allocator<HuffmanCode>>(
3564 btl: &mut BlockTypeAndLengthState<AllocHC>,
3565 mut fbr: bit_reader::BitReaderSlice<'a>,
3566 tree_type: i32,
3567) -> (bit_reader::BitReaderSlice<'a>, BrotliDecoderErrorCode) {
3568 let mut temp_br = bit_reader::BrotliBitReader {
3570 val_: fbr.val,
3571 bit_pos_: fbr.avail_bits,
3572 next_in: 0,
3573 avail_in: fbr.rem.len() as u32,
3574 };
3575 let status = DecodeBlockTypeAndLength(false, btl, &mut temp_br, tree_type, fbr.rem);
3576 fbr.val = temp_br.val_;
3577 fbr.avail_bits = temp_br.bit_pos_;
3578 fbr.rem = &fbr.rem[temp_br.next_in as usize..];
3579 (fbr, status)
3580}
3581
3582#[derive(Clone, Copy)]
3583enum LiteralBatchStatus {
3584 Decoded,
3585 NotHandled,
3586 CorruptInput,
3587}
3588
3589#[inline(always)]
3590fn decode_literal_batch<'b>(
3591 rb: &mut [u8],
3592 pos: usize,
3593 count: usize,
3594 trivial_literal_context: i32,
3595 literal_htree: &LiteralTable,
3596 context_trees: &[&LiteralTable; 64],
3597 context_lookup: &[u8; 512],
3598 mut fbr: bit_reader::BitReaderSlice<'b>,
3599) -> (bit_reader::BitReaderSlice<'b>, LiteralBatchStatus) {
3600 if trivial_literal_context != 0 {
3601 let ring_window = match rb.get_mut(pos..).and_then(|w| w.get_mut(..count)) {
3602 Some(w) => w,
3603 None => return (fbr, LiteralBatchStatus::NotHandled),
3604 };
3605 for dst in ring_window.iter_mut() {
3606 if !fbr.fill16_checked() {
3607 mark_unlikely();
3608 return (fbr, LiteralBatchStatus::CorruptInput);
3609 }
3610 *dst = decode_symbol_no_fill(&mut fbr, literal_htree) as u8;
3611 }
3612 (fbr, LiteralBatchStatus::Decoded)
3613 } else {
3614 let start = pos.wrapping_sub(2);
3615 let len = count + 2;
3616 let (p2_init, p1_init, ring_window) =
3617 match rb.get_mut(start..).and_then(|w| w.get_mut(..len)) {
3618 Some([p2_init, p1_init, ring_window @ ..]) => (p2_init, p1_init, ring_window),
3619 _ => return (fbr, LiteralBatchStatus::NotHandled),
3620 };
3621 let mut p1: u8 = *p1_init;
3622 let mut p2: u8 = *p2_init;
3623 for dst in ring_window.iter_mut() {
3624 if !fbr.fill16_checked() {
3625 mark_unlikely();
3626 return (fbr, LiteralBatchStatus::CorruptInput);
3627 }
3628 let context = (context_lookup[p1 as usize] | context_lookup[(p2 as usize) | 256]) as usize;
3629 let hc = context_trees[context & 63];
3630 p2 = p1;
3631 p1 = decode_symbol_no_fill(&mut fbr, hc) as u8;
3632 *dst = p1;
3633 }
3634 (fbr, LiteralBatchStatus::Decoded)
3635 }
3636}
3637
3638#[cold]
3639#[inline(never)]
3640fn execute_custom_shared_dictionary_copy<AllocU8: alloc::Allocator<u8>, AllocU32: alloc::Allocator<u32>>(
3641 shared_dict: &::shared_dictionary::BrotliSharedDictionary<AllocU8, AllocU32>,
3642 context_lookup: &[u8; 512],
3643 dist_rb_idx: &mut i32,
3644 meta_block_remaining_len: &mut i32,
3645 mut pos: i32,
3646 rb: &mut [u8],
3647 rb_size: i32,
3648 rb_mask: i32,
3649 distance_code: i32,
3650 max_distance: i32,
3651 distance_context: i32,
3652 copy_len: i32,
3653 compound_dictionary_size: u32,
3654) -> Result<(i32, bool), BrotliDecoderErrorCode> {
3655 let dict_id = if shared_dict.context_based {
3656 let p1 = rb[(pos.wrapping_sub(1) as usize) & (rb_mask as usize)];
3657 let p2 = rb[(pos.wrapping_sub(2) as usize) & (rb_mask as usize)];
3658 let context = (context_lookup[p1 as usize] | context_lookup[p2 as usize | 256]) as usize;
3659 shared_dict.context_map[context]
3660 } else {
3661 0
3662 };
3663 let address = distance_code - max_distance - 1 - compound_dictionary_size as i32;
3664 *dist_rb_idx += distance_context;
3665 let lookup = shared_dict.lookup(dict_id, copy_len, address).map_err(|why| match why {
3666 DictionaryLookupError::LengthNotEncodable =>
3667 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DICTIONARY,
3668 DictionaryLookupError::AddressOutOfRange =>
3669 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM,
3670 })?;
3671 let mut len = copy_len;
3672 let word = lookup.words.word(len, lookup.word_idx);
3673 if lookup.transform_idx == lookup.transforms.cutoff_identity() {
3674 rb[pos as usize..(pos + len) as usize].clone_from_slice(word);
3675 } else {
3676 len = lookup.transforms.apply(&mut rb[pos as usize..], word, len, lookup.transform_idx);
3677 if len == 0 && distance_code <= 120 {
3678 return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
3679 }
3680 }
3681 pos += len;
3682 *meta_block_remaining_len -= len;
3683 Ok((pos, pos >= rb_size))
3684}
3685
3686#[inline(always)]
3689fn execute_dictionary_copy<AllocU8: alloc::Allocator<u8>, AllocU32: alloc::Allocator<u32>>(
3690 compound_dictionary: &mut state::BrotliDecoderCompoundDictionary<AllocU8>,
3691 shared_dict: &::shared_dictionary::BrotliSharedDictionary<AllocU8, AllocU32>,
3692 context_lookup: &[u8; 512],
3693 dist_rb: &mut [i32; 4],
3694 dist_rb_idx: &mut i32,
3695 meta_block_remaining_len: &mut i32,
3696 mut pos: i32,
3697 rb: &mut [u8],
3698 rb_size: i32,
3699 rb_mask: i32,
3700 distance_code: i32,
3701 max_distance: i32,
3702 distance_context: i32,
3703 copy_len: i32,
3704 external_dictionary: &[u8],
3705) -> Result<(i32, bool), BrotliDecoderErrorCode> {
3706 if distance_code > kBrotliMaxAllowedDistance as i32 {
3707 return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE);
3708 }
3709 let compound_dictionary_size = compound_dictionary.total_size as u32;
3710 if (distance_code - max_distance) as u32 <= compound_dictionary_size {
3713 let address = compound_dictionary_size - (distance_code - max_distance) as u32;
3714 let address = address as usize;
3715 let length = copy_len as usize;
3716 if compound_dictionary.num_chunks == 1 && ((rb_size - pos) as usize) > length {
3720 if length > compound_dictionary.total_size - address {
3721 return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY);
3722 }
3723 let chunk = match compound_dictionary.chunks[0] {
3724 state::MaybeOwnedSlice::External(_) => external_dictionary,
3725 ref chunk => chunk.slice(),
3726 };
3727 let (dst, src) = match (rb.get_mut(pos as usize..pos as usize + length),
3728 chunk.get(address..address + length)) {
3729 (Some(dst), Some(src)) => (dst, src),
3730 _ => return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY),
3731 };
3732 dist_rb[(*dist_rb_idx & 3) as usize] = distance_code;
3733 *dist_rb_idx += 1;
3734 *meta_block_remaining_len -= copy_len;
3735 copy_bytes(dst, src);
3736 return Ok((pos + copy_len, false));
3737 }
3738 if !InitializeCompoundDictionaryCopy(compound_dictionary, address, length) {
3739 return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY);
3740 }
3741 dist_rb[(*dist_rb_idx & 3) as usize] = distance_code;
3742 *dist_rb_idx += 1;
3743 *meta_block_remaining_len -= copy_len;
3744 pos += CopyFromCompoundDictionary(compound_dictionary, rb, rb_size, pos, external_dictionary);
3745 return Ok((pos, pos >= rb_size));
3746 }
3747 if shared_dict.is_custom()
3748 && copy_len >= SHARED_BROTLI_MIN_DICTIONARY_WORD_LENGTH as i32
3749 && copy_len <= SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH as i32
3750 {
3751 return execute_custom_shared_dictionary_copy(
3752 shared_dict,
3753 context_lookup,
3754 dist_rb_idx,
3755 meta_block_remaining_len,
3756 pos,
3757 rb,
3758 rb_size,
3759 rb_mask,
3760 distance_code,
3761 max_distance,
3762 distance_context,
3763 copy_len,
3764 compound_dictionary_size,
3765 );
3766 }
3767 if copy_len >= kBrotliMinDictionaryWordLength as i32
3768 && copy_len <= kBrotliMaxDictionaryWordLength as i32
3769 {
3770 let mut offset = fast!((kBrotliDictionaryOffsetsByLength)[copy_len as usize]) as i32;
3771 let word_id = distance_code - max_distance - 1 - compound_dictionary_size as i32;
3772 let shift = fast!((kBrotliDictionarySizeBitsByLength)[copy_len as usize]);
3773 let mask = bit_reader::BitMask(shift as u32) as i32;
3774 let word_idx = word_id & mask;
3775 let transform_idx = word_id >> shift;
3776 *dist_rb_idx += distance_context;
3777 offset += word_idx * copy_len;
3778 if transform_idx >= kNumTransforms {
3779 return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
3780 }
3781 let mut len = copy_len;
3782 let word = fast!((kBrotliDictionary)[offset as usize ; (offset + len) as usize]);
3783 if transform_idx == 0 {
3784 copy_bytes(&mut rb[pos as usize..(pos + len) as usize], word);
3785 } else {
3786 len = TransformDictionaryWord(&mut rb[pos as usize..], word, len, transform_idx);
3787 }
3788 pos += len;
3789 *meta_block_remaining_len -= len;
3790 return Ok((pos, pos >= rb_size));
3791 }
3792 Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DICTIONARY)
3793}
3794
3795#[cfg_attr(target_pointer_width = "64", inline(always))]
3798#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3799fn copy_wrap_or_overlapping(
3800 rb: &mut [u8],
3801 rb_size: i32,
3802 rb_mask: i32,
3803 mut pos: i32,
3804 mut rem: i32,
3805 distance_code: i32,
3806) -> (i32, i32, bool) {
3807 let rb_mask_usize = (rb_mask as usize) & 0x7fff_ffff;
3808 if rb.len() <= rb_mask_usize {
3809 return (pos, rem, false);
3810 }
3811 let mut wrap_guard = rb_size - pos;
3812 if rem >= 16 && pos >= 0 && wrap_guard > 0 && distance_code > 0 && distance_code <= pos {
3813 let count = core::cmp::min(rem, wrap_guard);
3814 if copy_overlapping_backreference(rb, pos as usize, distance_code as usize, count as usize) {
3815 pos += count;
3816 rem -= count;
3817 wrap_guard -= count;
3818 if wrap_guard == 0 {
3819 return (pos, rem, true);
3820 }
3821 }
3822 }
3823 while rem > 0 {
3824 rem -= 1;
3825 rb[(pos as usize) & rb_mask_usize] =
3826 rb[(pos.wrapping_sub(distance_code) as usize) & rb_mask_usize];
3827 pos += 1;
3828 wrap_guard -= 1;
3829 if wrap_guard == 0 {
3830 return (pos, rem, true);
3831 }
3832 }
3833 (pos, rem, false)
3834}
3835
3836#[inline(always)]
3837fn save_mid_command_state<AllocU8: alloc::Allocator<u8>,
3838 AllocU32: alloc::Allocator<u32>,
3839 AllocHC: alloc::Allocator<HuffmanCode>>(
3840 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
3841 i: i32,
3842 distance_code: i32,
3843 distance_context: i32,
3844 copy_length: i32,
3845) {
3846 s.loop_counter = i;
3847 s.distance_code = distance_code;
3848 s.distance_context = distance_context;
3849 s.copy_length = copy_length;
3850 if let Some(&idx) = s
3851 .dist_context_map
3852 .slice()
3853 .get(s.dist_context_map_slice_index + (distance_context as usize & 3))
3854 {
3855 s.dist_htree_index = idx;
3856 }
3857}
3858
3859#[inline(always)]
3866fn ProcessCommandsInternal<
3867 M: CommandLoopMode,
3868 AllocU8: alloc::Allocator<u8>,
3869 AllocU32: alloc::Allocator<u32>,
3870 AllocHC: alloc::Allocator<HuffmanCode>,
3871>(
3872 single_command: bool,
3873 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
3874 input: &[u8],
3875 dictionary: &[u8],
3876) -> BrotliDecoderErrorCode {
3877 if M::SAFE {
3878 if (!CheckInputAmount(true, &s.br, 28)) || (!WarmupBitReader(true, &mut s.br, input)) {
3879 mark_unlikely();
3880 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
3881 }
3882 if !matches!(
3883 s.state,
3884 BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN
3885 | BrotliRunningState::BROTLI_STATE_COMMAND_INNER
3886 | BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
3887 | BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY
3888 ) {
3889 mark_unlikely();
3890 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3891 }
3892 }
3893
3894 let rb_size = s.ringbuffer_size;
3895 let rb_mask = s.ringbuffer_mask;
3896 let mut pos = s.pos;
3897 if !M::SAFE && (rb_size < 2 || (rb_size & (rb_size - 1)) != 0 || rb_mask != rb_size - 1 || pos < 0) {
3898 mark_unlikely();
3899 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3900 }
3901 let rb_mask_usize = (rb_mask as usize) & 0x7fff_ffff;
3902 let min_rb_len = rb_mask_usize + kRingBufferAllocationSlack;
3903 if !M::SAFE && (pos >= rb_size || s.ringbuffer.slice().len() < min_rb_len) {
3904 mark_unlikely();
3905 return SafeProcessCommands(s, input, dictionary);
3906 }
3907
3908 let mut fbr = if !M::SAFE {
3909 match bit_reader::BitReaderSlice::new(&s.br, input) {
3910 Some(r) => r,
3911 None => {
3912 mark_unlikely();
3913 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3914 }
3915 }
3916 } else {
3917 bit_reader::BitReaderSlice::empty()
3918 };
3919 let rb: &mut [u8] = if !M::SAFE {
3920 match s.ringbuffer.slice_mut().get_mut(..min_rb_len) {
3921 Some(r) => r,
3922 None => {
3923 mark_unlikely();
3924 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3925 }
3926 }
3927 } else {
3928 s.ringbuffer.slice_mut()
3929 };
3930
3931 let mut insert_copy_tree: &InsertCopyTable = huffman_window(&s.insert_copy_hgroup, s.htree_command_index as usize);
3932 let mut literal_htree: &LiteralTable = huffman_window(&s.literal_hgroup, s.literal_htree_index as usize);
3933 let mut context_trees: [&LiteralTable; 64] = EMPTY_CONTEXT_TREES;
3934 let mut context_trees_slice: Option<usize> = None;
3935 let mut distance_tree_index = s.dist_htree_index;
3936 let mut distance_tree: &[HuffmanCode] = if M::SAFE {
3937 huffman_tree(&s.distance_hgroup, distance_tree_index as usize)
3938 } else {
3939 &[]
3940 };
3941 let mut distance_roots: [&DistanceRootTable; 4] = if !M::SAFE {
3946 load_distance_roots(&s.distance_hgroup, s.dist_context_map.slice(), s.dist_context_map_slice_index)
3947 } else {
3948 EMPTY_DISTANCE_ROOTS
3949 };
3950 if !M::SAFE && s.trivial_literal_context == 0 {
3951 fill_context_trees(
3952 &mut context_trees,
3953 &s.literal_hgroup,
3954 s.context_map.slice(),
3955 s.context_map_slice_index,
3956 );
3957 context_trees_slice = Some(s.context_map_slice_index);
3958 }
3959
3960 let mut state = if M::SAFE {
3961 core::mem::replace(&mut s.state, BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN)
3962 } else {
3963 BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN
3964 };
3965 if M::SAFE
3966 && !matches!(
3967 state,
3968 BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN
3969 | BrotliRunningState::BROTLI_STATE_COMMAND_INNER
3970 | BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
3971 | BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY
3972 )
3973 {
3974 s.state = state;
3975 return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3976 }
3977 let mut i: i32 = if M::SAFE { s.loop_counter } else { 0 };
3978 let mut distance_code: i32 = if M::SAFE { s.distance_code } else { 0 };
3979 let mut distance_context: i32 = if M::SAFE { s.distance_context } else { 0 };
3980 let mut copy_length: i32 = if M::SAFE { s.copy_length } else { 0 };
3981
3982 let mut exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
3983 let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
3984 let mut mid_cmd: Option<(i32, i32, i32, i32)> = None;
3985
3986 'cmd: loop {
3987 if !M::SAFE {
3988 i = 0;
3989 distance_code = 0;
3990 distance_context = 0;
3991 copy_length = 0;
3992 }
3993 if !M::SAFE || matches!(state, BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN) {
3994 if !M::SAFE && !fbr.has_input() {
3995 mark_unlikely();
3996 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
3997 break 'cmd;
3998 }
3999 if s.block_type_length_state.block_length[1] == 0 {
4000 mark_unlikely();
4001 let status = if !M::SAFE {
4002 let (next_fbr, st) =
4003 decode_block_type_and_length_slice(&mut s.block_type_length_state, fbr, 1);
4004 fbr = next_fbr;
4005 if matches!(st, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4006 s.htree_command_index = s.block_type_length_state.block_type_rb[3] as u16;
4007 insert_copy_tree = huffman_window(&s.insert_copy_hgroup, s.htree_command_index as usize);
4008 }
4009 st
4010 } else {
4011 let st = DecodeBlockTypeAndLength(
4012 true,
4013 &mut s.block_type_length_state,
4014 &mut s.br,
4015 1,
4016 input,
4017 );
4018 if matches!(st, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4019 s.htree_command_index = s.block_type_length_state.block_type_rb[3] as u16;
4020 insert_copy_tree = huffman_window(&s.insert_copy_hgroup, s.htree_command_index as usize);
4021 }
4022 st
4023 };
4024 if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4025 result = status;
4026 break 'cmd;
4027 }
4028 continue 'cmd;
4029 }
4030
4031 if !read_command::<M>(
4032 &mut fbr,
4033 &mut s.br,
4034 input,
4035 &mut distance_code,
4036 &mut distance_context,
4037 &mut copy_length,
4038 &mut s.block_type_length_state.block_length[1],
4039 &mut i,
4040 insert_copy_tree,
4041 ) {
4042 mark_unlikely();
4043 result = if M::SAFE {
4044 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT
4045 } else {
4046 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE
4047 };
4048 break 'cmd;
4049 }
4050
4051 if M::SAFE {
4052 if i == 0 {
4053 state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4054 } else {
4055 s.meta_block_remaining_len -= i;
4056 state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4057 }
4058 } else if i != 0 {
4059 s.meta_block_remaining_len -= i;
4060 }
4061 }
4062
4063 if (!M::SAFE && i != 0) || (M::SAFE && matches!(state, BrotliRunningState::BROTLI_STATE_COMMAND_INNER)) {
4064 'inner: loop {
4065 if !M::SAFE {
4066 let i_u32 = i as u32;
4067 let block_len = s.block_type_length_state.block_length[0];
4068 let mut handled = false;
4069 if i > 0 && i_u32 <= block_len && pos < rb_size - i && i_u32 * 2 + 34 <= fbr.avail_in() {
4070 let (next_fbr, status) = decode_literal_batch(
4071 rb,
4072 pos as usize,
4073 i as usize,
4074 s.trivial_literal_context,
4075 literal_htree,
4076 &context_trees,
4077 s.context_lookup,
4078 fbr,
4079 );
4080 fbr = next_fbr;
4081 match status {
4082 LiteralBatchStatus::Decoded => {
4083 pos += i;
4084 s.block_type_length_state.block_length[0] -= i_u32;
4085 handled = true;
4086 }
4087 LiteralBatchStatus::NotHandled => {}
4088 LiteralBatchStatus::CorruptInput => {
4089 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
4090 break 'cmd;
4091 }
4092 }
4093 }
4094 if handled {
4095 break 'inner;
4096 }
4097 mark_unlikely();
4098 }
4099
4100 let mut p1: u8 = if !M::SAFE {
4101 rb[(pos.wrapping_sub(1) as usize) & rb_mask_usize]
4102 } else if rb.is_empty() {
4103 0
4104 } else {
4105 fast!((rb)[((pos - 1) & rb_mask) as usize])
4106 };
4107 let mut p2: u8 = if !M::SAFE {
4108 rb[(pos.wrapping_sub(2) as usize) & rb_mask_usize]
4109 } else if rb.is_empty() {
4110 0
4111 } else {
4112 fast!((rb)[((pos - 2) & rb_mask) as usize])
4113 };
4114 loop {
4115 if !M::SAFE && !fbr.has_input() {
4116 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4117 mid_cmd = Some((i, distance_code, distance_context, copy_length));
4118 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4119 break 'cmd;
4120 }
4121 if s.block_type_length_state.block_length[0] == 0 {
4122 if !M::SAFE {
4123 mark_unlikely();
4124 let status = if !fbr.has_input() {
4125 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT
4126 } else {
4127 let (next_fbr, st) =
4128 decode_block_type_and_length_slice(&mut s.block_type_length_state, fbr, 0);
4129 fbr = next_fbr;
4130 st
4131 };
4132 if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4133 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4134 mid_cmd = Some((i, distance_code, distance_context, copy_length));
4135 result = status;
4136 break 'cmd;
4137 }
4138 update_literal_block_state(
4139 &s.block_type_length_state.block_type_rb,
4140 &s.trivial_literal_contexts,
4141 s.context_map.slice(),
4142 s.context_modes.slice(),
4143 &mut s.context_map_slice_index,
4144 &mut s.trivial_literal_context,
4145 &mut s.literal_htree_index,
4146 &mut s.context_lookup,
4147 );
4148 literal_htree = huffman_window(&s.literal_hgroup, s.literal_htree_index as usize);
4149 if s.trivial_literal_context == 0
4150 && context_trees_slice != Some(s.context_map_slice_index)
4151 {
4152 fill_context_trees(
4153 &mut context_trees,
4154 &s.literal_hgroup,
4155 s.context_map.slice(),
4156 s.context_map_slice_index,
4157 );
4158 context_trees_slice = Some(s.context_map_slice_index);
4159 }
4160 continue 'inner;
4161 } else {
4162 mark_unlikely();
4163 let status = DecodeBlockTypeAndLength(
4164 true,
4165 &mut s.block_type_length_state,
4166 &mut s.br,
4167 0,
4168 input,
4169 );
4170 if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4171 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4172 mid_cmd = Some((i, distance_code, distance_context, copy_length));
4173 result = status;
4174 break 'cmd;
4175 }
4176 update_literal_block_state(
4177 &s.block_type_length_state.block_type_rb,
4178 &s.trivial_literal_contexts,
4179 s.context_map.slice(),
4180 s.context_modes.slice(),
4181 &mut s.context_map_slice_index,
4182 &mut s.trivial_literal_context,
4183 &mut s.literal_htree_index,
4184 &mut s.context_lookup,
4185 );
4186 literal_htree = huffman_window(&s.literal_hgroup, s.literal_htree_index as usize);
4187 if s.block_type_length_state.block_length[0] == 0 {
4188 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4189 mid_cmd = Some((i, distance_code, distance_context, copy_length));
4190 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
4191 break 'cmd;
4192 }
4193 }
4194 }
4195 let hc = if s.trivial_literal_context != 0 {
4196 literal_htree
4197 } else if !M::SAFE {
4198 let context = (s.context_lookup[p1 as usize] | s.context_lookup[p2 as usize | 256]) as usize;
4199 context_trees[context & 63]
4200 } else {
4201 let context = (s.context_lookup[p1 as usize] | s.context_lookup[p2 as usize | 256]) as usize;
4202 let idx = fast_slice!((s.context_map)[s.context_map_slice_index + (context & 63)]);
4203 huffman_window(&s.literal_hgroup, idx as usize)
4204 };
4205 let lit = if !M::SAFE {
4206 read_symbol_slice(&mut fbr, hc) as u8
4207 } else {
4208 let mut sym = 0u32;
4209 if !SafeReadSymbol(hc, &mut s.br, &mut sym, input) {
4210 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4211 mid_cmd = Some((i, distance_code, distance_context, copy_length));
4212 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4213 break 'cmd;
4214 }
4215 sym as u8
4216 };
4217 p2 = p1;
4218 p1 = lit;
4219 if !M::SAFE {
4220 rb[(pos as usize) & rb_mask_usize] = lit;
4221 } else {
4222 fast_mut!((rb)[pos as usize]) = lit;
4223 }
4224 s.block_type_length_state.block_length[0] -= 1;
4225 pos += 1;
4226 if pos == rb_size {
4227 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE;
4228 mid_cmd = Some((i - 1, distance_code, distance_context, copy_length));
4229 break 'cmd;
4230 }
4231 i -= 1;
4232 if i == 0 {
4233 break 'inner;
4234 }
4235 }
4236 }
4237 if s.meta_block_remaining_len <= 0 {
4238 mark_unlikely();
4239 exit_state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4240 break 'cmd;
4241 }
4242 if M::SAFE {
4243 state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4244 }
4245 }
4246
4247 if !M::SAFE || matches!(state, BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) {
4248 if distance_code >= 0 {
4249 distance_context = if distance_code != 0 { 0 } else { 1 };
4250 s.dist_rb_idx -= 1;
4251 distance_code = s.dist_rb[(s.dist_rb_idx & 3) as usize];
4252 } else {
4253 if s.block_type_length_state.block_length[2] == 0 {
4254 mark_unlikely();
4255 let status = if !M::SAFE {
4256 if !fbr.has_input() {
4257 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT
4258 } else {
4259 let (next_fbr, st) =
4260 decode_block_type_and_length_slice(&mut s.block_type_length_state, fbr, 2);
4261 fbr = next_fbr;
4262 st
4263 }
4264 } else {
4265 DecodeBlockTypeAndLength(
4266 true,
4267 &mut s.block_type_length_state,
4268 &mut s.br,
4269 2,
4270 input,
4271 )
4272 };
4273 if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4274 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4275 mid_cmd = Some((0, distance_code, distance_context, copy_length));
4276 result = status;
4277 break 'cmd;
4278 }
4279 s.dist_context_map_slice_index =
4280 (s.block_type_length_state.block_type_rb[5] << kDistanceContextBits) as usize;
4281 if !M::SAFE {
4282 distance_roots = load_distance_roots(
4283 &s.distance_hgroup,
4284 s.dist_context_map.slice(),
4285 s.dist_context_map_slice_index,
4286 );
4287 }
4288 }
4289 let memento = if M::SAFE {
4290 bit_reader::BrotliBitReaderSaveState(&s.br)
4291 } else {
4292 bit_reader::BrotliBitReaderState::default()
4293 };
4294 let dist_sym = if !M::SAFE {
4295 let distance_root = distance_roots[(distance_context as usize) & 3];
4296 fbr.fill16();
4297 let bits = fbr.val as u32;
4298 let table_index = (bits & HUFFMAN_TABLE_MASK) as usize;
4299 let root = distance_root.entry(table_index);
4300 let (sym, consumed) = if root.bits > HUFFMAN_TABLE_BITS as u8 {
4301 decode_distance_subtable(
4302 bits,
4303 table_index,
4304 root,
4305 &s.distance_hgroup,
4306 s.dist_context_map.slice(),
4307 s.dist_context_map_slice_index,
4308 distance_context,
4309 )
4310 } else {
4311 (root.value as usize, root.bits as u32)
4312 };
4313 fbr.avail_bits = fbr.avail_bits.wrapping_sub(consumed);
4314 fbr.val >>= consumed & bit_reader::SLICE_SHIFT_MASK;
4315 sym
4316 } else {
4317 let idx = fast_slice!((s.dist_context_map)[s.dist_context_map_slice_index + (distance_context as usize & 3)]);
4318 s.dist_htree_index = idx;
4319 if idx != distance_tree_index {
4320 distance_tree_index = idx;
4321 distance_tree = huffman_tree(&s.distance_hgroup, idx as usize);
4322 }
4323 let mut sym: u32 = 0;
4324 if !SafeReadSymbol(distance_tree, &mut s.br, &mut sym, input) {
4325 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4326 mid_cmd = Some((0, distance_code, distance_context, copy_length));
4327 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4328 break 'cmd;
4329 }
4330 sym as usize
4331 };
4332 if !read_distance::<M>(
4333 dist_sym,
4334 &memento,
4335 &mut fbr,
4336 &mut s.br,
4337 input,
4338 &mut distance_code,
4339 &mut distance_context,
4340 &mut s.dist_rb_idx,
4341 &s.dist_rb,
4342 &mut s.block_type_length_state.block_length[2],
4343 s.distance_postfix_bits,
4344 s.distance_postfix_mask,
4345 s.num_direct_distance_codes,
4346 ) {
4347 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4348 mid_cmd = Some((0, distance_code, distance_context, copy_length));
4349 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4350 break 'cmd;
4351 }
4352 }
4353
4354 let max_backward_distance = s.max_backward_distance;
4355 let mut max_distance = s.max_distance;
4356 if max_distance != max_backward_distance {
4357 max_distance = if pos < max_backward_distance {
4358 pos
4359 } else {
4360 max_backward_distance
4361 };
4362 s.max_distance = max_distance;
4363 }
4364
4365 i = copy_length;
4366 if distance_code > max_distance {
4367 mark_unlikely();
4368 match execute_dictionary_copy(
4369 &mut s.compound_dictionary,
4370 &s.dictionary,
4371 s.context_lookup,
4372 &mut s.dist_rb,
4373 &mut s.dist_rb_idx,
4374 &mut s.meta_block_remaining_len,
4375 pos,
4376 rb,
4377 rb_size,
4378 rb_mask,
4379 distance_code,
4380 max_distance,
4381 distance_context,
4382 i,
4383 dictionary,
4384 ) {
4385 Ok((next_pos, true)) => {
4386 pos = next_pos;
4387 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1;
4388 mid_cmd = Some((i, distance_code, distance_context, copy_length));
4389 break 'cmd;
4390 }
4391 Ok((next_pos, false)) => {
4392 pos = next_pos;
4393 if s.meta_block_remaining_len <= 0 {
4394 exit_state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4395 break 'cmd;
4396 }
4397 if M::SAFE {
4398 state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
4399 if single_command {
4400 break 'cmd;
4401 }
4402 }
4403 continue 'cmd;
4404 }
4405 Err(err) => {
4406 result = err;
4407 break 'cmd;
4408 }
4409 }
4410 }
4411
4412 s.dist_rb[(s.dist_rb_idx & 3) as usize] = distance_code;
4413 s.dist_rb_idx += 1;
4414 s.meta_block_remaining_len -= i;
4415
4416 let src_start = (pos.wrapping_sub(distance_code) as usize) & rb_mask_usize;
4417 let dst_start = (pos as usize) & rb_mask_usize;
4418 let src_start_u32 = src_start as u32;
4419 let dst_start_u32 = pos as u32;
4420 let copy_len_u32 = i as u32;
4421 let lo = core::cmp::min(dst_start_u32, src_start_u32);
4422 let hi = core::cmp::max(dst_start_u32, src_start_u32);
4423 if hi - lo < copy_len_u32 || hi.wrapping_add(copy_len_u32) >= rb_size as u32 {
4431 mark_unlikely();
4432 if M::SAFE {
4433 if rb.len() < 32 {
4434 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE;
4435 break 'cmd;
4436 }
4437 state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
4438 } else {
4439 let (next_pos, next_i, wrapped) =
4440 copy_wrap_or_overlapping(rb, rb_size, rb_mask, pos, i, distance_code);
4441 pos = next_pos;
4442 i = next_i;
4443 if wrapped {
4444 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2;
4445 mid_cmd = Some((i, distance_code, distance_context, copy_length));
4446 break 'cmd;
4447 }
4448 }
4449 } else {
4450 if !memmove16_from_ringbuffer(rb, dst_start_u32, src_start_u32) {
4451 mark_unlikely();
4452 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE;
4453 break 'cmd;
4454 }
4455 pos += i;
4456 if i > 16 {
4457 let copy_ok = if i > 32 {
4458 memcpy_within_slice(rb, dst_start + 16, src_start + 16, (i - 16) as usize)
4459 } else {
4460 memmove16_offset16(rb, dst_start_u32, src_start_u32)
4461 };
4462 if !copy_ok {
4463 mark_unlikely();
4464 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE;
4465 break 'cmd;
4466 }
4467 }
4468 }
4469 }
4470
4471 if M::SAFE && matches!(state, BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY) {
4472 let (next_pos, next_i, wrapped) =
4473 copy_wrap_or_overlapping(rb, rb_size, rb_mask, pos, i, distance_code);
4474 pos = next_pos;
4475 i = next_i;
4476 if wrapped {
4477 exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2;
4478 mid_cmd = Some((i, distance_code, distance_context, copy_length));
4479 break 'cmd;
4480 }
4481 }
4482
4483 if s.meta_block_remaining_len <= 0 {
4484 mark_unlikely();
4485 exit_state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4486 break 'cmd;
4487 }
4488 if M::SAFE {
4489 state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
4490 if single_command {
4491 break 'cmd;
4492 }
4493 }
4494 }
4495
4496 if !M::SAFE {
4497 fbr.sync_to(&mut s.br);
4498 }
4499 s.state = exit_state;
4500 s.pos = pos;
4501 if let Some((rem_i, d_code, d_ctx, c_len)) = mid_cmd {
4502 save_mid_command_state(s, rem_i, d_code, d_ctx, c_len);
4503 }
4504 result
4505}
4506
4507#[inline(never)]
4511fn ProcessCommands<AllocU8: alloc::Allocator<u8>,
4512 AllocU32: alloc::Allocator<u32>,
4513 AllocHC: alloc::Allocator<HuffmanCode>>
4514 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
4515 input: &[u8],
4516 dictionary: &[u8])
4517 -> BrotliDecoderErrorCode {
4518 if (!CheckInputAmount(false, &s.br, 28)) || (!WarmupBitReader(false, &mut s.br, input)) {
4519 mark_unlikely();
4520 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4521 }
4522 if !matches!(s.state, BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN) {
4523 mark_unlikely();
4524 let status = SafeProcessCommandsEntry(true, s, input, dictionary);
4525 if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS)
4526 || !matches!(s.state, BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN)
4527 {
4528 return status;
4529 }
4530 if (!CheckInputAmount(false, &s.br, 28)) || (!WarmupBitReader(false, &mut s.br, input)) {
4531 return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4532 }
4533 }
4534 ProcessCommandsInternal::<FastCommandLoop, _, _, _>(false, s, input, dictionary)
4535}
4536
4537#[inline(never)]
4538fn SafeProcessCommandsEntry<AllocU8: alloc::Allocator<u8>,
4539 AllocU32: alloc::Allocator<u32>,
4540 AllocHC: alloc::Allocator<HuffmanCode>>
4541 (single_command: bool,
4542 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
4543 input: &[u8],
4544 dictionary: &[u8])
4545 -> BrotliDecoderErrorCode {
4546 ProcessCommandsInternal::<SafeCommandLoop, _, _, _>(single_command, s, input, dictionary)
4547}
4548
4549#[inline(always)]
4550fn SafeProcessCommands<AllocU8: alloc::Allocator<u8>,
4551 AllocU32: alloc::Allocator<u32>,
4552 AllocHC: alloc::Allocator<HuffmanCode>>
4553 (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
4554 input: &[u8],
4555 dictionary: &[u8])
4556 -> BrotliDecoderErrorCode {
4557 SafeProcessCommandsEntry(false, s, input, dictionary)
4558}
4559
4560pub fn BrotliMaxDistanceSymbol(ndirect: u32, npostfix: u32) -> u32{
4563 let bound:[u32;kBrotliMaxPostfix + 1] = [0, 4, 12, 28];
4564 let diff:[u32;kBrotliMaxPostfix + 1] = [73, 126, 228, 424];
4565 let postfix = 1 << npostfix;
4566 if (ndirect < bound[npostfix as usize ]) {
4567 return ndirect + diff[npostfix as usize] + postfix;
4568 } else if (ndirect > bound[npostfix as usize] + postfix) {
4569 return ndirect + diff[npostfix as usize];
4570 } else {
4571 return bound[npostfix as usize] + diff[npostfix as usize] + postfix;
4572 }
4573}
4574
4575pub fn BrotliDecompressStream<AllocU8: alloc::Allocator<u8>,
4576 AllocU32: alloc::Allocator<u32>,
4577 AllocHC: alloc::Allocator<HuffmanCode>>
4578 (available_in: &mut usize,
4579 input_offset: &mut usize,
4580 xinput: &[u8],
4581 available_out: &mut usize,
4582 output_offset: &mut usize,
4583 output: &mut [u8],
4584 total_out: &mut usize,
4585 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
4586 -> BrotliResult {
4587 BrotliDecompressStreamWithDictionaryAndMetadata(
4588 available_in, input_offset, xinput,
4589 available_out, output_offset, output,
4590 total_out, &[], None, s)
4591}
4592
4593pub fn BrotliDecompressStreamWithDictionary<AllocU8: alloc::Allocator<u8>,
4598 AllocU32: alloc::Allocator<u32>,
4599 AllocHC: alloc::Allocator<HuffmanCode>>
4600 (available_in: &mut usize,
4601 input_offset: &mut usize,
4602 xinput: &[u8],
4603 available_out: &mut usize,
4604 output_offset: &mut usize,
4605 output: &mut [u8],
4606 total_out: &mut usize,
4607 dictionary: &[u8],
4608 s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
4609 -> BrotliResult {
4610 BrotliDecompressStreamWithDictionaryAndMetadata(
4611 available_in, input_offset, xinput,
4612 available_out, output_offset, output,
4613 total_out, dictionary, None, s)
4614}
4615
4616
4617pub fn BrotliDecompressStreamWithDictionaryAndMetadata<AllocU8: alloc::Allocator<u8>,
4622 AllocU32: alloc::Allocator<u32>,
4623 AllocHC: alloc::Allocator<HuffmanCode>>
4624 (available_in: &mut usize,
4625 input_offset: &mut usize,
4626 xinput: &[u8],
4627 mut available_out: &mut usize,
4628 mut output_offset: &mut usize,
4629 mut output: &mut [u8],
4630 mut total_out: &mut usize,
4631 dictionary: &[u8],
4632 mut metadata_cb: Option<&mut dyn state::BrotliMetadataCallback>,
4633 mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
4634 -> BrotliResult {
4635
4636 let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
4637
4638 let mut saved_buffer: [u8; 8] = s.buffer;
4639 let mut local_input: &[u8];
4640 if is_fatal(s.error_code) {
4641 return BrotliResult::ResultFailure;
4642 }
4643 if !bit_reader::is_valid_input_range(*input_offset, *available_in, xinput.len()) {
4644 return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
4645 }
4646 if dictionary.len() != s.external_dictionary_len() {
4647 return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
4648 }
4649 match output_offset.checked_add(*available_out) {
4650 Some(end) if end <= output.len() => {}
4651 _ => return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS),
4652 }
4653 if s.buffer_length as usize > s.buffer.len() {
4654 return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE);
4655 }
4656 if s.buffer_length == 0 {
4657 local_input = xinput;
4658 s.br.avail_in = *available_in as u32;
4659 s.br.next_in = *input_offset as u32;
4660 bit_reader::BrotliBitReaderClearUnclaimed(&mut s.br);
4661 } else {
4662 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4663 let copy_len = core::cmp::min(saved_buffer.len() - s.buffer_length as usize, *available_in);
4664 if copy_len > 0 {
4665 fast_mut!((saved_buffer)[s.buffer_length as usize ; (s.buffer_length as usize + copy_len)])
4666 .clone_from_slice(fast!((xinput)[*input_offset ; copy_len + *input_offset]));
4667 fast_mut!((s.buffer)[s.buffer_length as usize ; (s.buffer_length as usize + copy_len)])
4668 .clone_from_slice(fast!((xinput)[*input_offset ; copy_len + *input_offset]));
4669 }
4670 local_input = &saved_buffer[..];
4671 s.br.next_in = 0;
4672 bit_reader::BrotliBitReaderClearUnclaimed(&mut s.br);
4673 }
4674 loop {
4675 match result {
4676 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4677 _ => {
4678 match result {
4679 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT => {
4680 if s.ringbuffer.slice().len() != 0 {
4681 let (intermediate_result, _) = WriteRingBuffer(available_out,
4682 Some(&mut output),
4683 &mut output_offset,
4684 &mut total_out,
4685 true,
4686 &mut s);
4687 if is_fatal(intermediate_result) {
4688 result = intermediate_result;
4689 break;
4690 }
4691 }
4692 if s.buffer_length != 0 {
4693 if s.br.avail_in == 0 {
4695 s.buffer_length = 0;
4699 result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
4701 local_input = xinput;
4702 s.br.avail_in = *available_in as u32;
4703 s.br.next_in = *input_offset as u32;
4704 bit_reader::BrotliBitReaderClearUnclaimed(&mut s.br);
4705 continue;
4706 } else if *available_in != 0 {
4707 result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
4710 let new_byte = fast!((xinput)[*input_offset]);
4711 let buffer_length = s.buffer_length as usize;
4712 if saved_buffer.get(buffer_length) != Some(&new_byte) {
4714 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
4715 break;
4716 }
4717 s.buffer[buffer_length] = new_byte;
4718 s.buffer_length += 1;
4719 s.br.avail_in = s.buffer_length;
4720 (*input_offset) += 1;
4721 (*available_in) -= 1;
4722 continue;
4725 }
4726 break;
4733 } else {
4734 *input_offset = s.br.next_in as usize;
4737 *available_in = s.br.avail_in as usize;
4738 let buffer_length = s.buffer_length as usize;
4739 let input_end = *input_offset as u64 + *available_in as u64;
4740 let buffer_end = buffer_length as u64 + *available_in as u64;
4741 if input_end > xinput.len() as u64 || buffer_end > s.buffer.len() as u64 {
4742 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
4743 break;
4744 }
4745 let (input_end, buffer_end) = (input_end as usize, buffer_end as usize);
4746 s.buffer[buffer_length..buffer_end]
4747 .clone_from_slice(&xinput[*input_offset..input_end]);
4748 s.buffer_length = buffer_end as u32;
4749 *input_offset = input_end;
4750 *available_in = 0;
4751 break;
4752 }
4753 }
4755 _ => {
4756 if s.buffer_length != 0 {
4758 s.buffer_length = 0;
4761 } else {
4762 bit_reader::BrotliBitReaderUnload(&mut s.br);
4766 *available_in = s.br.avail_in as usize;
4767 *input_offset = s.br.next_in as usize;
4768 }
4769 }
4770 }
4771 break;
4772 }
4773 }
4774 if !bit_reader::is_valid_bit_reader(&s.br, local_input) {
4775 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
4776 continue;
4777 }
4778 loop {
4779 match s.state {
4781 BrotliRunningState::BROTLI_STATE_UNINITED => {
4782 if (!bit_reader::BrotliWarmupBitReader(&mut s.br, local_input)) {
4784 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4785 break;
4786 }
4787 result = DecodeWindowBits(&mut s.large_window, &mut s.window_bits, &mut s.br);
4790 match result {
4791 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4792 _ => break,
4793 }
4794 if s.large_window {
4795 s.state = BrotliRunningState::BROTLI_STATE_LARGE_WINDOW_BITS;
4796 } else {
4797 s.state = BrotliRunningState::BROTLI_STATE_INITIALIZE;
4798 }
4799 }
4800 BrotliRunningState::BROTLI_STATE_LARGE_WINDOW_BITS => {
4801 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 6, &mut s.window_bits, local_input)) {
4802 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4803 break;
4804 }
4805 if (s.window_bits < kBrotliLargeMinWbits ||
4806 s.window_bits > kBrotliLargeMaxWbits) {
4807 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
4808 break;
4809 }
4810 s.state = BrotliRunningState::BROTLI_STATE_INITIALIZE;
4811 }
4812 BrotliRunningState::BROTLI_STATE_INITIALIZE => {
4813 s.max_backward_distance = (1 << s.window_bits) - kBrotliWindowGap as i32;
4814 if s.custom_dict.slice().len() != 0 {
4819 let dict = mem::replace(&mut s.custom_dict, AllocU8::AllocatedMemory::default());
4820 if !s.attach_compound_dictionary_chunk(state::MaybeOwnedSlice::Owned(dict)) {
4821 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY;
4822 break;
4823 }
4824 }
4825
4826 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
4830 }
4832 BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN => {
4833 s.BrotliStateMetablockBegin();
4834 BROTLI_LOG_UINT!(s.pos);
4835 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER;
4836 }
4838 BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER => {
4839 result = DecodeMetaBlockLength(&mut s, local_input); match result {
4841 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4842 _ => break,
4843 }
4844 debug_assert!(s.meta_block_remaining_len <= 1 << 24);
4845 BROTLI_LOG_UINT!(s.is_last_metablock);
4846 BROTLI_LOG_UINT!(s.meta_block_remaining_len);
4847 BROTLI_LOG_UINT!(s.is_metadata);
4848 BROTLI_LOG_UINT!(s.is_uncompressed);
4849 if (s.is_metadata != 0 || s.is_uncompressed != 0) &&
4850 !bit_reader::BrotliJumpToByteBoundary(&mut s.br) {
4851 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_1;
4852 break;
4853 }
4854 if s.is_metadata != 0 {
4855 s.state = BrotliRunningState::BROTLI_STATE_METADATA;
4856
4857 if let Some(ref mut callback) = metadata_cb {
4858 callback.start(s.meta_block_remaining_len as usize);
4859 }
4860 break;
4861 }
4862 if s.meta_block_remaining_len == 0 {
4863 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4864 break;
4865 }
4866 BrotliCalculateRingBufferSize(s, local_input);
4867 if s.is_uncompressed != 0 {
4868 s.state = BrotliRunningState::BROTLI_STATE_UNCOMPRESSED;
4869 break;
4870 }
4871 s.loop_counter = 0;
4872 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0;
4873 break;
4874 }
4875 BrotliRunningState::BROTLI_STATE_UNCOMPRESSED => {
4876 let mut _bytes_copied = s.meta_block_remaining_len;
4877 result = CopyUncompressedBlockToOutput(&mut available_out,
4878 &mut output,
4879 &mut output_offset,
4880 &mut total_out,
4881 &mut s,
4882 local_input);
4883 _bytes_copied -= s.meta_block_remaining_len;
4884 match result {
4885 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4886 _ => break,
4887 }
4888 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4889 break;
4890 }
4891 BrotliRunningState::BROTLI_STATE_METADATA => {
4892 result = read_metadata_block(
4893 &mut s.br,
4894 &mut s.meta_block_remaining_len,
4895 local_input,
4896 &mut metadata_cb);
4897 if let BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS = result {
4898 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE
4899 }
4900 break;
4901 }
4902 BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0 => {
4903 if s.loop_counter >= 3 {
4904 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER_2;
4905 break;
4906 }
4907 {
4909 let index = s.loop_counter as usize;
4910 result =
4911 DecodeVarLenUint8(&mut s.substate_decode_uint8,
4912 &mut s.br,
4913 &mut fast_mut!((s.block_type_length_state.num_block_types)[index]),
4914 local_input);
4915 }
4916 match result {
4917 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4918 _ => break,
4919 }
4920 fast_mut!((s.block_type_length_state.num_block_types)[s.loop_counter as usize]) += 1;
4921 BROTLI_LOG_UINT!(s.block_type_length_state.num_block_types[s.loop_counter as usize]);
4922 if fast!((s.block_type_length_state.num_block_types)[s.loop_counter as usize]) < 2 {
4923 s.loop_counter += 1;
4924 break;
4925 }
4926 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_1;
4927 }
4929 BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_1 => {
4930 if !EnsureBlockTrees(&mut s) {
4934 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES;
4935 break;
4936 }
4937 let tree_offset = s.loop_counter as u32 * huffman::BROTLI_HUFFMAN_MAX_SIZE_258 as u32;
4938 let mut new_huffman_table = mem::replace(&mut s.block_type_length_state.block_type_trees,
4939 AllocHC::AllocatedMemory::default());
4940 let loop_counter = s.loop_counter as usize;
4941 let alphabet_size = fast!((s.block_type_length_state.num_block_types)[loop_counter]) + 2;
4942 result =
4943 ReadHuffmanCode(alphabet_size, alphabet_size,
4944 new_huffman_table.slice_mut(),
4945 tree_offset as usize,
4946 None,
4947 &mut s,
4948 local_input);
4949 let _ = mem::replace(&mut s.block_type_length_state.block_type_trees,
4950 new_huffman_table);
4951 match result {
4952 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4953 _ => break,
4954 }
4955 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_2;
4956 }
4958 BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_2 => {
4959 let tree_offset = s.loop_counter * huffman::BROTLI_HUFFMAN_MAX_SIZE_26 as i32;
4960 let mut new_huffman_table = mem::replace(&mut s.block_type_length_state.block_len_trees,
4961 AllocHC::AllocatedMemory::default());
4962 result = ReadHuffmanCode(kNumBlockLengthCodes, kNumBlockLengthCodes,
4963 new_huffman_table.slice_mut(),
4964 tree_offset as usize,
4965 None,
4966 &mut s,
4967 local_input);
4968 let _ = mem::replace(&mut s.block_type_length_state.block_len_trees,
4969 new_huffman_table);
4970 match result {
4971 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4972 _ => break,
4973 }
4974 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_3;
4975 }
4977 BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_3 => {
4978 let tree_offset = s.loop_counter * huffman::BROTLI_HUFFMAN_MAX_SIZE_26 as i32;
4979
4980 let mut block_length_out: u32 = 0;
4981 let ind_ret: (bool, u32);
4982
4983 ind_ret = SafeReadBlockLengthIndex(&s.block_type_length_state.substate_read_block_length,
4984 s.block_type_length_state.block_length_index,
4985 fast_slice!((s.block_type_length_state.block_len_trees)
4986 [tree_offset as usize;]),
4987 &mut s.br, local_input);
4988
4989 if !SafeReadBlockLengthFromIndex(&mut s.block_type_length_state,
4990 &mut s.br,
4991 &mut block_length_out,
4992 ind_ret,
4993 local_input) {
4994 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4995 break;
4996 }
4997 fast_mut!((s.block_type_length_state.block_length)[s.loop_counter as usize]) =
4998 block_length_out;
4999 BROTLI_LOG_UINT!(s.block_type_length_state.block_length[s.loop_counter as usize]);
5000 s.loop_counter += 1;
5001 s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0;
5002 break;
5003 }
5004 BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER_2 => {
5005 let mut bits: u32 = 0;
5006 if (!bit_reader::BrotliSafeReadBits(&mut s.br, 6, &mut bits, local_input)) {
5007 result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
5008 break;
5009 }
5010 s.distance_postfix_bits = bits & bit_reader::BitMask(2);
5011 bits >>= 2;
5012 s.num_direct_distance_codes = NUM_DISTANCE_SHORT_CODES +
5013 (bits << s.distance_postfix_bits);
5014 BROTLI_LOG_UINT!(s.num_direct_distance_codes);
5015 BROTLI_LOG_UINT!(s.distance_postfix_bits);
5016 s.distance_postfix_mask = bit_reader::BitMask(s.distance_postfix_bits) as i32;
5017 let num_literal_block_types =
5018 fast!((s.block_type_length_state.num_block_types)[0]) as usize;
5019 if s.context_modes.slice().len() < num_literal_block_types {
5020 s.alloc_u8.free_cell(core::mem::take(&mut s.context_modes));
5021 s.context_modes = s.alloc_u8.alloc_cell(num_literal_block_types);
5022 if s.context_modes.slice().len() < num_literal_block_types {
5023 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES;
5024 break;
5025 }
5026 }
5027 s.loop_counter = 0;
5028 s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MODES;
5029 }
5031 BrotliRunningState::BROTLI_STATE_CONTEXT_MODES => {
5032 result = ReadContextModes(&mut s, local_input);
5033 match result {
5034 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5035 _ => break,
5036 }
5037 s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1;
5038 }
5040 BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1 => {
5041 result =
5042 DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[0]) as usize) <<
5043 kLiteralContextBits as usize,
5044 false,
5045 &mut s,
5046 local_input);
5047 match result {
5048 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5049 _ => break,
5050 }
5051 DetectTrivialLiteralBlockTypes(s);
5052 s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2;
5053 }
5055 BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2 => {
5056 let num_direct_codes =
5057 s.num_direct_distance_codes - NUM_DISTANCE_SHORT_CODES;
5058 let num_distance_codes = BROTLI_DISTANCE_ALPHABET_SIZE(
5059 s.distance_postfix_bits, num_direct_codes,
5060 (if s.large_window { BROTLI_LARGE_MAX_DISTANCE_BITS } else {
5061 BROTLI_MAX_DISTANCE_BITS}));
5062 let max_distance_symbol = if s.large_window {
5063 BrotliMaxDistanceSymbol(
5064 num_direct_codes, s.distance_postfix_bits)
5065 } else {
5066 num_distance_codes
5067 };
5068 result =
5069 DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[2]) as usize) <<
5070 kDistanceContextBits as usize,
5071 true,
5072 s,
5073 local_input);
5074 match result {
5075 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5076 _ => break,
5077 }
5078 let num_command_htrees =
5079 fast!((s.block_type_length_state.num_block_types)[1]) as u16;
5080 if (s.literal_hgroup.needs_codes_growth(
5085 kNumLiteralCodes, kNumLiteralCodes, s.num_literal_htrees as u16) ||
5086 s.insert_copy_hgroup.needs_codes_growth(
5087 kNumInsertAndCopyCodes, kNumInsertAndCopyCodes, num_command_htrees) ||
5088 s.distance_hgroup.needs_codes_growth(
5089 num_distance_codes as u16, max_distance_symbol as u16, s.num_dist_htrees as u16)) &&
5090 !EnsureBlockTrees(s) {
5091 return SaveErrorCode!(
5092 s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES);
5093 }
5094 s.literal_hgroup.init(&mut s.alloc_u32,
5095 &mut s.alloc_hc,
5096 kNumLiteralCodes,
5097 kNumLiteralCodes,
5098 s.num_literal_htrees as u16);
5099 s.insert_copy_hgroup.init(&mut s.alloc_u32,
5100 &mut s.alloc_hc,
5101 kNumInsertAndCopyCodes,
5102 kNumInsertAndCopyCodes,
5103 num_command_htrees);
5104 s.distance_hgroup.init(&mut s.alloc_u32,
5105 &mut s.alloc_hc,
5106 num_distance_codes as u16,
5107 max_distance_symbol as u16,
5108 s.num_dist_htrees as u16);
5109 if (s.literal_hgroup.htrees.slice().len() == 0 ||
5110 s.literal_hgroup.codes.slice().len() == 0 ||
5111 s.insert_copy_hgroup.htrees.slice().len() == 0 ||
5112 s.insert_copy_hgroup.codes.slice().len() == 0 ||
5113 s.distance_hgroup.htrees.slice().len() == 0 ||
5114 s.distance_hgroup.codes.slice().len() == 0) {
5115 return SaveErrorCode!(
5116 s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS);
5117 }
5118
5119 s.loop_counter = 0;
5151 s.state = BrotliRunningState::BROTLI_STATE_TREE_GROUP;
5152 }
5154 BrotliRunningState::BROTLI_STATE_TREE_GROUP => {
5155 result = HuffmanTreeGroupDecode(s.loop_counter, &mut s, local_input);
5156 match result {
5157 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5158 _ => break,
5159 }
5160 s.loop_counter += 1;
5161 if (s.loop_counter >= 3) {
5162 PrepareLiteralDecoding(s);
5163 s.dist_context_map_slice_index = 0;
5164 s.htree_command_index = 0;
5171 result = BrotliEnsureRingBuffer(
5174 s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2);
5175 match result {
5176 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5177 _ => break,
5178 }
5179 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
5180 }
5181 break;
5182 }
5183 BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN |
5184 BrotliRunningState::BROTLI_STATE_COMMAND_INNER |
5185 BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS |
5186 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY => {
5187 result = ProcessCommands(s, local_input, dictionary);
5188 if let BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT = result {
5189 result = SafeProcessCommands(s, local_input, dictionary)
5190 }
5191 break;
5192 }
5193 BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE |
5194 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1 |
5195 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2 => {
5196 let (xresult, _) = WriteRingBuffer(&mut available_out,
5197 Some(&mut output),
5198 &mut output_offset,
5199 &mut total_out,
5200 false,
5201 &mut s);
5202 result = xresult;
5203 match result {
5204 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5205 _ => break,
5206 }
5207 if !WrapRingBuffer(s) {
5208 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
5209 break;
5210 }
5211 if s.ringbuffer_size == 1 << s.window_bits {
5212 s.max_distance = s.max_backward_distance;
5213 }
5214 match s.state {
5215 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1 => {
5216 if s.compound_dictionary.br_length != s.compound_dictionary.br_copied {
5217 let pos = s.pos;
5219 let rb_size = s.ringbuffer_size;
5220 let copied = CopyFromCompoundDictionary(
5221 &mut s.compound_dictionary,
5222 s.ringbuffer.slice_mut(),
5223 rb_size,
5224 pos,
5225 dictionary,
5226 );
5227 s.pos += copied;
5228 if s.pos >= s.ringbuffer_size {
5229 continue;
5231 }
5232 }
5233 if (s.meta_block_remaining_len <= 0) {
5234 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
5236 } else {
5237 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
5238 }
5239 break;
5240 }
5241 BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2 => {
5242 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
5243 }
5244 _ => {
5245 if (s.loop_counter == 0) {
5247 if (s.meta_block_remaining_len <= 0) {
5248 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
5249 } else {
5250 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
5251 }
5252 break;
5253 }
5254 s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
5255 }
5256 }
5257 break;
5258 }
5259 BrotliRunningState::BROTLI_STATE_METABLOCK_DONE => {
5260 if (s.meta_block_remaining_len < 0) {
5271 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2;
5272 break;
5273 }
5274 if (s.is_last_metablock == 0) {
5275 s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
5279 break;
5280 }
5281 s.BrotliStateCleanupAfterMetablock();
5282 if (!bit_reader::BrotliJumpToByteBoundary(&mut s.br)) {
5283 result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_2;
5289 break;
5290 }
5291 if (s.buffer_length == 0) {
5292 bit_reader::BrotliBitReaderUnload(&mut s.br);
5293 *available_in = s.br.avail_in as usize;
5294 *input_offset = s.br.next_in as usize;
5295 }
5296 s.state = BrotliRunningState::BROTLI_STATE_DONE;
5297 }
5299 BrotliRunningState::BROTLI_STATE_DONE => {
5300 if (s.ringbuffer.slice().len() != 0) {
5301 let (xresult, _) = WriteRingBuffer(&mut available_out,
5302 Some(&mut output),
5303 &mut output_offset,
5304 &mut total_out,
5305 true,
5306 &mut s);
5307 result = xresult;
5308 match result {
5309 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5310 _ => break,
5311 }
5312 }
5313 return SaveErrorCode!(s, result);
5314 }
5315 }
5316 }
5317 }
5318
5319 SaveErrorCode!(s, result)
5320}
5321
5322fn read_metadata_block(
5323 br: &mut bit_reader::BrotliBitReader,
5324 meta_block_remaining_len: &mut i32,
5325 local_input: &[u8],
5326 metadata_cb: &mut Option<&mut dyn state::BrotliMetadataCallback>,
5327) -> BrotliDecoderErrorCode {
5328 if *meta_block_remaining_len <= 0 {
5329 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
5330 }
5331
5332 let bit_reader_bits_avail = bit_reader::BrotliGetAvailableBits(br);
5333 debug_assert_eq!(bit_reader_bits_avail & 7, 0);
5334 let amt_in_bit_reader = core::cmp::min(
5335 (bit_reader_bits_avail / 8) as usize,
5336 *meta_block_remaining_len as usize);
5337
5338 if amt_in_bit_reader > 0 {
5339 let mut scratch = [0u8; core::mem::size_of::<bit_reader::BrotliBitReader>()];
5340 bit_reader::BrotliCopyBytes(&mut scratch[..], br, amt_in_bit_reader as u32, local_input);
5341 *meta_block_remaining_len -= amt_in_bit_reader as i32;
5342 if let Some(callback) = metadata_cb {
5343 callback.chunk(&scratch[..amt_in_bit_reader]);
5344 }
5345 }
5346 let remaining_bytes = core::cmp::min(*meta_block_remaining_len as usize,
5347 br.avail_in as usize);
5348 if remaining_bytes != 0 {
5349 if let Some(callback) = metadata_cb {
5350 let all_remaining_input = local_input.split_at(br.next_in as usize).1;
5351 callback.chunk(&all_remaining_input.split_at(remaining_bytes).0);
5352 }
5353 br.next_in += remaining_bytes as u32;
5354 bit_reader::BrotliBitReaderClearUnclaimed(br);
5355 br.avail_in -= remaining_bytes as u32;
5356 *meta_block_remaining_len -= remaining_bytes as i32;
5357 }
5358 if *meta_block_remaining_len == 0 {
5359 return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
5360 }
5361 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT
5362}
5363
5364#[cfg(test)]
5365mod safeguard_tests {
5366 use super::{copy_overlapping_backreference, memcpy_within_slice, memmove16_from_ringbuffer,
5367 memmove16_offset16};
5368
5369 #[test]
5373 fn context_lookup_values_fit_the_context_map() {
5374 for table in super::kContextLookup.iter() {
5375 for value in table.iter() {
5376 assert!(*value < 64);
5377 }
5378 }
5379 }
5380
5381 #[test]
5382 fn overlapping_backreferences_match_sequential_copy() {
5383 for distance in 1..65 {
5384 for size in 0..257 {
5385 let mut data = [0u8; 384];
5386 for (index, byte) in data.iter_mut().enumerate() {
5387 *byte = (index.wrapping_mul(73) ^ (index >> 3)) as u8;
5388 }
5389 let mut expected = data;
5390 for index in 64..64 + size {
5391 expected[index] = expected[index - distance];
5392 }
5393 assert!(copy_overlapping_backreference(&mut data, 64, distance, size));
5394 assert_eq!(&data[..], &expected[..]);
5395 }
5396 }
5397 }
5398
5399 #[test]
5400 fn overlapping_backreferences_reject_invalid_ranges() {
5401 let original = [37u8; 32];
5402 for &(dst, distance, size) in &[
5403 (8, 0, 4), (8, 9, 4), (33, 1, 0), (31, 1, 2),
5404 (usize::MAX, 1, 0), (8, usize::MAX, 1), (8, 1, usize::MAX)] {
5405 let mut data = original;
5406 assert!(!copy_overlapping_backreference(&mut data, dst, distance, size));
5407 assert_eq!(data, original);
5408 }
5409 }
5410
5411 #[test]
5412 fn memmove16_helpers_reject_out_of_bounds_ranges() {
5413 let mut short = [0u8; 31];
5415 assert!(!memmove16_from_ringbuffer(&mut short, 0, 0));
5416 assert!(!memmove16_offset16(&mut short, 0, 0));
5417 let mut data = [7u8; 64];
5418 for &(dst, src) in &[(33u32, 0u32), (0, 33), (u32::MAX, 0), (0, u32::MAX)] {
5419 assert!(!memmove16_from_ringbuffer(&mut data, dst, src));
5420 assert!(!memmove16_offset16(&mut data, dst, src));
5421 }
5422 assert_eq!(data, [7u8; 64]);
5423 assert!(memmove16_from_ringbuffer(&mut data, 32, 0));
5425 assert!(memmove16_offset16(&mut data, 0, 32));
5426 }
5427
5428 #[test]
5429 fn memmove16_helpers_copy_with_memmove_semantics() {
5430 let mut pattern = [0u8; 80];
5431 for (i, b) in pattern.iter_mut().enumerate() {
5432 *b = i as u8;
5433 }
5434 for &(dst, src) in &[(40u32, 0u32), (0, 40), (20, 16), (16, 20), (17, 16), (5, 5)] {
5437 let mut data = pattern;
5438 let mut expected = pattern;
5439 expected.copy_within(src as usize..src as usize + 16, dst as usize);
5440 assert!(memmove16_from_ringbuffer(&mut data, dst, src));
5441 assert_eq!(&data[..], &expected[..], "memmove16_from_ringbuffer({}, {})", dst, src);
5442
5443 let mut data = pattern;
5444 let mut expected = pattern;
5445 expected.copy_within(src as usize + 16..src as usize + 32, dst as usize + 16);
5446 assert!(memmove16_offset16(&mut data, dst, src));
5447 assert_eq!(&data[..], &expected[..], "memmove16_offset16({}, {})", dst, src);
5448 }
5449 }
5450
5451 #[test]
5452 fn memcpy_within_slice_validates_nonoverlapping_ranges() {
5453 let mut data = [0u8, 1, 2, 3, 4, 5, 6, 7];
5454 assert!(memcpy_within_slice(&mut data, 4, 0, 2));
5455 assert_eq!(data, [0, 1, 2, 3, 0, 1, 6, 7]);
5456
5457 let unchanged = data;
5458 assert!(!memcpy_within_slice(&mut data, 1, 0, 4));
5459 assert!(!memcpy_within_slice(&mut data, 7, 0, 2));
5460 assert!(!memcpy_within_slice(&mut data, usize::MAX, 0, 2));
5461 assert!(!memcpy_within_slice(&mut data, 0, usize::MAX, 2));
5462 assert_eq!(data, unchanged);
5463 }
5464}
5465
5466#[cfg(all(test, feature="std"))]
5469mod state_guard_tests {
5470 use super::{CheckRingBufferConsistency, DecodeContextMap, ReadHuffmanCode, UnwrittenBytes,
5471 WrapRingBuffer, WriteRingBuffer};
5472 use super::{decode_block_type_and_length_slice, DecodeBlockTypeAndLength};
5473 use bit_reader::BitReaderSlice;
5474 use super::{BrotliDecoderErrorCode, BrotliRunningState, BrotliState, HuffmanCode};
5475 use ::state::BrotliRunningHuffmanState;
5476 use ::alloc::Allocator;
5477 use ::StandardAlloc;
5478
5479 type TestState = BrotliState<StandardAlloc, StandardAlloc, StandardAlloc>;
5480
5481 fn state() -> TestState {
5482 BrotliState::new(StandardAlloc::default(), StandardAlloc::default(), StandardAlloc::default())
5483 }
5484
5485 fn state_with_ringbuffer(size: i32, window_bits: u32) -> TestState {
5488 let mut s = state();
5489 s.ringbuffer = s.alloc_u8.alloc_cell(size as usize);
5490 s.ringbuffer_size = size;
5491 s.ringbuffer_mask = size - 1;
5492 s.new_ringbuffer_size = size;
5493 s.window_bits = window_bits;
5494 s
5495 }
5496
5497 #[test]
5503 fn ring_buffer_consistency_rejects_inconsistent_state() {
5504 let mut s = state_with_ringbuffer(16, 4);
5505 assert!(CheckRingBufferConsistency(&s));
5506
5507 s.pos = -1;
5508 assert!(!CheckRingBufferConsistency(&s));
5509 s.pos = 0;
5510
5511 s.ringbuffer_size = 0;
5512 assert!(!CheckRingBufferConsistency(&s));
5513 s.ringbuffer_size = 16;
5514
5515 s.ringbuffer_mask = -1;
5516 assert!(!CheckRingBufferConsistency(&s));
5517
5518 s.ringbuffer_mask = 7;
5520 assert!(!CheckRingBufferConsistency(&s));
5521 s.ringbuffer_mask = 15;
5522
5523 s.ringbuffer_size = 32;
5525 s.ringbuffer_mask = 31;
5526 assert!(!CheckRingBufferConsistency(&s));
5527 }
5528
5529 #[test]
5530 fn unwritten_bytes_is_exact_past_a_32_bit_wrap() {
5531 let mut s = state_with_ringbuffer(1 << 16, 16);
5534 s.rb_roundtrips = 1 << 17; s.pos = 100;
5536 s.partial_pos_out = (1u64 << 33) + 40;
5537 assert_eq!(UnwrittenBytes(&s, false), 60);
5538 }
5539
5540 #[test]
5541 fn write_ring_buffer_rejects_inconsistent_ring_buffer() {
5542 let mut s = state_with_ringbuffer(16, 4);
5543 s.ringbuffer_mask = 7; let mut available_out = 8usize;
5545 let mut output = [0u8; 8];
5546 let mut output_offset = 0usize;
5547 let mut total_out = 0usize;
5548 let (code, out) = WriteRingBuffer(&mut available_out, Some(&mut output[..]),
5549 &mut output_offset, &mut total_out, false, &mut s);
5550 match code {
5551 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5552 other => panic!("expected UNREACHABLE, got {:?}", other),
5553 }
5554 assert!(out.is_empty());
5555 }
5556
5557 #[test]
5558 fn write_ring_buffer_rejects_negative_block_length() {
5559 let mut s = state_with_ringbuffer(16, 4);
5560 s.meta_block_remaining_len = -1;
5561 let mut available_out = 0usize;
5562 let mut output_offset = 0usize;
5563 let mut total_out = 0usize;
5564 let (code, _) = WriteRingBuffer(&mut available_out, None, &mut output_offset,
5565 &mut total_out, false, &mut s);
5566 match code {
5567 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1 => {}
5568 other => panic!("expected BLOCK_LENGTH_1, got {:?}", other),
5569 }
5570 }
5571
5572 #[test]
5573 fn write_ring_buffer_rejects_output_slice_that_cannot_hold_the_write() {
5574 let mut s = state_with_ringbuffer(16, 4);
5575 s.pos = 8; let mut available_out = 8usize;
5577 let mut output = [0u8; 8];
5578 let mut output_offset = 4usize;
5581 let mut total_out = 0usize;
5582 let (code, _) = WriteRingBuffer(&mut available_out, Some(&mut output[..]),
5583 &mut output_offset, &mut total_out, false, &mut s);
5584 match code {
5585 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS => {}
5586 other => panic!("expected INVALID_ARGUMENTS, got {:?}", other),
5587 }
5588 }
5589
5590 #[test]
5591 fn wrap_ring_buffer_rejects_state_it_cannot_split() {
5592 let mut s = state_with_ringbuffer(16, 4);
5593 s.should_wrap_ringbuffer = true;
5594
5595 s.pos = -1;
5596 assert!(!WrapRingBuffer(&mut s));
5597
5598 s.pos = 0;
5599 s.ringbuffer_size = -1;
5600 assert!(!WrapRingBuffer(&mut s));
5601
5602 s.ringbuffer_size = 64;
5604 s.pos = 1;
5605 assert!(!WrapRingBuffer(&mut s));
5606
5607 s.ringbuffer_size = 16;
5609 s.pos = 8;
5610 assert!(!WrapRingBuffer(&mut s));
5611
5612 let mut ok = state_with_ringbuffer(16, 4);
5614 ok.ringbuffer_size = 8;
5615 ok.ringbuffer_mask = 7;
5616 ok.pos = 4;
5617 ok.should_wrap_ringbuffer = true;
5618 assert!(WrapRingBuffer(&mut ok));
5619 assert!(!ok.should_wrap_ringbuffer);
5620 }
5621
5622 #[test]
5623 fn read_huffman_code_rejects_offset_past_table() {
5624 let mut s = state();
5625 let mut table = [HuffmanCode::default(); 4];
5626 let code = ReadHuffmanCode(256, 256, &mut table, 5, None, &mut s, &[]);
5627 match code {
5628 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => {}
5629 other => panic!("expected HUFFMAN_SPACE, got {:?}", other),
5630 }
5631 }
5632
5633 #[test]
5634 fn read_huffman_code_reports_a_simple_table_that_will_not_fit() {
5635 let mut s = state();
5638 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
5639 s.symbol = 0;
5640 let mut table = [HuffmanCode::default(); 8];
5641 match ReadHuffmanCode(256, 256, &mut table, 0, None, &mut s, &[]) {
5642 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => {}
5643 other => panic!("expected HUFFMAN_SPACE, got {:?}", other),
5644 }
5645 }
5646
5647 #[test]
5648 fn read_huffman_code_reports_a_complex_table_that_will_not_fit() {
5649 let mut s = state();
5650 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
5651 s.symbol = 256;
5653 s.space = 0;
5654 s.code_length_histo[1] = 2;
5655 let mut table = [HuffmanCode::default(); 8];
5656 match ReadHuffmanCode(256, 256, &mut table, 0, None, &mut s, &[]) {
5657 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => {}
5658 other => panic!("expected HUFFMAN_SPACE, got {:?}", other),
5659 }
5660 }
5661
5662 #[test]
5663 fn read_huffman_code_reports_a_code_length_histogram_mismatch() {
5664 let mut s = state();
5669 s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_COMPLEX;
5670 s.sub_loop_counter = super::CODE_LENGTH_CODES as u32;
5674 s.repeat = 1;
5675 s.space = 32;
5676 s.code_length_histo[2] = 9;
5678 let mut table = [HuffmanCode::default(); 1080];
5679 match ReadHuffmanCode(256, 256, &mut table, 0, None, &mut s, &[]) {
5680 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => {}
5681 other => panic!("expected HUFFMAN_SPACE, got {:?}", other),
5682 }
5683 }
5684
5685 #[test]
5686 fn write_ring_buffer_rejects_a_pending_run_longer_than_the_ring() {
5687 let mut s = state_with_ringbuffer(16, 4);
5690 s.rb_roundtrips = 1;
5691 s.pos = 16;
5692 s.partial_pos_out = 4;
5693 let mut available_out = 64usize;
5694 let mut output = [0u8; 64];
5695 let mut output_offset = 0usize;
5696 let mut total_out = 0usize;
5697 let (code, _) = WriteRingBuffer(&mut available_out, Some(&mut output[..]),
5698 &mut output_offset, &mut total_out, false, &mut s);
5699 match code {
5700 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5701 other => panic!("expected UNREACHABLE, got {:?}", other),
5702 }
5703 }
5704
5705 #[test]
5706 fn write_ring_buffer_rejects_output_offset_that_would_overflow() {
5707 let mut s = state_with_ringbuffer(16, 4);
5708 s.pos = 8;
5709 let mut available_out = 8usize;
5710 let mut output_offset = usize::MAX - 1;
5711 let mut total_out = 0usize;
5712 let (code, _) = WriteRingBuffer(&mut available_out, None, &mut output_offset,
5713 &mut total_out, false, &mut s);
5714 match code {
5715 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS => {}
5716 other => panic!("expected INVALID_ARGUMENTS, got {:?}", other),
5717 }
5718 }
5719
5720 #[test]
5721 fn decode_context_map_rejects_mismatched_state() {
5722 let mut s = state();
5723 s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1;
5725 match DecodeContextMap(4, true, &mut s, &[]) {
5726 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5727 other => panic!("expected UNREACHABLE, got {:?}", other),
5728 }
5729 s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2;
5730 match DecodeContextMap(4, false, &mut s, &[]) {
5731 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5732 other => panic!("expected UNREACHABLE, got {:?}", other),
5733 }
5734 s.state = BrotliRunningState::BROTLI_STATE_UNINITED;
5735 match DecodeContextMap(4, false, &mut s, &[]) {
5736 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5737 other => panic!("expected UNREACHABLE, got {:?}", other),
5738 }
5739 }
5740
5741 #[test]
5745 fn block_switch_with_one_block_type_is_a_format_error() {
5746 let mut s = state();
5747 s.block_type_length_state.num_block_types = [1, 1, 1];
5748 s.block_type_length_state.block_length = [0, 0, 0];
5749 for &safe in [false, true].iter() {
5750 for category in 0..3 {
5751 let result = DecodeBlockTypeAndLength(
5752 safe,
5753 &mut s.block_type_length_state,
5754 &mut s.br,
5755 category,
5756 &[],
5757 );
5758 match result {
5759 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH => {}
5760 other => panic!("category {} safe {}: expected FORMAT_BLOCK_SWITCH, got {:?}",
5761 category, safe, other),
5762 }
5763 }
5764 }
5765 for category in 0..3 {
5766 let fbr = BitReaderSlice::new(&s.br, &[]).unwrap();
5767 let (fbr, status) =
5768 decode_block_type_and_length_slice(&mut s.block_type_length_state, fbr, category);
5769 fbr.sync_to(&mut s.br);
5770 match status {
5771 BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH => {}
5772 other => panic!("category {} slice: expected FORMAT_BLOCK_SWITCH, got {:?}",
5773 category, other),
5774 }
5775 }
5776 assert_eq!(s.br.avail_in, 0);
5777 assert_eq!(s.buffer_length, 0);
5778 }
5779}
5780
5781#[cfg(all(test, feature="std"))]
5784mod metadata_block_tests {
5785 use super::{read_metadata_block, BrotliDecoderErrorCode};
5786 use ::bit_reader::{self, BrotliBitReader};
5787 use ::state::BrotliMetadataCallback;
5788 use std::vec::Vec;
5789
5790 #[derive(Default)]
5791 struct Chunks(Vec<Vec<u8>>);
5792
5793 impl BrotliMetadataCallback for Chunks {
5794 fn start(&mut self, _size: usize) {
5795 panic!("read_metadata_block must not start a block");
5796 }
5797 fn chunk(&mut self, data: &[u8]) {
5798 assert!(!data.is_empty());
5799 self.0.push(data.to_vec());
5800 }
5801 }
5802
5803 const ACCUMULATOR_BYTES: u32 = ::core::mem::size_of::<bit_reader::reg_t>() as u32;
5806
5807 fn input() -> Vec<u8> {
5808 (0..64u32).map(|i| (i * 37 + 11) as u8).collect()
5809 }
5810
5811 fn reader(input: &[u8], buffered: u32) -> BrotliBitReader {
5814 let mut br = BrotliBitReader::default();
5815 bit_reader::BrotliInitBitReader(&mut br);
5816 br.avail_in = input.len() as u32;
5817 for _ in 0..buffered {
5818 assert!(bit_reader::BrotliPullByte(&mut br, input));
5819 }
5820 br
5821 }
5822
5823 fn copy(br: &BrotliBitReader) -> BrotliBitReader {
5824 let mut copy = BrotliBitReader::default();
5825 bit_reader::BrotliBitReaderRestoreState(&mut copy, &bit_reader::BrotliBitReaderSaveState(br));
5826 copy
5827 }
5828
5829 fn fields(br: &BrotliBitReader) -> (u64, u32, u32, u32) {
5830 (br.val_ as u64, br.bit_pos_, br.next_in, br.avail_in)
5831 }
5832
5833 fn run(br: &mut BrotliBitReader, remaining: &mut i32, input: &[u8], with_callback: bool)
5834 -> (bool, Vec<Vec<u8>>) {
5835 let mut chunks = Chunks::default();
5836 let result = {
5837 let mut cb: Option<&mut dyn BrotliMetadataCallback> =
5838 if with_callback { Some(&mut chunks) } else { None };
5839 read_metadata_block(br, remaining, input, &mut cb)
5840 };
5841 let done = match result {
5842 BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => true,
5843 BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT => false,
5844 other => panic!("unexpected {:?}", other),
5845 };
5846 (done, chunks.0)
5847 }
5848
5849 #[test]
5850 fn zero_length_block_touches_nothing() {
5851 let input = input();
5852 for buffered in 0..ACCUMULATOR_BYTES + 1 {
5853 let mut br = reader(&input, buffered);
5854 let before = fields(&br);
5855 let mut remaining = 0;
5856 let (done, chunks) = run(&mut br, &mut remaining, &input, true);
5857 assert!(done);
5858 assert!(chunks.is_empty());
5859 assert_eq!(fields(&br), before);
5860 }
5861 }
5862
5863 #[test]
5864 fn block_inside_the_accumulator_leaves_the_rest_buffered() {
5865 let input = input();
5866 for buffered in 1..ACCUMULATOR_BYTES + 1 {
5867 for len in 1..buffered + 1 {
5868 let mut br = reader(&input, buffered);
5869 let mut remaining = len as i32;
5870 let (done, chunks) = run(&mut br, &mut remaining, &input, true);
5871 assert!(done);
5872 assert_eq!(remaining, 0);
5873 assert_eq!(chunks, vec![input[..len as usize].to_vec()]);
5874 assert_eq!((br.next_in, br.avail_in), (buffered, input.len() as u32 - buffered));
5877 assert_eq!(bit_reader::BrotliGetAvailableBits(&br), (buffered - len) * 8);
5878 for expected in &input[len as usize..buffered as usize + 4] {
5879 let mut byte = 0u32;
5880 assert!(bit_reader::BrotliSafeReadBits(&mut br, 8, &mut byte, &input));
5881 assert_eq!(byte, *expected as u32);
5882 }
5883 }
5884 }
5885 }
5886
5887 #[test]
5888 fn longer_block_drains_the_accumulator_then_reads_input_directly() {
5889 let input = input();
5890 for buffered in 0..ACCUMULATOR_BYTES + 1 {
5891 for len in buffered + 1..48 {
5892 let mut br = reader(&input, buffered);
5893 let mut remaining = len as i32;
5894 let (done, chunks) = run(&mut br, &mut remaining, &input, true);
5895 assert!(done);
5896 assert_eq!(remaining, 0);
5897 let mut expected = Vec::new();
5898 if buffered != 0 {
5899 expected.push(input[..buffered as usize].to_vec());
5900 }
5901 expected.push(input[buffered as usize..len as usize].to_vec());
5902 assert_eq!(chunks, expected);
5903 assert_eq!((br.next_in, br.avail_in), (len, input.len() as u32 - len));
5904 assert_eq!(bit_reader::BrotliGetAvailableBits(&br), 0);
5905
5906 let mut safe = copy(&br);
5911 let mut byte = 0u32;
5912 assert!(bit_reader::BrotliSafeReadBits(&mut safe, 8, &mut byte, &input));
5913 assert_eq!(byte, input[len as usize] as u32);
5914
5915 let mut fast = copy(&br);
5916 assert!(bit_reader::BrotliWarmupBitReader(&mut fast, &input));
5917 for expected in &input[len as usize..len as usize + 8] {
5918 bit_reader::BrotliFillBitWindow(&mut fast, 8, &input);
5919 assert_eq!(bit_reader::BrotliReadBits(&mut fast, 8, &input), *expected as u32);
5920 }
5921 }
5922 }
5923 }
5924
5925 #[test]
5926 fn block_longer_than_the_input_resumes_on_the_next_call() {
5927 let input = input();
5928 for buffered in 0..ACCUMULATOR_BYTES + 1 {
5929 for available in buffered..buffered + 6 {
5930 let len = available + 5;
5931 let first = &input[..available as usize];
5932 let mut br = reader(first, buffered);
5933 let mut remaining = len as i32;
5934 let (done, mut chunks) = run(&mut br, &mut remaining, first, true);
5935 assert!(!done);
5936 assert_eq!(remaining, 5);
5937 assert_eq!(br.avail_in, 0);
5938 assert_eq!(bit_reader::BrotliGetAvailableBits(&br), 0);
5939 assert!(chunks.iter().all(|c| !c.is_empty()));
5940
5941 br.avail_in = (input.len() - available as usize) as u32;
5944 let (done, more) = run(&mut br, &mut remaining, &input, true);
5945 assert!(done);
5946 assert_eq!(more, vec![input[available as usize..len as usize].to_vec()]);
5947 chunks.extend(more);
5948 assert_eq!(chunks.concat(), &input[..len as usize]);
5949 assert_eq!(br.next_in, len);
5950 }
5951 }
5952 }
5953
5954 #[test]
5955 fn no_callback_has_the_same_effect_on_the_reader() {
5956 let input = input();
5957 for buffered in 0..ACCUMULATOR_BYTES + 1 {
5958 for len in 0..20i32 {
5959 for &available in [input.len() as u32, buffered + 2].iter() {
5960 let limited = &input[..available as usize];
5961 let mut with = reader(limited, buffered);
5962 let mut without = copy(&with);
5963 let (mut with_remaining, mut without_remaining) = (len, len);
5964 let (with_done, _) = run(&mut with, &mut with_remaining, limited, true);
5965 let (without_done, chunks) = run(&mut without, &mut without_remaining, limited, false);
5966 assert!(chunks.is_empty());
5967 assert_eq!(with_done, without_done);
5968 assert_eq!(with_remaining, without_remaining);
5969 assert_eq!(fields(&with), fields(&without));
5970 }
5971 }
5972 }
5973 }
5974
5975 #[cfg(debug_assertions)]
5976 #[test]
5977 #[should_panic(expected = "assertion")]
5978 fn unaligned_accumulator_is_a_precondition_violation() {
5979 let input = input();
5980 let mut br = reader(&input, 2);
5981 let mut bits = 0u32;
5982 assert!(bit_reader::BrotliSafeReadBits(&mut br, 3, &mut bits, &input));
5983 let mut remaining = 4;
5984 run(&mut br, &mut remaining, &input, true);
5985 }
5986}