Skip to main content

brotli_decompressor/
decode.rs

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
8// #[macro_use] //<- for debugging, remove xprintln from bit_reader and replace with println
9// extern crate std;
10use 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
63// Static prefix code for the complex code length code lengths.
64const 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
144// pub struct BrotliState {
145// total_written : usize,
146// }
147//
148pub use state::BrotliState;
149// impl BrotliState {
150// pub fn new() -> BrotliState {
151// return BrotliState {total_written: 0 };
152// }
153// }
154
155/* Decodes WBITS by reading 1 - 7 bits, or 0x11 for "Large Window Brotli".
156   Precondition: bit-reader accumulator has at least 8 bits. */
157fn 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        // No break, transit to the next state.
217      }
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        // Use output value as a temporary storage. It MUST be persisted.
230        *value = bits;
231        // No break, transit to the next state.
232        *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        // No break, transit to the next state.
273      }
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        // No break, transit to the next state.
286      }
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        // No break, transit to the next state.
302
303      }
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        // No break, transit to the next state.
320      }
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        // No break, transit to the next state.
343      }
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        // No break, transit to the next state.
357      }
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// Decodes the Huffman code.
379// This method doesn't read data from the bit reader, BUT drops the amount of
380// bits that correspond to the decoded symbol.
381// bits MUST contain at least 15 (BROTLI_HUFFMAN_MAX_CODE_LENGTH) valid bits.
382#[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// Reads and decodes the next Huffman code from bit-stream.
401// This method peeks 16 bits of input and drops 0 - 15 of them.
402#[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// Same as DecodeSymbol, but it is known that there is less than 15 bits of
408// input are currently available.
409#[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; /* No valid bits at all. */
422  }
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; /* Not enough bits for the first level. */
433    }
434  }
435  if (available_bits <= HUFFMAN_TABLE_BITS) {
436    return false; /* Not enough bits to move to the second level. */
437  }
438
439  // Speculatively drop HUFFMAN_TABLE_BITS.
440  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; /* Not enough bits for the second level. */
446  }
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
469// The literal trees of the 64 contexts before any are looked up.
470static 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    // A 2nd-level subtable entry has at most `15 - 8 = 7` bits; masking with
488    // `& 7` proves `consumed <= 15 < 32` across both arms so LLVM elides the
489    // `consumed & SLICE_SHIFT_MASK` instruction in `decode_symbol_no_fill`.
490    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
525// Reads (s->symbol + 1) symbols.
526// Totally 1..4 symbols are read, 1..11 bits each.
527// The list of symbols MUST NOT contain duplicates.
528//
529fn 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  // max_bits == 1..11; symbol == 0..3; 1..44 bits will be read.
538  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
571// `BrotliState::symbol_lists_index` is initialized once to
572// `BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1` (16, the number of negative-indexed
573// list-head slots at the front of `symbols_lists_array`) and never mutated.
574// Using the compile-time constant avoids reloading `s.symbol_lists_index` and
575// keeps one fewer live register in `ReadSymbolCodeLengths`.
576const SYMBOL_LISTS_OFFSET: usize = huffman::BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1;
577
578// Process single decoded symbol code length:
579// A) reset the repeat variable
580// B) remember code length (if it is not 0)
581// C) extend corredponding index-chain
582// D) reduce the huffman space
583// E) update the histogram
584//
585#[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    // code_len == 1..15
598    // next_symbol may be negative, hence we offset by `SYMBOL_LISTS_OFFSET`
599    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// Process repeated symbol code length.
616// A) Check if it is the extension of previous repeat sequence; if the decoded
617// value is not kCodeLengthRepeatCode, then it is a new symbol-skip
618// B) Update repeat variable
619// C) Check if operation is feasible (fits alphapet)
620// D) For each symbol do the same operations as in ProcessSingleCodeLength
621//
622// PRECONDITION: code_len == kCodeLengthRepeatCode or kCodeLengthRepeatCode + 1
623//
624#[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
689// Reads and decodes symbol codelengths.
690fn 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); /* Use 1..5 bits */
728    let code_len: u32 = p.value as u32; /* code_len == 0..17 */
729    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      // code_len == 16..17, extra_bits == 2..3
740      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      // pullMoreInput;
787      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; /* code_len == 0..17 */
793    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      // code_len == 16..17, extra_bits == 2..3
805      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        // pullMoreInput;
809        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
831// Reads and decodes 15..18 codes using static prefix code.
832// Each code is 2..4 bits long. In total 30..72 bits are used.
833fn 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        // space is 0 or wrapped around
876        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
888// Decodes the Huffman tables.
889// There are 2 scenarios:
890// A) Huffman code contains only few symbols (1..4). Those symbols are read
891// directly; their code lengths are defined by the number of symbols.
892// For this scenario 4 - 49 bits will be read.
893//
894// B) 2-phase decoding:
895// B.1) Small Huffman table is decoded; it is specified with code lengths
896// encoded with predefined entropy code. 32 - 74 bits are used.
897// B.2) Decoded table is used to decode code lengths of symbols in resulting
898// Huffman table. In worst case 3520 bits are read.
899//
900fn 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  // Unnecessary masking, but might be good for safety.
915  alphabet_size &= 0x7ff;
916  // State machine
917  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        // The value is used as follows:
926        // 1 for simple code;
927        // 0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths
928        if (s.sub_loop_counter != 1) {
929          s.space = 32;
930          s.repeat = 0; /* num_codes */
931          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; // memset
934          }
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          // goto Complex;
940          continue;
941        }
942        s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
943        // No break, transit to the next state.
944      }
945      BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_SIZE => {
946        // Read symbols, codes & code lengths directly.
947        if (!bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut s.symbol, input)) {
948          // num_symbols
949          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        // No break, transit to the next state.
954        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        // No break, transit to the next state.
963        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      // Decode Huffman-coded code lengths.
991      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        // No break, transit to the next state.
1025        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        // Pass `s.symbol_lists_index` rather than `SYMBOL_LISTS_OFFSET` here so
1043        // LLVM does not constant-propagate 16 into `BrotliBuildHuffmanTable` and
1044        // unroll its `max_length` scan loop (which grows its stack frame on ARMv7).
1045        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// Decodes a block length by reading 3..39 bits.
1064#[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; /*nbits==2..24*/
1072  p.offset as u32 + bit_reader::BrotliReadBits(br, nbits, input)
1073}
1074
1075
1076// WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then
1077// reading can't be continued with ReadBlockLength.
1078fn 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; /* nbits==2..24 */
1108  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
1129// Transform:
1130// 1) initialize list L with values 0, 1,... 255
1131// 2) For each input element X:
1132// 2.1) let Y = L[X]
1133// 2.2) remove X-th element from L
1134// 2.3) prepend Y to L
1135// 2.4) append Y to output
1136//
1137// In most cases max(Y) <= 7, so most of L remains intact.
1138// To reduce the cost of initialization, we reuse L, remember the upper bound
1139// of Y values, and reinitialize only first elements in L.
1140//
1141// Most input values are 0, so a `while index > 0` loop skips the shift when
1142// `index == 0`. Masking with `& 0xff` proves to the compiler that every access
1143// to the 256-entry `mtf` array is in bounds.
1144fn InverseMoveToFrontTransform(v: &mut [u8],
1145                               v_len: u32,
1146                               mtf: &mut [u8;256],
1147                               mtf_upper_bound: &mut u32) {
1148  // Reinitialize elements that could have been changed.
1149  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  // Transform the input.
1155  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  // Remember amount of elements to be reinitialized.
1168  *mtf_upper_bound = new_upper_bound;
1169}
1170// Decodes a series of Huffman table using ReadHuffmanCode function.
1171fn 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  // This room also holds the windows the command loop reads the literal and
1223  // insert-and-copy trees through (`LITERAL_TABLE_WINDOW` and
1224  // `INSERT_COPY_TABLE_WINDOW` are the max table sizes of their alphabets).
1225  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    // Growing frees the old buffer.  Block trees must not be allocated after a
1230    // free (see EnsureBlockTrees), so allocate them first in that rare case.
1231    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, // break and return the result code
1251    }
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
1320// Decodes a context map.
1321// Decoding is done in 4 phases:
1322// 1) Read auxiliary information (6..16 bits) and allocate memory.
1323// In case of trivial context map, decoding is finished at this phase.
1324// 2) Decode Huffman table using ReadHuffmanCode function.
1325// This table will be used for reading context map items.
1326// 3) Read context map items; "0" values could be run-length encoded.
1327// 4) Optionally, apply InverseMoveToFront transform to the resulting map.
1328//
1329fn 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        // No break, continue to next state.
1365      }
1366      BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_READ_PREFIX => {
1367        let mut bits: u32 = 0;
1368        // In next stage ReadHuffmanCode uses at least 4 bits, so it is safe
1369        // to peek 4 bits ahead.
1370        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          // Use RLE for zeroes.
1375          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        // No break, continue to next state.
1384      }
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        // No break, continue to next state.
1408      }
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; // <- this was a goto beforehand... now we have reached label
1440          // we are treated like everyday citizens from this point forth
1441          {
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        // No break, continue to next state.
1460        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            // the error state is stored here--we can't make it this deep with an active error
1476            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  // unreachable!(); (compiler will error if it's reachable due to the unit return type)
1485}
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// Decodes a command or literal and updates block type ringbuffer.
1525// Reads 3..54 bits.
1526// A block switch in a category with a single block type is a format error,
1527// not a lack of input: reporting it as BROTLI_DECODER_NEEDS_MORE_INPUT makes
1528// the streaming decoder buffer input that will never complete the read
1529// (CVE-2026-111497 in the C decoder).
1530#[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  // Read 0..15 + 3..39 bits
1546  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
1647// Bytes decoded into the ring buffer but not yet handed to the caller.
1648// Callers must have established CheckRingBufferConsistency.
1649fn 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
1667// The invariant every ring-buffer read depends on: a positive size matching the
1668// mask, and a `pos` inside the allocation. Only a decoder bug can break it, but
1669// it stays a runtime check because the `unsafe` build would read out of bounds
1670// rather than panic.
1671fn 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  // window_bits is 9..=24, or 10..=30 for large-window streams; masked so the
1698  // shift stays in range regardless.
1699  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  // output is caller-supplied, hence INVALID_ARGUMENTS rather than UNREACHABLE.
1709  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  // The public API reports total_out as usize, matching C's size_t: on a 32-bit
1725  // target it truncates past 4GiB, while the internal accounting does not.
1726  *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      // TakeOutput still needs the bytes consumed by this partial write.
1730      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    // A transformed custom-dictionary word can overshoot the end by at most
1757    // 540 bytes (255-byte prefix + 31-byte word + 255-byte suffix, starting at
1758    // the final ring-buffer byte), which is why `pos` may exceed
1759    // `ringbuffer_size`. Wrapping is only done at the full window size, whose
1760    // minimum is 1 << kBrotliLargeMinWbits == 1024, and the tail region is
1761    // kRingBufferWriteAheadSlack + kBrotliMaxDictionaryWordLength bytes long.
1762    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  // Sizes the ring buffer for this metablock; a no-op once that is done, as
1786  // on re-entry after NEEDS_MORE_INPUT.
1787  match BrotliEnsureRingBuffer(s,
1788                               BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1) {
1789    BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
1790    error => return error,
1791  }
1792  // State machine
1793  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        // Copy remaining bytes from s.br.buf_ to ringbuffer.
1800        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        // s.partial_pos_rb += (size_t)s.ringbuffer_size;
1814        // No break, continue to next state by going aroudn the loop
1815      }
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
1836// We need the slack region for the following reasons:
1837// - doing up to two 16-byte copies for fast backward copying (32 bytes,
1838//   subsumed by the dictionary-word case below)
1839// - inserting a transformed dictionary word past the end of the ring
1840//   buffer: prefix + base word + suffix. The built-in transforms need only
1841//   5 + 24 + 8 = 37, but a serialized shared dictionary may define
1842//   transforms with full-length affixes, so a word starting on the last
1843//   ring-buffer byte can write this far past it.
1844const kRingBufferWriteAheadSlack: i32 =
1845  SHARED_BROTLI_MAX_TRANSFORM_AFFIX_LENGTH as i32           // 255-byte prefix
1846  + (SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH as i32 + 1)   //  32: 31-byte word, rounded up
1847  + SHARED_BROTLI_MAX_TRANSFORM_AFFIX_LENGTH as i32;        // 255-byte suffix => 542
1848// The C implementation hardcodes 542; fail the build if the two drift apart.
1849const _RING_BUFFER_SLACK_MATCHES_C: [(); 542] = [(); kRingBufferWriteAheadSlack as usize];
1850// Bytes allocated past ringbuffer_size: the write-ahead slack plus one more
1851// maximal built-in dictionary word, as this decoder has always allocated.
1852const kRingBufferAllocationSlack: usize =
1853  kRingBufferWriteAheadSlack as usize + kBrotliMaxDictionaryWordLength as usize;
1854// Smallest ring buffer allocated, as in the C decoder: starting at 1 KiB saves
1855// reallocations while the ring buffer grows. Any window is at least this large
1856// (1 << kBrotliLargeMinWbits).
1857const kRingBufferMinSize: i64 = 1024;
1858// A one-shot caller's output buffer may be far larger than the stream. Use it
1859// to grow at most four times the ring size needed by the decoded data alone.
1860const kOneShotRingBufferGrowthFactor: i64 = 4;
1861// Smallest ring buffer allocated for a last metablock, after which the ring
1862// buffer never grows, so the C decoder's larger minimum would buy nothing: the
1863// 32 bytes this decoder used for a stream of one short metablock before growth
1864// on demand. A fixed u8 pool (see u8_pool_size) starts every ring buffer this
1865// small, which also covers a short uncompressed metablock followed by an empty
1866// last one when BrotliCalculateRingBufferSize cannot see that last one yet.
1867const kSmallRingBufferMinSize: i64 = 32;
1868
1869// Calculates the smallest feasible ring buffer; a port of the C decoder's
1870// BrotliCalculateRingBufferSize. The ring buffer starts small and, whenever a
1871// metablock needs more room, grows to the smallest power of two that holds
1872// everything decoded so far plus that metablock, up to the window size. So a
1873// short stream never pays for the whole window (4 MiB at the encoder's default
1874// lgwin of 22), even when its data is not in the last metablock. Once the ring
1875// buffer reaches the window size it is never reallocated again. Unlike C, a
1876// ring buffer first allocated for the last metablock may be smaller than 1 KiB.
1877//
1878// A fixed u8 pool (u8_pool_size != 0) cannot merge the blocks that growth
1879// frees, so growing to the whole window takes up to twice the window from it.
1880// For such a pool the ring buffer is sized so that it never needs more of the
1881// pool than before growth on demand: a pool that can hold the whole window
1882// gets it at once for any metablock but the last one, as it always did, and
1883// otherwise the ring buffer grows from 32 bytes.
1884//
1885// A caller can raise the size the ring buffer starts from with
1886// set_initial_ring_buffer_size; u32::MAX allocates the whole window at once.
1887// A last metablock is still sized to fit, as the ring buffer never grows
1888// after it.
1889//
1890// An uncompressed metablock is never the last one, but encoders store small or
1891// incompressible input as one followed by an empty last metablock. So, as this
1892// decoder did before growth on demand, the first ring buffer for an
1893// uncompressed metablock is sized as for a last one when the header after its
1894// data, peeked from `input`, is an empty last metablock. If that header is not
1895// in `input` yet, the metablock is sized as one that is not last.
1896//
1897// This only computes new_ringbuffer_size: BrotliEnsureRingBuffer (re)allocates
1898// once the metablock is about to write to the ring buffer.
1899//
1900// When this method is called, metablock size and flags MUST be decoded.
1901fn 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  // window_bits is 10..=24, or 10..=30 for large-window streams. The sizes are
1907  // computed as i64, and the shift masked, so no state can overflow them.
1908  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  // Whether no data follows this metablock.
1912  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    // -1 if the header is not in the input yet; else ISLAST and ISLASTEMPTY
1917    // are its two low bits.
1918    if next_block_header != -1 && (next_block_header & 3) == 3 {
1919      is_last = true;
1920    }
1921  }
1922  // We need at least 2 bytes of ring buffer size to get the last two
1923  // bytes for context from there
1924  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    // Rounded up to a power of two, and capped at the window, by the loop
1930    // below.
1931    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 maximum is already reached, no further extension is required.
1939  if s.ringbuffer_size as i64 == window_size {
1940    return;
1941  }
1942
1943  // Metadata blocks do not touch the ring buffer.
1944  if s.is_metadata != 0 {
1945    return;
1946  }
1947
1948  // Everything decoded so far stays in the ring buffer, which has not wrapped:
1949  // it wraps only once it is as large as the window.
1950  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  // Whether this is a fixed pool that can hold the whole window. The sum is
1966  // taken in u64, which cannot overflow: window_size as u64 is at most 2^63.
1967  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    // Reduce ring buffer size to save memory when server is unscrupulous.
1971    // In worst case memory usage might be 1.5x bigger for a short period of
1972    // ring buffer reallocation. A min_size of at least 1 keeps the loop
1973    // finite whatever the state holds.
1974    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  // Only a window_bits the decoder never accepts gives a size outside i32;
1981  // 0 then makes BrotliEnsureRingBuffer reject the state instead.
1982  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
1990// Allocates the ring buffer, or grows it to new_ringbuffer_size keeping the
1991// bytes decoded so far; a port of the C decoder's BrotliEnsureRingBuffer.
1992//
1993// new_ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
1994// this function is called.
1995//
1996// Last two bytes of ring buffer are initialized to 0, so context calculation
1997// could be done uniformly for the first two and all other positions.
1998//
1999// Nothing here can panic, and on failure the decoder keeps its current ring
2000// buffer untouched, so the state stays consistent and droppable. Returns
2001// `alloc_error` if the allocator cannot supply the memory, and UNREACHABLE
2002// for a state the decoder could not have produced.
2003fn 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  // The ring buffer is only reallocated before it first wraps (it wraps only
2014  // at the window size, which is final), so the decoded bytes are exactly
2015  // [0, pos) of the current allocation. The new size must be a power of two,
2016  // so that its mask works as a modulus, at least 2 for the context bytes, and
2017  // large enough to hold those bytes. These checks keep every index below in
2018  // bounds.
2019  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    // Normally the empty cell of a failed allocation. Hand it back regardless:
2031    // a short cell from a misbehaving allocator is still the allocator's.
2032    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
2049// Lazily builds compound_dictionary.block_map, a 256-entry table that maps
2050// address >> block_bits to the first chunk that might contain that address.
2051fn EnsureCompoundDictionaryInitialized<AllocU8: alloc::Allocator<u8>>(
2052  addon: &mut state::BrotliDecoderCompoundDictionary<AllocU8>,
2053) {
2054  // 256 = (1 << 8) slots in block map.
2055  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    // chunk_offsets[num_chunks] is a sentinel equal to maximal_address + 1.
2069    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  // Now if X is in the range [0..maximal_address] then
2079  // block_map[X >> block_bits] is in [0..num_chunks).
2080}
2081
2082// Prepares a copy of `length` bytes starting at compound dictionary address
2083// `address` (0 = first byte of the first chunk). Returns false if the copy
2084// would run off the end of the dictionary.
2085#[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  // Several chunks might be mapped to the same block index.
2098  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// Copies the prepared dictionary reference into the ring buffer at `pos`,
2109// stopping at the end of the ring buffer if necessary (the caller flushes
2110// and re-invokes). An external chunk's bytes are `external`, whose size
2111// BrotliDecompressStreamWithDictionary has checked. Returns the number of
2112// bytes copied.
2113#[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  // StandardAlloc for u8 cells, except that requests of at least `fail_at`
2160  // bytes fail and `short` hands out one byte less than asked. Records every
2161  // request and counts the cells handed out and taken back.
2162  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  // What BrotliDecompressStream does for a metablock of `mlen` bytes: size the
2213  // ring buffer at the header, then allocate before writing to it.
2214  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  // Stands in for decoding the metablock: writes its `mlen` bytes after `pos`.
2221  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    // The context bytes of the first two positions read the zeroed tail.
2254    assert_eq!(&s.ringbuffer.slice()[1022..1024], &[0, 0]);
2255    finish_metablock(&mut s);
2256    // A metablock that exactly fits the rest of the ring buffer reuses it.
2257    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    // One byte more than fits doubles it, keeping everything decoded so far.
2262    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    // It grows straight to the smallest power of two that fits.
2268    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    // No larger than the window...
2273    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    // ...which is final: later metablocks wrap it instead.
2278    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    // Each growth handed the previous ring buffer back.
2284    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    // A short first metablock gets 1 KiB whatever the window, even when it is
2298    // not the last one (which used to allocate the whole window).
2299    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    // The smallest window is the smallest ring buffer.
2305    assert_eq!(first_size(10, 1, true, false), 1024);
2306    // BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: always the window.
2307    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    // The one departure from C: the ring buffer never grows after the last
2311    // metablock, so if that is the first to need it, it may be under 1 KiB.
2312    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    // Metadata does not touch the ring buffer.
2319    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  // With a fixed u8 pool, the ring buffer never needs more of the pool than
2328  // before growth on demand, when the whole window came at once for any
2329  // metablock but the last one, and a last one got as little as 32 bytes.
2330  #[test]
2331  fn fixed_pool_ring_buffer_needs_no_more_than_before_growth() {
2332    let slack = kRingBufferAllocationSlack;
2333    let window = 1usize << 16;
2334    // A pool that holds the whole window gets it at once...
2335    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    // ...unless the metablock is the last one.
2345    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    // A smaller pool could not hold the whole window, so the ring buffer
2351    // grows, starting from 32 bytes rather than 1 KiB.
2352    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    // BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION still wins.
2367    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    // Needs a 4 MiB ring buffer, which the allocator refuses.
2382    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    // Nothing was lost, so once memory is available the growth goes through.
2391    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    // No size was calculated.
2419    assert_eq!(ensure(&mut s), unreachable);
2420    // Not a power of two.
2421    s.new_ringbuffer_size = 1000;
2422    assert_eq!(ensure(&mut s), unreachable);
2423    // Decoded bytes that would not fit, or that were never allocated.
2424    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    // A ring buffer that has wrapped can no longer be moved.
2432    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  // Packs fields least significant bit first, as brotli streams are laid out.
2441  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    // Uncompressed data starts at the next byte boundary.
2459    fn raw(&mut self, data: &[u8]) {
2460      self.bytes.extend_from_slice(data);
2461      self.bits = self.bytes.len() * 8;
2462    }
2463  }
2464
2465  // A stream with a 64 KiB window of uncompressed metablocks of the given
2466  // lengths, then an empty last one; and the pseudo-random data it holds.
2467  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); // WBITS=16
2470    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      // ISLAST=0, MNIBBLES=4, MLEN-1, ISUNCOMPRESSED=1.
2478      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); // ISLAST=1, ISLASTEMPTY=1
2486    (writer.bytes, data)
2487  }
2488
2489  // Hands the decoder at most in_chunk bytes of input and out_chunk bytes of
2490  // output space per call.
2491  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    // 10 + 1000 bytes fit in 1 KiB; 2510 need 4 KiB and 5510 need 8 KiB;
2517    // 35510 need the whole 64 KiB window, which the rest then wraps around.
2518    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    // The whole window at once, where the stream above grows to it in four.
2539    assert_eq!(s.alloc_u8.requests, [65536 + kRingBufferAllocationSlack]);
2540    // Once decoding has started, nothing changes.
2541    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    // Rounded up to a power of two of at least 32 bytes...
2561    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    // ...that still holds the metablock...
2565    assert_eq!(first_size(4096, 5000, false), 8192);
2566    // ...and is no larger than the window.
2567    assert_eq!(first_size(u32::MAX, 10, false), 1 << 22);
2568    // A last metablock is sized to fit, as the ring buffer never grows after it.
2569    assert_eq!(first_size(u32::MAX, 10, true), 32);
2570    // Disabling reallocation still allocates the whole window.
2571    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    // At 64 KiB of decoded output, jump fourfold instead of taking every
2599    // intermediate power of two on the way to the caller's output capacity.
2600    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    // Even with a much larger output buffer and a large window, a short
2612    // stream cannot force the full output capacity into the first ring.
2613    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    // One byte starts decoding the stream header, before any ring buffer...
2629    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    // ...after which the size no longer changes.
2639    assert!(!s.set_initial_ring_buffer_size(0));
2640    assert!(decode_in_chunks(&mut s, &input[1..], 333, 777) == expected);
2641    // The whole window at once, where by default this stream grows to it in
2642    // four allocations (see ring_buffer_grows_across_metablocks_then_wraps).
2643    assert_eq!(s.alloc_u8.requests, [65536 + kRingBufferAllocationSlack]);
2644  }
2645
2646  // Encoders store small or incompressible input as an uncompressed metablock
2647  // and an empty last one. When the decoder can see the empty one, it sizes the
2648  // ring buffer for the uncompressed one as for a last metablock.
2649  #[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    // With the empty last metablock in the input, whatever the initial size...
2661    assert_eq!(requests(0, true, usize::MAX), [32 + slack]);
2662    assert_eq!(requests(u32::MAX, true, usize::MAX), [32 + slack]);
2663    // ...though disabling reallocation still takes the whole window.
2664    assert_eq!(requests(0, false, usize::MAX), [65536 + slack]);
2665    // One byte at a time, the uncompressed metablock is sized as not last.
2666    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    // The existing 10x10y stream, embedded so this regression needs no fixture.
2673    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    // The end wraps to zero on 32-bit and is out of bounds on 64-bit.
2787    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    // The alphabets the decoder uses, so the groups have the room the
2813    // command loop's table windows expect.
2814    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
2842// The table for decoding context maps, needed only by metablocks with more
2843// than one tree in a group.
2844fn 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
2855// Allocates the context-map table, block-type trees, and block-length trees
2856// unless they are already allocated. Returns false if an allocation fails.
2857// Callers invoke this before freeing/growing any reusable metablock buffer so
2858// fixed pool allocators never see an allocation after a free.
2859fn 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
2884// Reads 1..256 2-bit context modes.
2885pub 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    // kDistanceShortCodeIndexOffset has 2-bit values from LSB:
2925    // 3, 2, 1, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2
2926    const kDistanceShortCodeIndexOffset: u32 = 0xaaafff1b;
2927    // kDistanceShortCodeValueOffset has 2-bit values from LSB:
2928    // -0, 0,-0, 0,-1, 1,-2, 2,-3, 3,-1, 1,-2, 2,-3, 3
2929    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        // A huge distance will cause a BROTLI_FAILURE() soon.
2939        // This is a little faster than failing here.
2940        *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
2959// Selects a command loop flavour at compile time. Associated consts rather than
2960// const generics: const generics need Rust 1.51.
2961trait 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 second-level distance Huffman lookup (`table_element.bits > 8`).
2970// Outlined so the common 8-bit root lookup in `read_distance` needs only the
2971// thin `&DistanceRootTable` pointer and never loads `distance_hgroup` or
2972// `dist_context_map` from `BrotliState` unless `root.bits > 8`.
2973#[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// Converts the decoded distance symbol `code` to `*distance_code`, reading its
3000// extra bits. Precondition: *distance_code < 0. `memento` is the reader state
3001// from before the symbol was read; only the safe path uses it, to roll back
3002// when the extra bits are not all available yet (the fast path passes a
3003// default state).
3004#[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      // NPOSTFIX == 0 (every metablock below q10, and many at q10-q11):
3030      // `checked_sub` handles direct codes (`16 <= code < ndirect`) and codes
3031      // with extra bits (`code >= ndirect`) with one comparison, in 32-bit
3032      // arithmetic (identical in the low 32 bits for the at most 30-bit extra
3033      // distances the alphabet limit allows).
3034      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      // NPOSTFIX > 0 (primarily q10-q11, where NDIRECT is also often non-zero):
3049      // branchless decode avoids ~1.5M branch mispredictions on mixed direct /
3050      // extra-bit distance streams such as `wiki-Brotli.html` q11. When
3051      // `code < num_direct`, `distval < 0`, `mask == 0`, and `nbits == 0`, so
3052      // `read_bits(0)` consumes 0 bits and returns 0 while the masked formula
3053      // reduces to `code - 15`.
3054      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  // 64-bit shifts are multi-instruction sequences on 32-bit targets; the low
3107  // 32 bits, all that the `i32` result keeps, are the same in u32.
3108  #[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  // `kCmdLut` is padded to 1024 entries, so masking (a single bit-field
3150  // clear) replaces a compare and branch; valid insert-and-copy codes are
3151  // below 704.
3152  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// Copies 16 bytes `[0..16]` in the ring buffer while checking `<= len - 32` up
3201// front (the ring buffer always carries `kRingBufferAllocationSlack = 566 >= 32`
3202// bytes past `ringbuffer_size`). Using the exact same `len < 32 || max > len - 32`
3203// guard as `memmove16_offset16` lets LLVM GVN eliminate the second bounds check
3204// on the `17 <= copy_len <= 32` path and kills `max(off_dst, off_src)` before
3205// the copy, reducing register pressure in `ProcessCommands`.
3206#[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  // On 32-bit targets (ARMv7), `clone_from_slice` on a 16-byte range emits
3224  // panicking slice bounds checks; matching a 16-element slice prefix lowers
3225  // to a single unaligned NEON `vld1.8`/`vst1.8` pair with no panic path.
3226  #[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// Copies bytes `[16..32]` relative to `u32off_src`/`u32off_dst` by matching a
3260// 32-byte slice prefix at `off_src`/`off_dst` rather than computing `off + 16`
3261// up front. This lets LLVM reuse the `&data[off_src]`/`&mut data[off_dst]`
3262// base pointers from the preceding `memmove16_from_ringbuffer` with an immediate `#16` offset
3263// instead of hoisting `dst_start + 16`/`src_start + 16` across `copy_len > 32`.
3264#[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  // Both ranges must fit and must not overlap: the `unsafe` build lowers this to
3343  // copy_nonoverlapping, and the safe build's split_at_mut would panic.
3344  // Subtraction, not `off + size`, so no caller offset can wrap past the checks.
3345  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  /* After unrecoverable error remaining output is considered nonsensical. */
3379  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  // Either WriteRingBuffer returns those "success" codes...
3407  match status {
3408    BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS |  BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT => {
3409      *size = requested_out - available_out;
3410    },
3411    _ => {
3412      // ... or stream is broken. Normally this should be caught by
3413      //   BrotliDecoderDecompressStream, this is just a safeguard.
3414      if is_fatal(status) {
3415        // SaveErrorCode!(s, status); //borrow checker doesn't like this
3416        // but since it's a safeguard--ignore
3417      }
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// The tree with the given index in a Huffman tree group, as
3453// HuffmanTreeGroup::build_hgroup_cache lists them; empty if there is none.
3454#[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// As huffman_tree, as a fixed window (see huffman::HuffmanTable).
3466// Outlined on 32-bit targets so LLVM LICM does not hoist `&group.codes` and
3467// `&EMPTY_TABLE` out of cold block-switch paths into `ProcessCommands`'s
3468// loop preheader.
3469#[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// The 256-entry root tables of the 4 distance contexts at `slice_index` in the
3485// distance context map, sharing the lookup when contexts use the same tree
3486// (all 4 do below q10). Thin `&DistanceRootTable` pointers avoid carrying a
3487// fat-slice length register and per-symbol bounds check in `read_distance`.
3488#[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// Fills `trees[context]` with the literal tree of each of the 64 contexts of
3528// the literal block type whose context map starts at `context_map[slice_index]`.
3529#[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      // Context maps are RLE-encoded and typically contain long runs of
3539      // identical tree indices; reuse the resolved table reference across
3540      // adjacent equal entries.
3541      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// Takes `fbr` by value and returns it (like `decode_literal_batch`) so
3559// outlining on 32-bit targets does not force `fbr` into a stack `alloca` in
3560// `ProcessCommands`.
3561#[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  // A reader over the remaining input, in the same bit layout as the slice.
3569  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// Executes a compound, custom shared, or static dictionary reference when
3687// `distance_code > max_distance`. Returns `Ok((new_pos, post_write_1))`.
3688#[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  // Distances in (max_distance, max_distance + compound_dictionary_size]
3711  // address the attached compound dictionary, furthest byte first.
3712  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    // A dictionary of one chunk (the common case: one attached raw
3717    // dictionary) whose copy ends before the ring buffer does is a plain
3718    // slice copy, without the chunked block-map walk.
3719    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// Copies `rem` bytes from `pos - distance_code` (modulo `rb_mask`) into `rb`,
3796// stopping early and returning `(new_pos, new_rem, true)` if `pos` reaches `rb_size`.
3797#[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// Unified command loop parameterized over a `CommandLoopMode`:
3860// - `FastCommandLoop`: entered from `COMMAND_BEGIN` with `>= 28` input bytes,
3861//   compiling to a single-entry loop over `BitReaderSlice` with in-place
3862//   `HuffmanTreeGroup` borrows.
3863// - `SafeCommandLoop`: streaming/tail fallback handling arbitrary command entry
3864//   states, `< 28`-byte input tails, and single-command resumption.
3865#[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  // The 256-entry root tables of the 4 distance contexts of the current
3942  // distance block type, resolved once per block type instead of reading the
3943  // distance context map and looking a tree up whenever consecutive distances
3944  // use different contexts (most distances at q10-q11).
3945  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      // Check if the copy extends over the ringbuffer end or overlaps with
4424      // itself before the speculative 16-byte copy. `copy_wrap_or_overlapping`
4425      // overwrites `[pos..pos + i]` from the beginning, so skipping the
4426      // 16-byte copy on the wrap/overlap path is semantically identical and
4427      // lets the wrap check (`hi + copy_len_u32`), overlap check (`hi - lo <
4428      // copy_len_u32`), and slice bounds check (`hi <= len - 32`) share
4429      // `hi = max(dst_start_u32, src_start_u32)`.
4430      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// Kept out of line: inlined into BrotliDecompressStream, the command loop would
4508// share registers with the whole stream state machine and reload its state
4509// from the stack.
4510#[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
4560/* Returns the maximum number of distance symbols which can only represent
4561   distances not exceeding BROTLI_MAX_ALLOWED_DISTANCE. */
4562pub 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
4593// As BrotliDecompressStream, lending the decoder `dictionary` for this call:
4594// the dictionary attached with BrotliState::attach_external_dictionary, or an
4595// empty slice if there is none. Any other size fails with
4596// BROTLI_DECODER_ERROR_INVALID_ARGUMENTS.
4597pub 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
4617// As BrotliDecompressStream, lending the decoder `dictionary` for this call:
4618// the dictionary attached with BrotliState::attach_external_dictionary, or an
4619// empty slice if there is none. Also pass in a callback to be called back with any
4620// metadata metablocks that are encountered.
4621pub 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              // Used with internal buffer.
4694              if s.br.avail_in == 0 {
4695                // Successfully finished read transaction.
4696                // Accamulator contains less than 8 bits, because internal buffer
4697                // is expanded byte-by-byte until it is enough to complete read.
4698                s.buffer_length = 0;
4699                // Switch to input stream and restart.
4700                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                // Not enough data in buffer, but can take one more byte from
4708                // input stream.
4709                result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
4710                let new_byte = fast!((xinput)[*input_offset]);
4711                let buffer_length = s.buffer_length as usize;
4712                // This byte was copied into saved_buffer at function entry.
4713                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                // Retry with more data in buffer.
4723                // we can't re-borrow the saved buffer...so we have to do this recursively
4724                continue;
4725              }
4726              // Can't finish reading and no more input.
4727
4728              // FIXME :: NOT SURE WHAT THIS MEANT
4729              // saved_buffer = core::mem::replace(
4730              //  &mut s.br.input_,
4731              //  &mut[]); // clear input
4732              break;
4733            } else {
4734              // Input stream doesn't contain enough input.
4735              // Copy tail to internal buffer and return.
4736              *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            // unreachable!(); <- dead code
4754          }
4755          _ => {
4756            // Fail or needs more output.
4757            if s.buffer_length != 0 {
4758              // Just consumed the buffered input and produced some output. Otherwise
4759              // it would result in "needs more input". Reset internal buffer.
4760              s.buffer_length = 0;
4761            } else {
4762              // Using input stream in last iteration. When decoder switches to input
4763              // stream it has less than 8 bits in accamulator, so it is safe to
4764              // return unused accamulator bits there.
4765              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      // this emulates fallthrough behavior
4780      match s.state {
4781        BrotliRunningState::BROTLI_STATE_UNINITED => {
4782          // Prepare to the first read.
4783          if (!bit_reader::BrotliWarmupBitReader(&mut s.br, local_input)) {
4784            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4785            break;
4786          }
4787          // Decode window size.
4788          /* Reads 1..8 bits. */
4789          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          // A dictionary passed at construction time becomes a compound
4815          // dictionary chunk; it is kept in its own buffer rather than
4816          // prepended to the ring buffer so that it remains addressable
4817          // after the ring buffer wraps.
4818          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          // block_type_trees and block_len_trees are allocated when first
4827          // needed; see EnsureBlockTrees.
4828
4829          s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
4830          // No break, continue to next state
4831        }
4832        BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN => {
4833          s.BrotliStateMetablockBegin();
4834          BROTLI_LOG_UINT!(s.pos);
4835          s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER;
4836          // No break, continue to next state
4837        }
4838        BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER => {
4839          result = DecodeMetaBlockLength(&mut s, local_input); // Reads 2 - 31 bits.
4840          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          // Reads 1..11 bits.
4908          {
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          // No break, continue to next state
4928        }
4929        BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_1 => {
4930          // Only a metablock with more than one block type of some kind needs
4931          // the block type and block length trees, so a stream without block
4932          // switches, as most short ones are, may never allocate them.
4933          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          // No break, continue to next state
4957        }
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          // No break, continue to next state
4976        }
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          // No break, continue to next state
5030        }
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          // No break, continue to next state
5039        }
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          // No break, continue to next state
5054        }
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            // Growing a tree group frees its old `codes` buffer. Block trees
5081            // must not be allocated after a free (see `EnsureBlockTrees`), so
5082            // allocate them first when a group from an earlier metablock needs
5083            // a larger `codes` buffer.
5084            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          /*{
5120            let num_distance_codes: u32 = s.num_direct_distance_codes +
5121                                          (48u32 << s.distance_postfix_bits);
5122            result =
5123              DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[2]) as usize) <<
5124                               kDistanceContextBits as usize,
5125                               true,
5126                               s,
5127                               local_input);
5128            match result {
5129              BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5130              _ => break,
5131            }
5132            s.literal_hgroup.init(&mut s.alloc_u32,
5133                                  &mut s.alloc_hc,
5134                                  kNumLiteralCodes,
5135                                  s.num_literal_htrees as u16);
5136            s.insert_copy_hgroup.init(&mut s.alloc_u32,
5137                                      &mut s.alloc_hc,
5138                                      kNumInsertAndCopyCodes,
5139                                      fast!((s.block_type_length_state.num_block_types)[1]) as u16);
5140            s.distance_hgroup.init(&mut s.alloc_u32,
5141                                   &mut s.alloc_hc,
5142                                   num_distance_codes as u16,
5143                                   s.num_dist_htrees as u16);
5144            if (s.literal_hgroup.codes.slice().len() == 0 ||
5145                s.insert_copy_hgroup.codes.slice().len() == 0 ||
5146                s.distance_hgroup.codes.slice().len() == 0) {
5147              return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS);
5148            }
5149          }*/
5150          s.loop_counter = 0;
5151          s.state = BrotliRunningState::BROTLI_STATE_TREE_GROUP;
5152          // No break, continue to next state
5153        }
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              /*
5165            s.context_map_slice_index = 0;
5166            let context_mode_index = fast!((s.block_type_length_state.block_type_rb)[1]);
5167            let context_mode = fast_slice!((s.context_modes)[context_mode_index as usize]);
5168            s.context_lookup = &kContextLookup[context_mode as usize & 3];
5169               */
5170            s.htree_command_index = 0;
5171            // look it up each time s.literal_htree=s.literal_hgroup.htrees[s.literal_htree_index];
5172            // The header is fully decoded: size the ring buffer for the body.
5173            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                // Resume an interrupted copy from the compound dictionary.
5218                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                  // Ring buffer is full again; flush it and continue copying.
5230                  continue;
5231                }
5232              }
5233              if (s.meta_block_remaining_len <= 0) {
5234                // Next metablock, if any
5235                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              // BROTLI_STATE_COMMAND_INNER_WRITE
5246              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          // RFC 7932 §9.3: "if the number of literals to insert, the copy
5261          // length, or the resulting dictionary word length would cause MLEN to
5262          // be exceeded, then the stream should be rejected as invalid." When a
5263          // command overshoots the declared meta-block length, the command loop
5264          // exits to this state with meta_block_remaining_len < 0. The only
5265          // negative-length guard was in WriteRingBuffer, which is not reached
5266          // when the whole output fits in the ring buffer before the final
5267          // flush, so such malformed streams decoded as success. The C
5268          // reference and andybalholm/brotli (Go) reject them as BLOCK_LENGTH_2;
5269          // mirror that check here, before cleanup.
5270          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            // Keep `context_modes`, `context_map`, `dist_context_map`, and the
5276            // Huffman tree groups allocated so the next metablock can reuse
5277            // their buffers when they are large enough.
5278            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
5279            break;
5280          }
5281          s.BrotliStateCleanupAfterMetablock();
5282          if (!bit_reader::BrotliJumpToByteBoundary(&mut s.br)) {
5283            // RFC 7932 §9.2: padding bits at the end of the final metablock
5284            // must be zero. Without `break`, control falls through to
5285            // BROTLI_STATE_DONE which calls WriteRingBuffer and unconditionally
5286            // overwrites `result` with that call's return value, silently
5287            // dropping the padding error.
5288            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          // No break, continue to next state
5298        }
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  // ProcessCommandsInternal indexes the 64 literal trees of a block type with
5370  // `context & 63` for context = lookup[p1] | lookup[p2 + 256]: the mask
5371  // changes nothing only while every entry is below 64.
5372  #[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    // Both require 32 readable and writable bytes from each offset.
5414    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    // The last offsets that fit.
5424    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    // Disjoint and overlapping ranges in both directions, including the
5435    // distances below 16 that LZ77 copies hit.
5436    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// These need a live BrotliState, so they need an allocator: StandardAlloc is
5467// std-only, as in the `tests` module above.
5468#[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  // A decoder whose ring buffer is consistent: size is a power of two, mask is
5486  // size - 1, and the allocation is at least that long.
5487  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  // None of the guards below is reachable through BrotliDecompressStream, so
5498  // each is driven directly from an inconsistent decoder state. They exist
5499  // because the `unsafe` build turns an out-of-range index into an out-of-bounds
5500  // access rather than a panic.
5501
5502  #[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    // mask that does not match the size
5519    s.ringbuffer_mask = 7;
5520    assert!(!CheckRingBufferConsistency(&s));
5521    s.ringbuffer_mask = 15;
5522
5523    // size larger than the allocation
5524    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    // rb_roundtrips * ringbuffer_size alone overflows a 32-bit usize, so this
5532    // only stays exact because the counters are u64.
5533    let mut s = state_with_ringbuffer(1 << 16, 16);
5534    s.rb_roundtrips = 1 << 17; // 2^17 * 2^16 == 2^33 bytes decoded
5535    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; // no longer size - 1
5544    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; // 8 bytes pending
5576    let mut available_out = 8usize;
5577    let mut output = [0u8; 8];
5578    // output_offset past the end of the caller's buffer: available_out claims
5579    // room the slice does not have.
5580    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    // size beyond the allocation
5603    s.ringbuffer_size = 64;
5604    s.pos = 1;
5605    assert!(!WrapRingBuffer(&mut s));
5606
5607    // pos past the tail region the wrap copies from
5608    s.ringbuffer_size = 16;
5609    s.pos = 8;
5610    assert!(!WrapRingBuffer(&mut s));
5611
5612    // and a state it can handle: half the buffer is the tail region
5613    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    // The simple-code builder needs 1 << HUFFMAN_TABLE_BITS entries; a caller
5636    // slice shorter than that must surface as an error, not a partial table.
5637    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    // Nothing left to read, and a complete code, so the builder runs.
5652    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    // Resuming BROTLI_STATE_HUFFMAN_COMPLEX with a histogram that does not
5665    // describe code_length_code_lengths is exactly what the builder's
5666    // consistency check exists to catch: without it the sort loop indexes
5667    // `sorted` out of bounds.
5668    let mut s = state();
5669    s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_COMPLEX;
5670    // Resume with every code-length code already read (sub_loop_counter at the
5671    // end of kCodeLengthCodeOrder) and a single code recorded, so
5672    // ReadCodeLengthCodeLengths returns success without consuming input.
5673    s.sub_loop_counter = super::CODE_LENGTH_CODES as u32;
5674    s.repeat = 1;
5675    s.space = 32;
5676    // ...but claim a length that code_length_code_lengths does not contain.
5677    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    // partial_pos_out lagging by more than one full ring makes `to_write`
5688    // exceed what actually lives in the buffer.
5689    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    // Neither CONTEXT_MAP_1 with is_dist=false nor CONTEXT_MAP_2 with true.
5724    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  // CVE-2026-111497: the C decoder reported a block switch in a category with
5742  // a single block type as needing more input, and the streaming loop then
5743  // overran its 8-byte input buffer waiting for input that could not help.
5744  #[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// read_metadata_block driven directly from bit readers holding 0..=8 whole
5782// bytes in the accumulator, as a byte-aligned metadata header can leave them.
5783#[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  // Bytes the bit reader's accumulator holds: 8 on 64-bit targets, 4 on
5804  // 32-bit ones.
5805  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  // A reader over all of `input` with its first `buffered` bytes pulled into
5812  // the accumulator.
5813  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        // Input untouched; the bytes after the block are still buffered, in
5875        // order, ahead of the input.
5876        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        // The accumulator is now cold. Both ways the decoder reads next must
5907        // resume at the first byte after the block: the safe byte-at-a-time
5908        // reads of a meta-block header, and the warmed-up, window-filling
5909        // reads of the compressed fast path.
5910        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        // The decoder hands over more input the same way: same buffer
5942        // extended, cursor where it stopped.
5943        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}