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// Once a regrown ring buffer would reach this fraction of the window, it is
1862// grown to the window at once (see BrotliCalculateRingBufferSize).
1863const kRingBufferGrowthJumpDivisor: i64 = 2;
1864// Smallest ring buffer allocated for a last metablock, after which the ring
1865// buffer never grows, so the C decoder's larger minimum would buy nothing: the
1866// 32 bytes this decoder used for a stream of one short metablock before growth
1867// on demand. A fixed u8 pool (see u8_pool_size) starts every ring buffer this
1868// small, which also covers a short uncompressed metablock followed by an empty
1869// last one when BrotliCalculateRingBufferSize cannot see that last one yet.
1870const kSmallRingBufferMinSize: i64 = 32;
1871
1872// Calculates the smallest feasible ring buffer; a port of the C decoder's
1873// BrotliCalculateRingBufferSize. The ring buffer starts small and, whenever a
1874// metablock needs more room, grows to the smallest power of two that holds
1875// everything decoded so far plus that metablock, up to the window size. So a
1876// short stream never pays for the whole window (4 MiB at the encoder's default
1877// lgwin of 22), even when its data is not in the last metablock. Once the ring
1878// buffer reaches the window size it is never reallocated again. Unlike C, a
1879// ring buffer first allocated for the last metablock may be smaller than 1 KiB.
1880//
1881// A fixed u8 pool (u8_pool_size != 0) cannot merge the blocks that growth
1882// frees, so growing to the whole window takes up to twice the window from it.
1883// For such a pool the ring buffer is sized so that it never needs more of the
1884// pool than before growth on demand: a pool that can hold the whole window
1885// gets it at once for any metablock but the last one, as it always did, and
1886// otherwise the ring buffer grows from 32 bytes.
1887//
1888// A caller can raise the size the ring buffer starts from with
1889// set_initial_ring_buffer_size; u32::MAX allocates the whole window at once.
1890// A last metablock is still sized to fit, as the ring buffer never grows
1891// after it.
1892//
1893// An uncompressed metablock is never the last one, but encoders store small or
1894// incompressible input as one followed by an empty last metablock. So, as this
1895// decoder did before growth on demand, the first ring buffer for an
1896// uncompressed metablock is sized as for a last one when the header after its
1897// data, peeked from `input`, is an empty last metablock. If that header is not
1898// in `input` yet, the metablock is sized as one that is not last.
1899//
1900// This only computes new_ringbuffer_size: BrotliEnsureRingBuffer (re)allocates
1901// once the metablock is about to write to the ring buffer.
1902//
1903// When this method is called, metablock size and flags MUST be decoded.
1904fn BrotliCalculateRingBufferSize<AllocU8: alloc::Allocator<u8>,
1905                                 AllocU32: alloc::Allocator<u32>,
1906                                 AllocHC: alloc::Allocator<HuffmanCode>>
1907  (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
1908   input: &[u8]) {
1909  // window_bits is 10..=24, or 10..=30 for large-window streams. The sizes are
1910  // computed as i64, and the shift masked, so no state can overflow them.
1911  let window_size = 1i64 << (s.window_bits & 63);
1912  let mut new_ringbuffer_size = window_size;
1913  let fixed_pool = s.u8_pool_size != 0;
1914  // Whether no data follows this metablock.
1915  let mut is_last = s.is_last_metablock != 0;
1916  if s.is_uncompressed != 0 && s.ringbuffer.slice().len() == 0 {
1917    let next_block_header =
1918      bit_reader::BrotliPeekByte(&mut s.br, s.meta_block_remaining_len as u32, input);
1919    // -1 if the header is not in the input yet; else ISLAST and ISLASTEMPTY
1920    // are its two low bits.
1921    if next_block_header != -1 && (next_block_header & 3) == 3 {
1922      is_last = true;
1923    }
1924  }
1925  // We need at least 2 bytes of ring buffer size to get the last two
1926  // bytes for context from there
1927  let mut min_size = if s.ringbuffer_size != 0 {
1928    s.ringbuffer_size as i64
1929  } else if is_last {
1930    kSmallRingBufferMinSize
1931  } else if s.initial_ringbuffer_size != 0 {
1932    // Rounded up to a power of two, and capped at the window, by the loop
1933    // below.
1934    core::cmp::max(s.initial_ringbuffer_size as i64, kSmallRingBufferMinSize)
1935  } else if fixed_pool {
1936    kSmallRingBufferMinSize
1937  } else {
1938    kRingBufferMinSize
1939  };
1940
1941  // If maximum is already reached, no further extension is required.
1942  if s.ringbuffer_size as i64 == window_size {
1943    return;
1944  }
1945
1946  // Metadata blocks do not touch the ring buffer.
1947  if s.is_metadata != 0 {
1948    return;
1949  }
1950
1951  // Everything decoded so far stays in the ring buffer, which has not wrapped:
1952  // it wraps only once it is as large as the window.
1953  let mut output_size = if s.ringbuffer.slice().len() == 0 {
1954    0
1955  } else {
1956    s.pos as i64
1957  };
1958  output_size += s.meta_block_remaining_len as i64;
1959  if min_size < output_size {
1960    min_size = output_size;
1961  }
1962  if !is_last && s.one_shot_output_size != 0 {
1963    let hinted_size = core::cmp::min(s.one_shot_output_size as i64,
1964                                     output_size.saturating_mul(kOneShotRingBufferGrowthFactor));
1965    min_size = core::cmp::max(min_size, hinted_size);
1966  }
1967
1968  // Whether this is a fixed pool that can hold the whole window. The sum is
1969  // taken in u64, which cannot overflow: window_size as u64 is at most 2^63.
1970  let pool_holds_window = fixed_pool &&
1971    s.u8_pool_size as u64 >= window_size as u64 + kRingBufferAllocationSlack as u64;
1972  if s.canny_ringbuffer_allocation && !(pool_holds_window && !is_last) {
1973    // Reduce ring buffer size to save memory when server is unscrupulous.
1974    // In worst case memory usage might be 1.5x bigger for a short period of
1975    // ring buffer reallocation. A min_size of at least 1 keeps the loop
1976    // finite whatever the state holds.
1977    let min_size = core::cmp::max(min_size, 1);
1978    while (new_ringbuffer_size >> 1) >= min_size {
1979      new_ringbuffer_size >>= 1;
1980    }
1981    // Each regrowth allocates a fresh buffer and copies everything decoded so
1982    // far, and the allocator may fault in all of it again. A stream that has
1983    // outgrown a quarter of the window and keeps going is large: grow to the
1984    // window now rather than to half of it and then again. A caller's size
1985    // hint, initial or one-shot, already bounds the growth and is kept to.
1986    if s.ringbuffer_size != 0 && s.initial_ringbuffer_size == 0 &&
1987       s.one_shot_output_size == 0 && !is_last &&
1988       new_ringbuffer_size * kRingBufferGrowthJumpDivisor >= window_size {
1989      new_ringbuffer_size = window_size;
1990    }
1991  }
1992
1993  // Only a window_bits the decoder never accepts gives a size outside i32;
1994  // 0 then makes BrotliEnsureRingBuffer reject the state instead.
1995  s.new_ringbuffer_size = if new_ringbuffer_size > 0 &&
1996                             new_ringbuffer_size <= i32::MAX as i64 {
1997    new_ringbuffer_size as i32
1998  } else {
1999    0
2000  };
2001}
2002
2003// Allocates the ring buffer, or grows it to new_ringbuffer_size keeping the
2004// bytes decoded so far; a port of the C decoder's BrotliEnsureRingBuffer.
2005//
2006// new_ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
2007// this function is called.
2008//
2009// Last two bytes of ring buffer are initialized to 0, so context calculation
2010// could be done uniformly for the first two and all other positions.
2011//
2012// Nothing here can panic, and on failure the decoder keeps its current ring
2013// buffer untouched, so the state stays consistent and droppable. Returns
2014// `alloc_error` if the allocator cannot supply the memory, and UNREACHABLE
2015// for a state the decoder could not have produced.
2016fn BrotliEnsureRingBuffer<AllocU8: alloc::Allocator<u8>,
2017                          AllocU32: alloc::Allocator<u32>,
2018                          AllocHC: alloc::Allocator<HuffmanCode>>
2019  (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2020   alloc_error: BrotliDecoderErrorCode)
2021   -> BrotliDecoderErrorCode {
2022  let new_size = s.new_ringbuffer_size;
2023  if s.ringbuffer_size == new_size && s.ringbuffer.slice().len() != 0 {
2024    return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2025  }
2026  // The ring buffer is only reallocated before it first wraps (it wraps only
2027  // at the window size, which is final), so the decoded bytes are exactly
2028  // [0, pos) of the current allocation. The new size must be a power of two,
2029  // so that its mask works as a modulus, at least 2 for the context bytes, and
2030  // large enough to hold those bytes. These checks keep every index below in
2031  // bounds.
2032  let pos = s.pos;
2033  if new_size < 2 || (new_size & (new_size - 1)) != 0 || pos < 0 || pos > new_size ||
2034     pos as usize > s.ringbuffer.slice().len() || s.rb_roundtrips != 0 {
2035    return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
2036  }
2037  let size = new_size as usize;
2038  let decoded = pos as usize;
2039  let alloc_size = size + kRingBufferAllocationSlack;
2040
2041  let mut new_ringbuffer = s.alloc_u8.alloc_cell(alloc_size);
2042  if new_ringbuffer.slice().len() < alloc_size {
2043    // Normally the empty cell of a failed allocation. Hand it back regardless:
2044    // a short cell from a misbehaving allocator is still the allocator's.
2045    s.alloc_u8.free_cell(new_ringbuffer);
2046    return alloc_error;
2047  }
2048  {
2049    let new_slice = new_ringbuffer.slice_mut();
2050    new_slice[size - 2] = 0;
2051    new_slice[size - 1] = 0;
2052    new_slice[..decoded].clone_from_slice(&s.ringbuffer.slice()[..decoded]);
2053  }
2054  let old_ringbuffer = mem::replace(&mut s.ringbuffer, new_ringbuffer);
2055  s.alloc_u8.free_cell(old_ringbuffer);
2056
2057  s.ringbuffer_size = new_size;
2058  s.ringbuffer_mask = new_size - 1;
2059  BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
2060}
2061
2062// Lazily builds compound_dictionary.block_map, a 256-entry table that maps
2063// address >> block_bits to the first chunk that might contain that address.
2064fn EnsureCompoundDictionaryInitialized<AllocU8: alloc::Allocator<u8>>(
2065  addon: &mut state::BrotliDecoderCompoundDictionary<AllocU8>,
2066) {
2067  // 256 = (1 << 8) slots in block map.
2068  let mut block_bits: u32 = 8;
2069  let maximal_address = addon.total_size as u32 - 1;
2070  if addon.block_bits != COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED {
2071    return;
2072  }
2073  while (maximal_address >> block_bits) != 0 {
2074    block_bits += 1;
2075  }
2076  block_bits -= 8;
2077  addon.block_bits = block_bits;
2078  let mut cursor: u32 = 0;
2079  let mut index: usize = 0;
2080  while cursor <= maximal_address {
2081    // chunk_offsets[num_chunks] is a sentinel equal to maximal_address + 1.
2082    while fast!((addon.chunk_offsets)[index + 1]) < cursor {
2083      index += 1;
2084    }
2085    fast_mut!((addon.block_map)[(cursor >> block_bits) as usize]) = index as u8;
2086    match cursor.checked_add(1 << block_bits) {
2087      Some(next) => cursor = next,
2088      None => break,
2089    }
2090  }
2091  // Now if X is in the range [0..maximal_address] then
2092  // block_map[X >> block_bits] is in [0..num_chunks).
2093}
2094
2095// Prepares a copy of `length` bytes starting at compound dictionary address
2096// `address` (0 = first byte of the first chunk). Returns false if the copy
2097// would run off the end of the dictionary.
2098#[cold]
2099#[inline(never)]
2100fn InitializeCompoundDictionaryCopy<AllocU8: alloc::Allocator<u8>>(
2101  addon: &mut state::BrotliDecoderCompoundDictionary<AllocU8>,
2102  address: usize,
2103  length: usize,
2104) -> bool {
2105  EnsureCompoundDictionaryInitialized(addon);
2106  if length > addon.total_size - address {
2107    return false;
2108  }
2109  let mut index = fast!((addon.block_map)[address >> addon.block_bits]) as usize;
2110  // Several chunks might be mapped to the same block index.
2111  while address as u32 >= fast!((addon.chunk_offsets)[index + 1]) {
2112    index += 1;
2113  }
2114  addon.br_index = index;
2115  addon.br_offset = address - fast!((addon.chunk_offsets)[index]) as usize;
2116  addon.br_length = length;
2117  addon.br_copied = 0;
2118  true
2119}
2120
2121// Copies the prepared dictionary reference into the ring buffer at `pos`,
2122// stopping at the end of the ring buffer if necessary (the caller flushes
2123// and re-invokes). An external chunk's bytes are `external`, whose size
2124// BrotliDecompressStreamWithDictionary has checked. Returns the number of
2125// bytes copied.
2126#[cold]
2127#[inline(never)]
2128fn CopyFromCompoundDictionary<AllocU8: alloc::Allocator<u8>>(
2129  addon: &mut state::BrotliDecoderCompoundDictionary<AllocU8>,
2130  ringbuffer: &mut [u8],
2131  ringbuffer_size: i32,
2132  pos: i32,
2133  external: &[u8],
2134) -> i32 {
2135  let ringbuffer_size = ringbuffer_size as usize;
2136  let mut pos = pos as usize;
2137  let orig_pos = pos;
2138  while addon.br_length != addon.br_copied {
2139    let chunk = match addon.chunks[addon.br_index] {
2140      state::MaybeOwnedSlice::External(_) => external,
2141      ref chunk => chunk.slice(),
2142    };
2143    let space = ringbuffer_size - pos;
2144    let rem_chunk_length = chunk.len() - addon.br_offset;
2145    let mut length = addon.br_length - addon.br_copied;
2146    if length > rem_chunk_length {
2147      length = rem_chunk_length;
2148    }
2149    if length > space {
2150      length = space;
2151    }
2152    fast_mut!((ringbuffer)[pos ; pos + length])
2153      .clone_from_slice(fast!((chunk)[addon.br_offset ; addon.br_offset + length]));
2154    pos += length;
2155    addon.br_offset += length;
2156    addon.br_copied += length;
2157    if length == rem_chunk_length {
2158      addon.br_index += 1;
2159      addon.br_offset = 0;
2160    }
2161    if pos == ringbuffer_size {
2162      break;
2163    }
2164  }
2165  (pos - orig_pos) as i32
2166}
2167
2168#[cfg(all(test, feature="std"))]
2169mod tests {
2170  use super::*;
2171
2172  // StandardAlloc for u8 cells, except that requests of at least `fail_at`
2173  // bytes fail and `short` hands out one byte less than asked. Records every
2174  // request and counts the cells handed out and taken back.
2175  struct CountingAlloc {
2176    fail_at: usize,
2177    short: bool,
2178    requests: std::vec::Vec<usize>,
2179    allocated: usize,
2180    freed: usize,
2181  }
2182
2183  impl Default for CountingAlloc {
2184    fn default() -> Self {
2185      CountingAlloc {
2186        fail_at: usize::MAX,
2187        short: false,
2188        requests: std::vec::Vec::new(),
2189        allocated: 0,
2190        freed: 0,
2191      }
2192    }
2193  }
2194
2195  impl Allocator<u8> for CountingAlloc {
2196    type AllocatedMemory = <::StandardAlloc as Allocator<u8>>::AllocatedMemory;
2197    fn alloc_cell(&mut self, len: usize) -> Self::AllocatedMemory {
2198      self.requests.push(len);
2199      if len >= self.fail_at {
2200        return Self::AllocatedMemory::default();
2201      }
2202      let len = if self.short && len != 0 { len - 1 } else { len };
2203      if len != 0 {
2204        self.allocated += 1;
2205      }
2206      ::StandardAlloc::default().alloc_cell(len)
2207    }
2208    fn free_cell(&mut self, data: Self::AllocatedMemory) {
2209      if data.slice().len() != 0 {
2210        self.freed += 1;
2211      }
2212    }
2213  }
2214
2215  type CountingState = BrotliState<CountingAlloc, ::StandardAlloc, ::StandardAlloc>;
2216
2217  fn counting_state(window_bits: u32) -> CountingState {
2218    let mut s = BrotliState::new(CountingAlloc::default(),
2219                                 ::StandardAlloc::default(),
2220                                 ::StandardAlloc::default());
2221    s.window_bits = window_bits;
2222    s
2223  }
2224
2225  // What BrotliDecompressStream does for a metablock of `mlen` bytes: size the
2226  // ring buffer at the header, then allocate before writing to it.
2227  fn start_metablock(s: &mut CountingState, mlen: i32) -> BrotliDecoderErrorCode {
2228    s.meta_block_remaining_len = mlen;
2229    BrotliCalculateRingBufferSize(s, &[]);
2230    BrotliEnsureRingBuffer(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2)
2231  }
2232
2233  // Stands in for decoding the metablock: writes its `mlen` bytes after `pos`.
2234  fn finish_metablock(s: &mut CountingState) {
2235    let (pos, mlen) = (s.pos as usize, s.meta_block_remaining_len as usize);
2236    for (i, byte) in s.ringbuffer.slice_mut()[pos..pos + mlen].iter_mut().enumerate() {
2237      *byte = ((pos + i) % 251) as u8 + 1;
2238    }
2239    s.pos += s.meta_block_remaining_len;
2240    s.meta_block_remaining_len = 0;
2241  }
2242
2243  fn assert_holds_decoded_bytes(s: &CountingState) {
2244    let ringbuffer = s.ringbuffer.slice();
2245    for i in 0..s.pos as usize {
2246      assert_eq!(ringbuffer[i], (i % 251) as u8 + 1, "byte {}", i);
2247    }
2248  }
2249
2250  fn assert_success(result: BrotliDecoderErrorCode) {
2251    assert_eq!(result as i32, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS as i32);
2252  }
2253
2254  fn assert_ring_buffer(s: &CountingState, size: i32) {
2255    assert_eq!(s.ringbuffer_size, size);
2256    assert_eq!(s.ringbuffer_mask, size - 1);
2257    assert_eq!(s.new_ringbuffer_size, size);
2258    assert_eq!(s.ringbuffer.slice().len(), size as usize + kRingBufferAllocationSlack);
2259  }
2260
2261  #[test]
2262  fn ring_buffer_starts_small_and_grows_on_demand() {
2263    let mut s = counting_state(22);
2264    assert_success(start_metablock(&mut s, 10));
2265    assert_ring_buffer(&s, 1024);
2266    // The context bytes of the first two positions read the zeroed tail.
2267    assert_eq!(&s.ringbuffer.slice()[1022..1024], &[0, 0]);
2268    finish_metablock(&mut s);
2269    // A metablock that exactly fits the rest of the ring buffer reuses it.
2270    assert_success(start_metablock(&mut s, 1014));
2271    assert_ring_buffer(&s, 1024);
2272    finish_metablock(&mut s);
2273    assert_eq!(s.alloc_u8.allocated, 1);
2274    // One byte more than fits doubles it, keeping everything decoded so far.
2275    assert_success(start_metablock(&mut s, 1));
2276    assert_ring_buffer(&s, 2048);
2277    assert_holds_decoded_bytes(&s);
2278    assert_eq!(&s.ringbuffer.slice()[2046..2048], &[0, 0]);
2279    finish_metablock(&mut s);
2280    // It grows straight to the smallest power of two that fits.
2281    assert_success(start_metablock(&mut s, 5000));
2282    assert_ring_buffer(&s, 8192);
2283    assert_holds_decoded_bytes(&s);
2284    finish_metablock(&mut s);
2285    // No larger than the window...
2286    assert_success(start_metablock(&mut s, 3 << 20));
2287    assert_ring_buffer(&s, 1 << 22);
2288    assert_holds_decoded_bytes(&s);
2289    finish_metablock(&mut s);
2290    // ...which is final: later metablocks wrap it instead.
2291    assert_success(start_metablock(&mut s, 3 << 20));
2292    assert_ring_buffer(&s, 1 << 22);
2293    let slack = kRingBufferAllocationSlack;
2294    assert_eq!(s.alloc_u8.requests,
2295               [1024 + slack, 2048 + slack, 8192 + slack, (1 << 22) + slack]);
2296    // Each growth handed the previous ring buffer back.
2297    assert_eq!(s.alloc_u8.allocated, 4);
2298    assert_eq!(s.alloc_u8.freed, 3);
2299  }
2300
2301  #[test]
2302  fn ring_buffer_growth_jumps_to_the_window_from_a_quarter_of_it() {
2303    // With a 4 MiB window, a regrowth that would reach 2 MiB allocates the
2304    // window instead, so the ring buffer is allocated twice rather than three
2305    // times for a stream of more than 1 MiB.
2306    let mut s = counting_state(22);
2307    assert_success(start_metablock(&mut s, 1 << 20));
2308    assert_ring_buffer(&s, 1 << 20);
2309    finish_metablock(&mut s);
2310    assert_success(start_metablock(&mut s, 1));
2311    assert_ring_buffer(&s, 1 << 22);
2312    assert_holds_decoded_bytes(&s);
2313    let slack = kRingBufferAllocationSlack;
2314    assert_eq!(s.alloc_u8.requests, [(1 << 20) + slack, (1 << 22) + slack]);
2315
2316    // Below a quarter of the window it grows one power of two at a time.
2317    let mut s = counting_state(22);
2318    assert_success(start_metablock(&mut s, 1 << 19));
2319    finish_metablock(&mut s);
2320    assert_success(start_metablock(&mut s, 1));
2321    assert_ring_buffer(&s, 1 << 20);
2322
2323    // The first allocation is sized for its metablock, however large.
2324    let mut s = counting_state(22);
2325    assert_success(start_metablock(&mut s, 1 << 21));
2326    assert_ring_buffer(&s, 1 << 21);
2327
2328    // A last metablock gets just what it needs: nothing follows it.
2329    let mut s = counting_state(22);
2330    assert_success(start_metablock(&mut s, 1 << 20));
2331    finish_metablock(&mut s);
2332    s.is_last_metablock = 1;
2333    assert_success(start_metablock(&mut s, 1));
2334    assert_ring_buffer(&s, 1 << 21);
2335  }
2336
2337  #[test]
2338  fn ring_buffer_sizing_matches_the_c_decoder() {
2339    let first_size = |window_bits: u32, mlen: i32, canny: bool, is_last: bool| {
2340      let mut s = counting_state(window_bits);
2341      s.canny_ringbuffer_allocation = canny;
2342      s.is_last_metablock = is_last as u8;
2343      assert_success(start_metablock(&mut s, mlen));
2344      s.ringbuffer_size
2345    };
2346    // A short first metablock gets 1 KiB whatever the window, even when it is
2347    // not the last one (which used to allocate the whole window).
2348    assert_eq!(first_size(16, 1, true, false), 1024);
2349    assert_eq!(first_size(24, 1024, true, false), 1024);
2350    assert_eq!(first_size(30, 1, true, false), 1024);
2351    assert_eq!(first_size(24, 1025, true, false), 2048);
2352    assert_eq!(first_size(16, 1 << 24, true, false), 1 << 16);
2353    // The smallest window is the smallest ring buffer.
2354    assert_eq!(first_size(10, 1, true, false), 1024);
2355    // BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: always the window.
2356    assert_eq!(first_size(16, 1, false, false), 1 << 16);
2357    assert_eq!(first_size(24, 1, false, false), 1 << 24);
2358    assert_eq!(first_size(24, 1, false, true), 1 << 24);
2359    // The one departure from C: the ring buffer never grows after the last
2360    // metablock, so if that is the first to need it, it may be under 1 KiB.
2361    assert_eq!(first_size(22, 1, true, true), 32);
2362    assert_eq!(first_size(10, 17, true, true), 32);
2363    assert_eq!(first_size(22, 40, true, true), 64);
2364    assert_eq!(first_size(22, 513, true, true), 1024);
2365    assert_eq!(first_size(22, 1025, true, true), 2048);
2366
2367    // Metadata does not touch the ring buffer.
2368    let mut s = counting_state(22);
2369    s.is_metadata = 1;
2370    s.meta_block_remaining_len = 100;
2371    BrotliCalculateRingBufferSize(&mut s, &[]);
2372    assert_eq!(s.new_ringbuffer_size, 0);
2373    assert!(s.alloc_u8.requests.is_empty());
2374  }
2375
2376  // With a fixed u8 pool, the ring buffer never needs more of the pool than
2377  // before growth on demand, when the whole window came at once for any
2378  // metablock but the last one, and a last one got as little as 32 bytes.
2379  #[test]
2380  fn fixed_pool_ring_buffer_needs_no_more_than_before_growth() {
2381    let slack = kRingBufferAllocationSlack;
2382    let window = 1usize << 16;
2383    // A pool that holds the whole window gets it at once...
2384    let mut s = counting_state(16);
2385    s.u8_pool_size = window + slack;
2386    assert_success(start_metablock(&mut s, 10));
2387    assert_ring_buffer(&s, window as i32);
2388    assert_eq!(&s.ringbuffer.slice()[window - 2..window], &[0, 0]);
2389    finish_metablock(&mut s);
2390    assert_success(start_metablock(&mut s, 50000));
2391    assert_ring_buffer(&s, window as i32);
2392    assert_eq!(s.alloc_u8.requests, [window + slack]);
2393    // ...unless the metablock is the last one.
2394    let mut s = counting_state(16);
2395    s.u8_pool_size = window + slack;
2396    s.is_last_metablock = 1;
2397    assert_success(start_metablock(&mut s, 40));
2398    assert_ring_buffer(&s, 64);
2399    // A smaller pool could not hold the whole window, so the ring buffer
2400    // grows, starting from 32 bytes rather than 1 KiB.
2401    let mut s = counting_state(16);
2402    s.u8_pool_size = window + slack - 1;
2403    assert_success(start_metablock(&mut s, 1));
2404    assert_ring_buffer(&s, 32);
2405    finish_metablock(&mut s);
2406    assert_success(start_metablock(&mut s, 100));
2407    assert_ring_buffer(&s, 128);
2408    assert_holds_decoded_bytes(&s);
2409    finish_metablock(&mut s);
2410    assert_success(start_metablock(&mut s, 40000));
2411    assert_ring_buffer(&s, window as i32);
2412    assert_holds_decoded_bytes(&s);
2413    assert_eq!(s.alloc_u8.requests, [32 + slack, 128 + slack, window + slack]);
2414    assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (3, 2));
2415    // BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION still wins.
2416    let mut s = counting_state(16);
2417    s.u8_pool_size = 1;
2418    s.canny_ringbuffer_allocation = false;
2419    s.is_last_metablock = 1;
2420    assert_success(start_metablock(&mut s, 1));
2421    assert_ring_buffer(&s, window as i32);
2422  }
2423
2424  #[test]
2425  fn failed_ring_buffer_growth_keeps_the_current_one() {
2426    let mut s = counting_state(24);
2427    s.alloc_u8.fail_at = 1 << 20;
2428    assert_success(start_metablock(&mut s, 700));
2429    finish_metablock(&mut s);
2430    // Needs a 4 MiB ring buffer, which the allocator refuses.
2431    assert_eq!(start_metablock(&mut s, 3 << 20) as i32,
2432               BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2 as i32);
2433    assert_eq!(s.ringbuffer_size, 1024);
2434    assert_eq!(s.ringbuffer_mask, 1023);
2435    assert_eq!(s.ringbuffer.slice().len(), 1024 + kRingBufferAllocationSlack);
2436    assert_eq!(s.pos, 700);
2437    assert_holds_decoded_bytes(&s);
2438    assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (1, 0));
2439    // Nothing was lost, so once memory is available the growth goes through.
2440    s.alloc_u8.fail_at = usize::MAX;
2441    assert_success(BrotliEnsureRingBuffer(
2442      &mut s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2));
2443    assert_ring_buffer(&s, 4 << 20);
2444    assert_holds_decoded_bytes(&s);
2445    assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (2, 1));
2446  }
2447
2448  #[test]
2449  fn short_ring_buffer_allocation_is_returned_and_reported() {
2450    let mut s = counting_state(22);
2451    s.alloc_u8.short = true;
2452    assert_eq!(start_metablock(&mut s, 10) as i32,
2453               BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2 as i32);
2454    assert_eq!(s.ringbuffer.slice().len(), 0);
2455    assert_eq!(s.ringbuffer_size, 0);
2456    assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (1, 1));
2457  }
2458
2459  #[test]
2460  fn ensure_ring_buffer_rejects_states_the_decoder_cannot_produce() {
2461    let unreachable = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE as i32;
2462    let ensure = |s: &mut CountingState| {
2463      BrotliEnsureRingBuffer(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1)
2464        as i32
2465    };
2466    let mut s = counting_state(16);
2467    // No size was calculated.
2468    assert_eq!(ensure(&mut s), unreachable);
2469    // Not a power of two.
2470    s.new_ringbuffer_size = 1000;
2471    assert_eq!(ensure(&mut s), unreachable);
2472    // Decoded bytes that would not fit, or that were never allocated.
2473    s.new_ringbuffer_size = 1024;
2474    s.pos = 1025;
2475    assert_eq!(ensure(&mut s), unreachable);
2476    s.pos = 1;
2477    assert_eq!(ensure(&mut s), unreachable);
2478    s.pos = -1;
2479    assert_eq!(ensure(&mut s), unreachable);
2480    // A ring buffer that has wrapped can no longer be moved.
2481    s.pos = 0;
2482    s.rb_roundtrips = 1;
2483    assert_eq!(ensure(&mut s), unreachable);
2484    assert!(s.alloc_u8.requests.is_empty());
2485    s.rb_roundtrips = 0;
2486    assert_eq!(ensure(&mut s), BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS as i32);
2487  }
2488
2489  // Packs fields least significant bit first, as brotli streams are laid out.
2490  struct BitWriter {
2491    bytes: std::vec::Vec<u8>,
2492    bits: usize,
2493  }
2494
2495  impl BitWriter {
2496    fn put(&mut self, count: usize, value: u32) {
2497      for i in 0..count {
2498        if self.bits % 8 == 0 {
2499          self.bytes.push(0);
2500        }
2501        let last = self.bytes.len() - 1;
2502        self.bytes[last] |= (((value >> i) & 1) as u8) << (self.bits % 8);
2503        self.bits += 1;
2504      }
2505    }
2506
2507    // Uncompressed data starts at the next byte boundary.
2508    fn raw(&mut self, data: &[u8]) {
2509      self.bytes.extend_from_slice(data);
2510      self.bits = self.bytes.len() * 8;
2511    }
2512  }
2513
2514  // A stream with a 64 KiB window of uncompressed metablocks of the given
2515  // lengths, then an empty last one; and the pseudo-random data it holds.
2516  fn uncompressed_stream(lengths: &[usize]) -> (std::vec::Vec<u8>, std::vec::Vec<u8>) {
2517    let mut writer = BitWriter { bytes: std::vec::Vec::new(), bits: 0 };
2518    writer.put(1, 0); // WBITS=16
2519    let mut data = std::vec::Vec::new();
2520    let mut seed = 1u32;
2521    for &length in lengths {
2522      let block: std::vec::Vec<u8> = (0..length).map(|_| {
2523        seed = seed.wrapping_mul(1103515245).wrapping_add(12345);
2524        (seed >> 16) as u8
2525      }).collect();
2526      // ISLAST=0, MNIBBLES=4, MLEN-1, ISUNCOMPRESSED=1.
2527      writer.put(1, 0);
2528      writer.put(2, 0);
2529      writer.put(16, length as u32 - 1);
2530      writer.put(1, 1);
2531      writer.raw(&block);
2532      data.extend_from_slice(&block);
2533    }
2534    writer.put(2, 3); // ISLAST=1, ISLASTEMPTY=1
2535    (writer.bytes, data)
2536  }
2537
2538  // Hands the decoder at most in_chunk bytes of input and out_chunk bytes of
2539  // output space per call.
2540  fn decode_in_chunks(s: &mut CountingState, input: &[u8], in_chunk: usize, out_chunk: usize)
2541                      -> std::vec::Vec<u8> {
2542    let mut output = std::vec::Vec::new();
2543    let mut buffer = vec![0u8; core::cmp::min(out_chunk, 1 << 20)];
2544    let mut input_offset = 0;
2545    loop {
2546      let mut available_in = core::cmp::min(in_chunk, input.len() - input_offset);
2547      let mut available_out = buffer.len();
2548      let mut output_offset = 0;
2549      let mut total_out = 0;
2550      let result = BrotliDecompressStream(&mut available_in, &mut input_offset, input,
2551                                          &mut available_out, &mut output_offset, &mut buffer,
2552                                          &mut total_out, s);
2553      output.extend_from_slice(&buffer[..output_offset]);
2554      match result {
2555        BrotliResult::ResultSuccess => return output,
2556        BrotliResult::NeedsMoreInput => assert!(input_offset < input.len(), "truncated"),
2557        BrotliResult::NeedsMoreOutput => {}
2558        BrotliResult::ResultFailure => panic!("decoding failed: {:?}", s.error_code),
2559      }
2560    }
2561  }
2562
2563  #[test]
2564  fn ring_buffer_grows_across_metablocks_then_wraps() {
2565    // 10 + 1000 bytes fit in 1 KiB; 2510 need 4 KiB and 5510 need 8 KiB;
2566    // 35510 need the whole 64 KiB window, which the rest then wraps around.
2567    let (input, expected) = uncompressed_stream(&[10, 1000, 1500, 3000, 30000, 40000, 5000]);
2568    let slack = kRingBufferAllocationSlack;
2569    for &(in_chunk, out_chunk) in &[(usize::MAX, usize::MAX), (1, 1), (1, 4099), (4099, 1),
2570                                     (333, 777)] {
2571      let mut s = counting_state(0);
2572      let output = decode_in_chunks(&mut s, &input, in_chunk, out_chunk);
2573      assert!(output == expected, "chunks of {} and {}", in_chunk, out_chunk);
2574      assert_eq!(s.alloc_u8.requests, [1024 + slack, 4096 + slack, 8192 + slack, 65536 + slack]);
2575      assert_eq!((s.alloc_u8.allocated, s.alloc_u8.freed), (4, 3));
2576    }
2577  }
2578
2579  #[test]
2580  fn set_parameter_disables_growth_only_before_decoding() {
2581    use state::BrotliDecoderParameter::{BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION,
2582                                        BROTLI_DECODER_PARAM_LARGE_WINDOW};
2583    let (input, expected) = uncompressed_stream(&[10, 1000, 1500, 3000, 30000, 40000, 5000]);
2584    let mut s = counting_state(0);
2585    assert!(s.set_parameter(BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION, 1));
2586    assert!(decode_in_chunks(&mut s, &input, usize::MAX, usize::MAX) == expected);
2587    // The whole window at once, where the stream above grows to it in four.
2588    assert_eq!(s.alloc_u8.requests, [65536 + kRingBufferAllocationSlack]);
2589    // Once decoding has started, nothing changes.
2590    let large_window = s.large_window;
2591    for &value in &[0, 1] {
2592      assert!(!s.set_parameter(BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION, value));
2593      assert!(!s.set_parameter(BROTLI_DECODER_PARAM_LARGE_WINDOW, value));
2594    }
2595    assert!(!s.canny_ringbuffer_allocation);
2596    assert_eq!(s.large_window, large_window);
2597  }
2598
2599  #[test]
2600  fn initial_ring_buffer_size_sets_the_first_ring_buffer() {
2601    let first_size = |initial: u32, mlen: i32, is_last: bool| {
2602      let mut s = counting_state(22);
2603      assert!(s.set_initial_ring_buffer_size(initial));
2604      s.is_last_metablock = is_last as u8;
2605      assert_success(start_metablock(&mut s, mlen));
2606      s.ringbuffer_size
2607    };
2608    assert_eq!(first_size(0, 10, false), 1024);
2609    // Rounded up to a power of two of at least 32 bytes...
2610    assert_eq!(first_size(4096, 10, false), 4096);
2611    assert_eq!(first_size(5000, 10, false), 8192);
2612    assert_eq!(first_size(1, 10, false), 32);
2613    // ...that still holds the metablock...
2614    assert_eq!(first_size(4096, 5000, false), 8192);
2615    // ...and is no larger than the window.
2616    assert_eq!(first_size(u32::MAX, 10, false), 1 << 22);
2617    // A last metablock is sized to fit, as the ring buffer never grows after it.
2618    assert_eq!(first_size(u32::MAX, 10, true), 32);
2619    // Disabling reallocation still allocates the whole window.
2620    let mut s = counting_state(22);
2621    assert!(s.set_initial_ring_buffer_size(4096));
2622    s.canny_ringbuffer_allocation = false;
2623    assert_success(start_metablock(&mut s, 10));
2624    assert_eq!(s.ringbuffer_size, 1 << 22);
2625  }
2626
2627  #[test]
2628  fn one_shot_output_hint_grows_in_bounded_steps() {
2629    let mut tiny = counting_state(22);
2630    tiny.one_shot_output_size = 1 << 20;
2631    assert_success(start_metablock(&mut tiny, 16));
2632    assert_ring_buffer(&tiny, 1024);
2633
2634    let mut small = counting_state(22);
2635    small.one_shot_output_size = 1 << 20;
2636    assert_success(start_metablock(&mut small, 300));
2637    assert_ring_buffer(&small, 2048);
2638
2639    let mut s = counting_state(22);
2640    s.one_shot_output_size = 1 << 20;
2641    let slack = kRingBufferAllocationSlack;
2642
2643    assert_success(start_metablock(&mut s, 10));
2644    assert_ring_buffer(&s, 1024);
2645    finish_metablock(&mut s);
2646
2647    // At 64 KiB of decoded output, jump fourfold instead of taking every
2648    // intermediate power of two on the way to the caller's output capacity.
2649    assert_success(start_metablock(&mut s, (64 << 10) - 10));
2650    assert_ring_buffer(&s, 256 << 10);
2651    assert_holds_decoded_bytes(&s);
2652    finish_metablock(&mut s);
2653
2654    assert_success(start_metablock(&mut s, 192 << 10));
2655    assert_ring_buffer(&s, 1 << 20);
2656    assert_holds_decoded_bytes(&s);
2657    assert_eq!(s.alloc_u8.requests, [1024 + slack, (256 << 10) + slack,
2658                                     (1 << 20) + slack]);
2659
2660    // Even with a much larger output buffer and a large window, a short
2661    // stream cannot force the full output capacity into the first ring.
2662    let mut oversized = counting_state(30);
2663    oversized.one_shot_output_size = 1 << 30;
2664    assert_success(start_metablock(&mut oversized, 10));
2665    assert_ring_buffer(&oversized, 1024);
2666    finish_metablock(&mut oversized);
2667    assert_success(start_metablock(&mut oversized, (64 << 10) - 10));
2668    assert_ring_buffer(&oversized, 256 << 10);
2669  }
2670
2671  #[test]
2672  fn initial_ring_buffer_size_is_only_set_before_decoding() {
2673    let (input, expected) = uncompressed_stream(&[10, 1000, 1500, 3000, 30000, 40000, 5000]);
2674    let mut s = counting_state(0);
2675    assert!(s.set_initial_ring_buffer_size(4096));
2676    assert!(s.set_initial_ring_buffer_size(u32::MAX));
2677    // One byte starts decoding the stream header, before any ring buffer...
2678    let (mut available_in, mut input_offset) = (1, 0);
2679    let (mut available_out, mut output_offset, mut total_out) = (0, 0, 0);
2680    match BrotliDecompressStream(&mut available_in, &mut input_offset, &input,
2681                                 &mut available_out, &mut output_offset, &mut [],
2682                                 &mut total_out, &mut s) {
2683      BrotliResult::NeedsMoreInput => {}
2684      _ => panic!("expected NeedsMoreInput"),
2685    }
2686    assert!(s.alloc_u8.requests.is_empty());
2687    // ...after which the size no longer changes.
2688    assert!(!s.set_initial_ring_buffer_size(0));
2689    assert!(decode_in_chunks(&mut s, &input[1..], 333, 777) == expected);
2690    // The whole window at once, where by default this stream grows to it in
2691    // four allocations (see ring_buffer_grows_across_metablocks_then_wraps).
2692    assert_eq!(s.alloc_u8.requests, [65536 + kRingBufferAllocationSlack]);
2693  }
2694
2695  // Encoders store small or incompressible input as an uncompressed metablock
2696  // and an empty last one. When the decoder can see the empty one, it sizes the
2697  // ring buffer for the uncompressed one as for a last metablock.
2698  #[test]
2699  fn uncompressed_metablock_before_an_empty_last_one_is_sized_to_fit() {
2700    let (input, expected) = uncompressed_stream(&[10]);
2701    let requests = |initial: u32, canny: bool, in_chunk: usize| {
2702      let mut s = counting_state(0);
2703      assert!(s.set_initial_ring_buffer_size(initial));
2704      s.canny_ringbuffer_allocation = canny;
2705      assert!(decode_in_chunks(&mut s, &input, in_chunk, usize::MAX) == expected);
2706      s.alloc_u8.requests.clone()
2707    };
2708    let slack = kRingBufferAllocationSlack;
2709    // With the empty last metablock in the input, whatever the initial size...
2710    assert_eq!(requests(0, true, usize::MAX), [32 + slack]);
2711    assert_eq!(requests(u32::MAX, true, usize::MAX), [32 + slack]);
2712    // ...though disabling reallocation still takes the whole window.
2713    assert_eq!(requests(0, false, usize::MAX), [65536 + slack]);
2714    // One byte at a time, the uncompressed metablock is sized as not last.
2715    assert_eq!(requests(0, true, 1), [1024 + slack]);
2716    assert_eq!(requests(u32::MAX, true, 1), [65536 + slack]);
2717  }
2718
2719  #[test]
2720  fn take_output_returns_every_consumed_byte() {
2721    // The existing 10x10y stream, embedded so this regression needs no fixture.
2722    let input = [0x1b, 0x13, 0x00, 0x00, 0xa4, 0xb0, 0xb2, 0xea, 0x81, 0x47, 0x02, 0x8a];
2723    let expected = b"XXXXXXXXXXYYYYYYYYYY";
2724    let mut state = BrotliState::new(::StandardAlloc::default(),
2725                                     ::StandardAlloc::default(),
2726                                     ::StandardAlloc::default());
2727    let mut available_in = input.len();
2728    let mut input_offset = 0usize;
2729    let mut available_out = 0usize;
2730    let mut output_offset = 0usize;
2731    let mut total_out = 0usize;
2732    let result = BrotliDecompressStream(&mut available_in, &mut input_offset, &input,
2733                                        &mut available_out, &mut output_offset, &mut [],
2734                                        &mut total_out, &mut state);
2735    assert_eq!(result as i32, BrotliResult::NeedsMoreOutput as i32);
2736    assert_eq!(total_out, 0);
2737
2738    let mut consumed = 0usize;
2739    for &limit in &[1usize, 3, 7, 0] {
2740      assert!(BrotliDecoderHasMoreOutput(&state));
2741      let mut size = limit;
2742      {
2743        let output = BrotliDecoderTakeOutput(&mut state, &mut size);
2744        assert_eq!(size, if limit == 0 { expected.len() - consumed } else { limit });
2745        assert_eq!(output.len(), size);
2746        assert_eq!(output, &expected[consumed..consumed + size]);
2747      }
2748      consumed += size;
2749      assert_eq!(state.partial_pos_out, consumed as u64);
2750    }
2751    assert_eq!(consumed, expected.len());
2752    assert!(!BrotliDecoderHasMoreOutput(&state));
2753    for &limit in &[1usize, 0] {
2754      let mut size = limit;
2755      assert!(BrotliDecoderTakeOutput(&mut state, &mut size).is_empty());
2756      assert_eq!(size, 0);
2757    }
2758  }
2759
2760  fn assert_large_remaining_copy_is_clamped(meta_block_remaining_len: i32,
2761                                            pos: i32,
2762                                            expected_result: BrotliDecoderErrorCode) {
2763    let mut s = BrotliState::new(::StandardAlloc::default(),
2764                                 ::StandardAlloc::default(),
2765                                 ::StandardAlloc::default());
2766    s.ringbuffer_size = 16;
2767    s.new_ringbuffer_size = 16;
2768    s.window_bits = 5;
2769    s.ringbuffer = s.alloc_u8.alloc_cell(s.ringbuffer_size as usize);
2770    s.meta_block_remaining_len = meta_block_remaining_len;
2771    s.pos = pos;
2772    s.br.avail_in = 1u32 << 31;
2773
2774    let input = [0x5au8];
2775    let mut available_out = 0usize;
2776    let mut output = [0u8; 0];
2777    let mut output_offset = 0usize;
2778    let mut total_out = 0usize;
2779    let result = CopyUncompressedBlockToOutput(&mut available_out,
2780                                               &mut output,
2781                                               &mut output_offset,
2782                                               &mut total_out,
2783                                               &mut s,
2784                                               &input);
2785
2786    assert_eq!(result as i32, expected_result as i32);
2787    assert_eq!(s.br.avail_in, (1u32 << 31) - 1);
2788    assert_eq!(s.meta_block_remaining_len, meta_block_remaining_len - 1);
2789    assert_eq!(s.pos, pos + 1);
2790    assert_eq!(s.ringbuffer.slice()[pos as usize], input[0]);
2791  }
2792
2793  #[test]
2794  fn uncompressed_copy_clamps_unsigned_remaining_bytes() {
2795    assert_large_remaining_copy_is_clamped(
2796      1, 0, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS);
2797    assert_large_remaining_copy_is_clamped(
2798      16, 15, BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT);
2799  }
2800
2801  #[test]
2802  fn stream_rejects_wrapping_output_range() {
2803    let mut state = BrotliState::new(::StandardAlloc::default(),
2804                                     ::StandardAlloc::default(),
2805                                     ::StandardAlloc::default());
2806    let input = [0x06u8];
2807    let mut output = [0u8; 1];
2808    let mut available_in = input.len();
2809    let mut input_offset = 0usize;
2810    let mut available_out = usize::MAX;
2811    let mut output_offset = 1usize;
2812    let mut total_out = 0usize;
2813
2814    let result = BrotliDecompressStream(&mut available_in,
2815                                        &mut input_offset,
2816                                        &input,
2817                                        &mut available_out,
2818                                        &mut output_offset,
2819                                        &mut output,
2820                                        &mut total_out,
2821                                        &mut state);
2822
2823    assert_eq!(result as i32, BrotliResult::ResultFailure as i32);
2824    assert_eq!(state.error_code as i32,
2825               BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS as i32);
2826  }
2827
2828  #[test]
2829  fn stream_rejects_wrapping_input_range() {
2830    let mut state = BrotliState::new(::StandardAlloc::default(),
2831                                     ::StandardAlloc::default(),
2832                                     ::StandardAlloc::default());
2833    let input = [0x06u8];
2834    let mut output = [0u8; 1];
2835    // The end wraps to zero on 32-bit and is out of bounds on 64-bit.
2836    let mut available_in = u32::MAX as usize;
2837    let mut input_offset = 1usize;
2838    let mut available_out = output.len();
2839    let mut output_offset = 0usize;
2840    let mut total_out = 0usize;
2841
2842    let result = BrotliDecompressStream(&mut available_in,
2843                                        &mut input_offset,
2844                                        &input,
2845                                        &mut available_out,
2846                                        &mut output_offset,
2847                                        &mut output,
2848                                        &mut total_out,
2849                                        &mut state);
2850
2851    assert_eq!(result as i32, BrotliResult::ResultFailure as i32);
2852    assert_eq!(state.error_code as i32,
2853               BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS as i32);
2854  }
2855
2856  #[test]
2857  fn format_distance_error_restores_huffman_tree_groups() {
2858    let mut state = BrotliState::new(::StandardAlloc::default(),
2859                                     ::StandardAlloc::default(),
2860                                     ::StandardAlloc::default());
2861    // The alphabets the decoder uses, so the groups have the room the
2862    // command loop's table windows expect.
2863    state.BrotliHuffmanTreeGroupInit(state::WhichTreeGroup::LITERAL,
2864                                     kNumLiteralCodes, kNumLiteralCodes, 1);
2865    state.BrotliHuffmanTreeGroupInit(state::WhichTreeGroup::INSERT_COPY,
2866                                     kNumInsertAndCopyCodes, kNumInsertAndCopyCodes, 2);
2867    state.BrotliHuffmanTreeGroupInit(state::WhichTreeGroup::DISTANCE, 64, 64, 3);
2868    let expected_code_lengths = [
2869      state.literal_hgroup.codes.slice().len(),
2870      state.insert_copy_hgroup.codes.slice().len(),
2871      state.distance_hgroup.codes.slice().len(),
2872    ];
2873
2874    state.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2875    state.distance_code = 1;
2876    state.dist_rb_idx = 1;
2877    state.dist_rb[0] = i32::MAX;
2878    state.max_distance = 0;
2879    state.max_backward_distance = 0;
2880
2881    let result = SafeProcessCommands(&mut state, &[], &[]);
2882
2883    assert_eq!(result as i32,
2884               BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE as i32);
2885    assert_eq!(state.literal_hgroup.codes.slice().len(), expected_code_lengths[0]);
2886    assert_eq!(state.insert_copy_hgroup.codes.slice().len(), expected_code_lengths[1]);
2887    assert_eq!(state.distance_hgroup.codes.slice().len(), expected_code_lengths[2]);
2888  }
2889}
2890
2891// The table for decoding context maps, needed only by metablocks with more
2892// than one tree in a group.
2893fn EnsureContextMapTable<AllocU8: alloc::Allocator<u8>,
2894                         AllocU32: alloc::Allocator<u32>,
2895                         AllocHC: alloc::Allocator<HuffmanCode>>
2896  (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
2897   -> bool {
2898  if s.context_map_table.slice().len() == 0 {
2899    s.context_map_table = s.alloc_hc.alloc_cell(huffman::BROTLI_HUFFMAN_MAX_SIZE_272 as usize);
2900  }
2901  s.context_map_table.slice().len() != 0
2902}
2903
2904// Allocates the context-map table, block-type trees, and block-length trees
2905// unless they are already allocated. Returns false if an allocation fails.
2906// Callers invoke this before freeing/growing any reusable metablock buffer so
2907// fixed pool allocators never see an allocation after a free.
2908fn EnsureBlockTrees<AllocU8: alloc::Allocator<u8>,
2909                    AllocU32: alloc::Allocator<u32>,
2910                    AllocHC: alloc::Allocator<HuffmanCode>>
2911  (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
2912   -> bool {
2913  if !EnsureContextMapTable(s) {
2914    return false;
2915  }
2916  if s.block_type_length_state.block_type_trees.slice().len() == 0 {
2917    s.block_type_length_state.block_type_trees =
2918      s.alloc_hc.alloc_cell(3 * huffman::BROTLI_HUFFMAN_MAX_SIZE_258 as usize);
2919    if s.block_type_length_state.block_type_trees.slice().len() == 0 {
2920      return false;
2921    }
2922  }
2923  if s.block_type_length_state.block_len_trees.slice().len() == 0 {
2924    s.block_type_length_state.block_len_trees =
2925      s.alloc_hc.alloc_cell(3 * huffman::BROTLI_HUFFMAN_MAX_SIZE_26 as usize);
2926    if s.block_type_length_state.block_len_trees.slice().len() == 0 {
2927      return false;
2928    }
2929  }
2930  true
2931}
2932
2933// Reads 1..256 2-bit context modes.
2934pub fn ReadContextModes<AllocU8: alloc::Allocator<u8>,
2935                        AllocU32: alloc::Allocator<u32>,
2936                        AllocHC: alloc::Allocator<HuffmanCode>>
2937  (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2938   input: &[u8])
2939   -> BrotliDecoderErrorCode {
2940
2941  let mut i: i32 = s.loop_counter;
2942
2943  for context_mode_iter in fast_mut!((s.context_modes.slice_mut())[i as usize ;
2944                                                       (s.block_type_length_state.num_block_types[0]
2945                                                        as usize)])
2946    .iter_mut() {
2947    let mut bits: u32 = 0;
2948    if (!bit_reader::BrotliSafeReadBits(&mut s.br, 2, &mut bits, input)) {
2949      mark_unlikely();
2950      s.loop_counter = i;
2951      return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2952    }
2953    *context_mode_iter = bits as u8;
2954    BROTLI_LOG_UINT!(i);
2955    i += 1;
2956  }
2957  BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS
2958}
2959
2960#[inline(always)]
2961fn TakeDistanceFromRingBuffer(
2962  distance_code: &mut i32,
2963  dist_rb_idx: &mut i32,
2964  dist_rb: &[i32; 4],
2965  distance_context: &mut i32,
2966) {
2967  if *distance_code == 0 {
2968    *dist_rb_idx -= 1;
2969    *distance_code = fast!((dist_rb)[(*dist_rb_idx & 3) as usize]);
2970    *distance_context = 1;
2971  } else {
2972    let dcode = *distance_code << 1;
2973    // kDistanceShortCodeIndexOffset has 2-bit values from LSB:
2974    // 3, 2, 1, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2
2975    const kDistanceShortCodeIndexOffset: u32 = 0xaaafff1b;
2976    // kDistanceShortCodeValueOffset has 2-bit values from LSB:
2977    // -0, 0,-0, 0,-1, 1,-2, 2,-3, 3,-1, 1,-2, 2,-3, 3
2978    const kDistanceShortCodeValueOffset: u32 = 0xfa5fa500;
2979    let mut v = (*dist_rb_idx + (kDistanceShortCodeIndexOffset as i32 >> dcode)) & 0x3;
2980    *distance_code = fast!((dist_rb)[v as usize]);
2981    v = (kDistanceShortCodeValueOffset >> dcode) as i32 & 0x3;
2982    if (dcode & 0x3) != 0 {
2983      *distance_code += v;
2984    } else {
2985      *distance_code -= v;
2986      if *distance_code <= 0 {
2987        // A huge distance will cause a BROTLI_FAILURE() soon.
2988        // This is a little faster than failing here.
2989        *distance_code = 0x7fffffff;
2990      }
2991    }
2992  }
2993}
2994
2995pub fn SafeReadBits(br: &mut bit_reader::BrotliBitReader,
2996                    n_bits: u32,
2997                    val: &mut u32,
2998                    input: &[u8])
2999                    -> bool {
3000  if (n_bits != 0) {
3001    bit_reader::BrotliSafeReadBits(br, n_bits, val, input)
3002  } else {
3003    *val = 0;
3004    true
3005  }
3006}
3007
3008// Selects a command loop flavour at compile time. Associated consts rather than
3009// const generics: const generics need Rust 1.51.
3010trait CommandLoopMode {
3011  const SAFE: bool;
3012}
3013struct FastCommandLoop;
3014struct SafeCommandLoop;
3015impl CommandLoopMode for FastCommandLoop { const SAFE: bool = false; }
3016impl CommandLoopMode for SafeCommandLoop { const SAFE: bool = true; }
3017
3018// Cold second-level distance Huffman lookup (`table_element.bits > 8`).
3019// Outlined so the common 8-bit root lookup in `read_distance` needs only the
3020// thin `&DistanceRootTable` pointer and never loads `distance_hgroup` or
3021// `dist_context_map` from `BrotliState` unless `root.bits > 8`.
3022#[cold]
3023#[inline(never)]
3024fn decode_distance_subtable<
3025  AllocU32: alloc::Allocator<u32>,
3026  AllocHC: alloc::Allocator<HuffmanCode>,
3027>(
3028  bits: u32,
3029  table_index: usize,
3030  root: HuffmanCode,
3031  distance_hgroup: &HuffmanTreeGroup<AllocU32, AllocHC>,
3032  dist_context_map: &[u8],
3033  dist_context_map_slice_index: usize,
3034  distance_context: i32,
3035) -> (usize, u32) {
3036  let tree_idx = dist_context_map
3037    .get(dist_context_map_slice_index + (distance_context as usize & 3))
3038    .copied()
3039    .unwrap_or(0) as usize;
3040  let distance_tree = huffman_tree(distance_hgroup, tree_idx);
3041  let sub_idx = table_index
3042    + root.value as usize
3043    + (((bits & bit_reader::BitMask(root.bits as u32)) >> HUFFMAN_TABLE_BITS) as usize);
3044  let sub = distance_tree.entry(sub_idx);
3045  (sub.value as usize, HUFFMAN_TABLE_BITS + (sub.bits as u32 & 7))
3046}
3047
3048// Converts the decoded distance symbol `code` to `*distance_code`, reading its
3049// extra bits. Precondition: *distance_code < 0. `memento` is the reader state
3050// from before the symbol was read; only the safe path uses it, to roll back
3051// when the extra bits are not all available yet (the fast path passes a
3052// default state).
3053#[inline(always)]
3054fn read_distance<M: CommandLoopMode>(
3055  code: usize,
3056  memento: &bit_reader::BrotliBitReaderState,
3057  fbr: &mut bit_reader::BitReaderSlice,
3058  br: &mut bit_reader::BrotliBitReader,
3059  input: &[u8],
3060  distance_code: &mut i32,
3061  distance_context: &mut i32,
3062  dist_rb_idx: &mut i32,
3063  dist_rb: &[i32; 4],
3064  block_len_2: &mut u32,
3065  distance_postfix_bits: u32,
3066  distance_postfix_mask: i32,
3067  num_direct_distance_codes: u32,
3068) -> bool {
3069  if (code & !0xfusize) == 0 {
3070    *distance_code = code as i32;
3071    *distance_context = 0;
3072    TakeDistanceFromRingBuffer(distance_code, dist_rb_idx, dist_rb, distance_context);
3073    *block_len_2 -= 1;
3074    return true;
3075  }
3076  if !M::SAFE {
3077    if distance_postfix_bits == 0 {
3078      // NPOSTFIX == 0 (every metablock below q10, and many at q10-q11):
3079      // `checked_sub` handles direct codes (`16 <= code < ndirect`) and codes
3080      // with extra bits (`code >= ndirect`) with one comparison, in 32-bit
3081      // arithmetic (identical in the low 32 bits for the at most 30-bit extra
3082      // distances the alphabet limit allows).
3083      let ndirect = num_direct_distance_codes;
3084      let code = code as u32;
3085      *distance_code = match code.checked_sub(ndirect) {
3086        Some(distval) => {
3087          let nbits = (distval >> 1) + 1;
3088          let bits = fbr.read_bits(nbits);
3089          ((2 + (distval & 1)).wrapping_shl(nbits))
3090            .wrapping_add(ndirect)
3091            .wrapping_sub(4 + NUM_DISTANCE_SHORT_CODES as u32 - 1)
3092            .wrapping_add(bits) as i32
3093        }
3094        None => code.wrapping_sub(NUM_DISTANCE_SHORT_CODES as u32 - 1) as i32,
3095      };
3096    } else {
3097      // NPOSTFIX > 0 (primarily q10-q11, where NDIRECT is also often non-zero):
3098      // branchless decode avoids ~1.5M branch mispredictions on mixed direct /
3099      // extra-bit distance streams such as `wiki-Brotli.html` q11. When
3100      // `code < num_direct`, `distval < 0`, `mask == 0`, and `nbits == 0`, so
3101      // `read_bits(0)` consumes 0 bits and returns 0 while the masked formula
3102      // reduces to `code - 15`.
3103      let num_direct = num_direct_distance_codes as i32;
3104      let distval = code as i32 - num_direct;
3105      let mask = !(distval >> 31) as u32;
3106      let d = (distval as u32) & mask;
3107      let postfix_bits = distance_postfix_bits & 3;
3108      let postfix = d & (distance_postfix_mask as u32);
3109      let hcode = d >> postfix_bits;
3110      let nbits = ((hcode >> 1) + 1) & mask;
3111      let bits = fbr.read_bits(nbits);
3112      let offset = (((2u32 + (hcode & 1)).wrapping_shl(nbits)).wrapping_sub(4)) & mask;
3113      *distance_code = ((offset.wrapping_add(bits).wrapping_shl(postfix_bits))
3114        .wrapping_add(postfix) & mask)
3115        .wrapping_add((code as u32) & !mask)
3116        .wrapping_add((num_direct as u32) & mask)
3117        .wrapping_sub(NUM_DISTANCE_SHORT_CODES as u32 - 1) as i32;
3118    }
3119    *distance_context = 0;
3120    *block_len_2 -= 1;
3121    return true;
3122  }
3123  let num_direct = num_direct_distance_codes as usize;
3124  if code < num_direct {
3125    *distance_code = (code - (NUM_DISTANCE_SHORT_CODES as usize - 1)) as i32;
3126    *distance_context = 0;
3127    *block_len_2 -= 1;
3128    return true;
3129  }
3130  let distval = (code - num_direct) as u32;
3131  let postfix_bits = distance_postfix_bits & 3;
3132  let postfix = distval & (distance_postfix_mask as u32);
3133  let hcode = distval >> postfix_bits;
3134  let nbits = (hcode >> 1) + 1;
3135  if nbits > 29 {
3136    *distance_code = 0x7fffffff;
3137    *distance_context = 0;
3138    *block_len_2 -= 1;
3139    return true;
3140  }
3141  let mut bits: u32 = 0;
3142  if !SafeReadBits(br, nbits, &mut bits, input) {
3143    bit_reader::BrotliBitReaderRestoreState(br, memento);
3144    return false;
3145  }
3146  #[cfg(target_pointer_width = "64")]
3147  {
3148    let offset = ((2u64 + (hcode & 1) as u64) << (nbits & 63)).wrapping_sub(4);
3149    *distance_code = ((offset.wrapping_add(bits as u64) << postfix_bits)
3150      .wrapping_add(postfix as u64)
3151      .wrapping_add(num_direct as u64) as i32)
3152      .wrapping_sub(NUM_DISTANCE_SHORT_CODES as i32)
3153      .wrapping_add(1);
3154  }
3155  // 64-bit shifts are multi-instruction sequences on 32-bit targets; the low
3156  // 32 bits, all that the `i32` result keeps, are the same in u32.
3157  #[cfg(not(target_pointer_width = "64"))]
3158  {
3159    let offset = (2u32 + (hcode & 1)).wrapping_shl(nbits).wrapping_sub(4);
3160    *distance_code = (offset.wrapping_add(bits).wrapping_shl(postfix_bits)
3161      .wrapping_add(postfix)
3162      .wrapping_add(num_direct as u32) as i32)
3163      .wrapping_sub(NUM_DISTANCE_SHORT_CODES as i32)
3164      .wrapping_add(1);
3165  }
3166  *distance_context = 0;
3167  *block_len_2 -= 1;
3168  true
3169}
3170
3171#[inline(always)]
3172fn read_command<M: CommandLoopMode>(
3173  fbr: &mut bit_reader::BitReaderSlice,
3174  br: &mut bit_reader::BrotliBitReader,
3175  input: &[u8],
3176  distance_code: &mut i32,
3177  distance_context: &mut i32,
3178  copy_len_out: &mut i32,
3179  block_len_1: &mut u32,
3180  insert_length: &mut i32,
3181  insert_copy_tree: &InsertCopyTable,
3182) -> bool {
3183  let memento = if M::SAFE {
3184    bit_reader::BrotliBitReaderSaveState(br)
3185  } else {
3186    bit_reader::BrotliBitReaderState::default()
3187  };
3188  let cmd_code = if !M::SAFE {
3189    *block_len_1 -= 1;
3190    read_symbol_slice(fbr, insert_copy_tree) as usize
3191  } else {
3192    let mut sym: u32 = 0;
3193    if !SafeReadSymbol(insert_copy_tree, br, &mut sym, input) {
3194      return false;
3195    }
3196    sym as usize
3197  };
3198  // `kCmdLut` is padded to 1024 entries, so masking (a single bit-field
3199  // clear) replaces a compare and branch; valid insert-and-copy codes are
3200  // below 704.
3201  let v = &prefix::kCmdLut[cmd_code & 1023];
3202  *distance_code = v.distance_code as i32;
3203  *distance_context = v.context as i32;
3204  if !M::SAFE {
3205    let mut insert_len = v.insert_len_offset as i32;
3206    if v.insert_len_extra_bits != 0 {
3207      mark_unlikely();
3208      insert_len += fbr.read_bits(v.insert_len_extra_bits as u32) as i32;
3209    }
3210    let copy_offset = v.copy_len_offset as i32;
3211    let copy_extra = fbr.read_bits(v.copy_len_extra_bits as u32) as i32;
3212    *insert_length = insert_len;
3213    *copy_len_out = copy_offset + copy_extra;
3214  } else {
3215    let mut insert_len = v.insert_len_offset as i32;
3216    let insert_extra_bits = v.insert_len_extra_bits as u32;
3217    if insert_extra_bits != 0 {
3218      let mut bits = 0u32;
3219      if !bit_reader::BrotliSafeReadBits(br, insert_extra_bits, &mut bits, input) {
3220        bit_reader::BrotliBitReaderRestoreState(br, &memento);
3221        return false;
3222      }
3223      insert_len += bits as i32;
3224    }
3225    let copy_extra_bits = v.copy_len_extra_bits as u32;
3226    let mut copy_bits = 0u32;
3227    if !SafeReadBits(br, copy_extra_bits, &mut copy_bits, input) {
3228      bit_reader::BrotliBitReaderRestoreState(br, &memento);
3229      return false;
3230    }
3231    *insert_length = insert_len;
3232    *copy_len_out = v.copy_len_offset as i32 + copy_bits as i32;
3233    *block_len_1 -= 1;
3234  }
3235  true
3236}
3237
3238
3239#[inline(always)]
3240fn WarmupBitReader(safe: bool, br: &mut bit_reader::BrotliBitReader, input: &[u8]) -> bool {
3241  safe || bit_reader::BrotliWarmupBitReader(br, input)
3242}
3243
3244#[inline(always)]
3245fn CheckInputAmount(safe: bool, br: &bit_reader::BrotliBitReader, num: u32) -> bool {
3246  safe || bit_reader::BrotliCheckInputAmount(br, num)
3247}
3248
3249// Copies 16 bytes `[0..16]` in the ring buffer while checking `<= len - 32` up
3250// front (the ring buffer always carries `kRingBufferAllocationSlack = 566 >= 32`
3251// bytes past `ringbuffer_size`). Using the exact same `len < 32 || max > len - 32`
3252// guard as `memmove16_offset16` lets LLVM GVN eliminate the second bounds check
3253// on the `17 <= copy_len <= 32` path and kills `max(off_dst, off_src)` before
3254// the copy, reducing register pressure in `ProcessCommands`.
3255#[inline(always)]
3256fn memmove16_from_ringbuffer(data: &mut [u8], u32off_dst: u32, u32off_src: u32) -> bool {
3257  let off_dst = u32off_dst as usize;
3258  let off_src = u32off_src as usize;
3259  let len = data.len();
3260  if len < 32 || core::cmp::max(off_dst, off_src) > len - 32 {
3261    return false;
3262  }
3263  #[cfg(target_pointer_width = "64")]
3264  {
3265    let dst_end = off_dst + 16;
3266    let src_end = off_src + 16;
3267    let mut local_array: [u8; 16] = fast_uninitialized!(16);
3268    local_array.clone_from_slice(&data[off_src..src_end]);
3269    data[off_dst..dst_end].clone_from_slice(&local_array);
3270    true
3271  }
3272  // On 32-bit targets (ARMv7), `clone_from_slice` on a 16-byte range emits
3273  // panicking slice bounds checks; matching a 16-element slice prefix lowers
3274  // to a single unaligned NEON `vld1.8`/`vst1.8` pair with no panic path.
3275  #[cfg(not(target_pointer_width = "64"))]
3276  {
3277    let local_array: [u8; 16] = match data.get(off_src..) {
3278      Some(&[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, ..]) => {
3279        [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15]
3280      }
3281      _ => return false,
3282    };
3283    match data.get_mut(off_dst..) {
3284      Some([d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, ..]) => {
3285        *d0 = local_array[0];
3286        *d1 = local_array[1];
3287        *d2 = local_array[2];
3288        *d3 = local_array[3];
3289        *d4 = local_array[4];
3290        *d5 = local_array[5];
3291        *d6 = local_array[6];
3292        *d7 = local_array[7];
3293        *d8 = local_array[8];
3294        *d9 = local_array[9];
3295        *d10 = local_array[10];
3296        *d11 = local_array[11];
3297        *d12 = local_array[12];
3298        *d13 = local_array[13];
3299        *d14 = local_array[14];
3300        *d15 = local_array[15];
3301        true
3302      }
3303      _ => false,
3304    }
3305  }
3306}
3307
3308// Copies bytes `[16..32]` relative to `u32off_src`/`u32off_dst` by matching a
3309// 32-byte slice prefix at `off_src`/`off_dst` rather than computing `off + 16`
3310// up front. This lets LLVM reuse the `&data[off_src]`/`&mut data[off_dst]`
3311// base pointers from the preceding `memmove16_from_ringbuffer` with an immediate `#16` offset
3312// instead of hoisting `dst_start + 16`/`src_start + 16` across `copy_len > 32`.
3313#[inline(always)]
3314fn memmove16_offset16(data: &mut [u8], u32off_dst: u32, u32off_src: u32) -> bool {
3315  let off_dst = u32off_dst as usize;
3316  let off_src = u32off_src as usize;
3317  let len = data.len();
3318  if len < 32 || core::cmp::max(off_dst, off_src) > len - 32 {
3319    return false;
3320  }
3321  #[cfg(target_pointer_width = "64")]
3322  {
3323    let mut local_array: [u8; 16] = fast_uninitialized!(16);
3324    local_array.clone_from_slice(&data[off_src + 16..off_src + 32]);
3325    data[off_dst + 16..off_dst + 32].clone_from_slice(&local_array);
3326    true
3327  }
3328  #[cfg(not(target_pointer_width = "64"))]
3329  {
3330    let local_array: [u8; 16] = match data.get(off_src..) {
3331      Some(
3332        &[
3333          _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,
3334          a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,
3335          ..,
3336        ],
3337      ) => [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15],
3338      _ => return false,
3339    };
3340    match data.get_mut(off_dst..) {
3341      Some(
3342        [
3343          _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,
3344          d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15,
3345          ..,
3346        ],
3347      ) => {
3348        *d0 = local_array[0];
3349        *d1 = local_array[1];
3350        *d2 = local_array[2];
3351        *d3 = local_array[3];
3352        *d4 = local_array[4];
3353        *d5 = local_array[5];
3354        *d6 = local_array[6];
3355        *d7 = local_array[7];
3356        *d8 = local_array[8];
3357        *d9 = local_array[9];
3358        *d10 = local_array[10];
3359        *d11 = local_array[11];
3360        *d12 = local_array[12];
3361        *d13 = local_array[13];
3362        *d14 = local_array[14];
3363        *d15 = local_array[15];
3364        true
3365      }
3366      _ => false,
3367    }
3368  }
3369}
3370
3371#[inline(always)]
3372fn copy_overlapping_backreference(data: &mut [u8], dst: usize, distance: usize,
3373                                 size: usize) -> bool {
3374  if distance == 0 || distance > dst || dst > data.len() || size > data.len() - dst {
3375    return false;
3376  }
3377  let seed = core::cmp::min(distance, size);
3378  data.copy_within(dst - distance..dst - distance + seed, dst);
3379  let mut copied = seed;
3380  while copied < size {
3381    let step = core::cmp::min(copied, size - copied);
3382    data.copy_within(dst..dst + step, dst + copied);
3383    copied += step;
3384  }
3385  true
3386}
3387
3388#[cfg_attr(target_pointer_width = "64", inline(always))]
3389#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3390fn memcpy_within_slice(data: &mut [u8], off_dst: usize, off_src: usize, size: usize) -> bool {
3391  // Both ranges must fit and must not overlap: the `unsafe` build lowers this to
3392  // copy_nonoverlapping, and the safe build's split_at_mut would panic.
3393  // Subtraction, not `off + size`, so no caller offset can wrap past the checks.
3394  let len = data.len();
3395  let apart = if off_dst > off_src { off_dst - off_src } else { off_src - off_dst };
3396  if size > len || off_dst > len - size || off_src > len - size || apart < size {
3397    return false;
3398  }
3399
3400  #[cfg(not(feature="unsafe"))]
3401  {
3402    if off_dst > off_src {
3403      let (src, dst) = data.split_at_mut(off_dst);
3404      let src_slice = fast!((src)[off_src ; off_src + size]);
3405      fast_mut!((dst)[0;size]).clone_from_slice(src_slice);
3406    } else {
3407      let (dst, src) = data.split_at_mut(off_src);
3408      let src_slice = fast!((src)[0;size]);
3409      fast_mut!((dst)[off_dst;off_dst + size]).clone_from_slice(src_slice);
3410    }
3411  }
3412
3413  #[cfg(feature="unsafe")]
3414  unsafe {
3415    let ptr = data.as_mut_ptr();
3416    let dst = ptr.add(off_dst);
3417    let src = ptr.add(off_src);
3418    core::ptr::copy_nonoverlapping(src, dst, size);
3419  }
3420  true
3421}
3422
3423pub fn BrotliDecoderHasMoreOutput<AllocU8: alloc::Allocator<u8>,
3424                           AllocU32: alloc::Allocator<u32>,
3425                           AllocHC: alloc::Allocator<HuffmanCode>>
3426  (s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
3427  /* After unrecoverable error remaining output is considered nonsensical. */
3428  if is_fatal(s.error_code) {
3429    return false;
3430  }
3431  s.ringbuffer.len() != 0 && CheckRingBufferConsistency(s) && UnwrittenBytes(s, false) != 0
3432}
3433pub fn BrotliDecoderTakeOutput<'a,
3434                               AllocU8: alloc::Allocator<u8>,
3435                               AllocU32: alloc::Allocator<u32>,
3436                               AllocHC: alloc::Allocator<HuffmanCode>>(
3437  s: &'a mut BrotliState<AllocU8, AllocU32, AllocHC>,
3438  size: &mut usize,
3439) -> &'a [u8] {
3440  let one:usize = 1;
3441  let mut available_out = if *size != 0 { *size } else { one << 24 };
3442  let requested_out = available_out;
3443  if (s.ringbuffer.len() == 0) || is_fatal(s.error_code) {
3444    *size = 0;
3445    return &[];
3446  }
3447  if !WrapRingBuffer(s) {
3448    s.error_code = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3449    *size = 0;
3450    return &[];
3451  }
3452  let mut ign = 0usize;
3453  let mut ign2 = 0usize;
3454  let (status, result) = WriteRingBuffer(&mut available_out, None, &mut ign,&mut ign2, true, s);
3455  // Either WriteRingBuffer returns those "success" codes...
3456  match status {
3457    BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS |  BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT => {
3458      *size = requested_out - available_out;
3459    },
3460    _ => {
3461      // ... or stream is broken. Normally this should be caught by
3462      //   BrotliDecoderDecompressStream, this is just a safeguard.
3463      if is_fatal(status) {
3464        // SaveErrorCode!(s, status); //borrow checker doesn't like this
3465        // but since it's a safeguard--ignore
3466      }
3467      *size = 0;
3468      return &[];
3469    }
3470  }
3471  return result;
3472}
3473
3474#[cfg(feature="ffi-api")]
3475pub fn BrotliDecoderIsUsed<AllocU8: alloc::Allocator<u8>,
3476                           AllocU32: alloc::Allocator<u32>,
3477                           AllocHC: alloc::Allocator<HuffmanCode>>(
3478  s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
3479  !matches!(s.state, BrotliRunningState::BROTLI_STATE_UNINITED)
3480    || bit_reader::BrotliGetAvailableBits(&s.br) != 0
3481}
3482
3483pub fn BrotliDecoderIsFinished<AllocU8: alloc::Allocator<u8>,
3484                               AllocU32: alloc::Allocator<u32>,
3485                               AllocHC: alloc::Allocator<HuffmanCode>>(
3486  s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
3487  if let BrotliRunningState::BROTLI_STATE_DONE = s.state {
3488    !BrotliDecoderHasMoreOutput(s)
3489  } else {
3490    false
3491  }
3492}
3493
3494pub fn BrotliDecoderGetErrorCode<AllocU8: alloc::Allocator<u8>,
3495                               AllocU32: alloc::Allocator<u32>,
3496                               AllocHC: alloc::Allocator<HuffmanCode>>(
3497  s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> BrotliDecoderErrorCode {
3498  s.error_code
3499}
3500
3501// The tree with the given index in a Huffman tree group, as
3502// HuffmanTreeGroup::build_hgroup_cache lists them; empty if there is none.
3503#[inline(always)]
3504fn huffman_tree<AllocU32: alloc::Allocator<u32>, AllocHC: alloc::Allocator<HuffmanCode>>(
3505  group: &HuffmanTreeGroup<AllocU32, AllocHC>,
3506  index: usize,
3507) -> &[HuffmanCode] {
3508  match group.htrees.slice().get(index) {
3509    Some(offset) => group.codes.slice().get(*offset as usize..).unwrap_or(&[]),
3510    None => &[],
3511  }
3512}
3513
3514// As huffman_tree, as a fixed window (see huffman::HuffmanTable).
3515// Outlined on 32-bit targets so LLVM LICM does not hoist `&group.codes` and
3516// `&EMPTY_TABLE` out of cold block-switch paths into `ProcessCommands`'s
3517// loop preheader.
3518#[cfg_attr(target_pointer_width = "64", inline(always))]
3519#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3520fn huffman_window<AllocU32: alloc::Allocator<u32>, AllocHC: alloc::Allocator<HuffmanCode>,
3521                  T: huffman::TableWindow>(
3522  group: &HuffmanTreeGroup<AllocU32, AllocHC>,
3523  index: usize,
3524) -> &T {
3525  let offset = group.htrees.slice().get(index).map(|o| *o as usize);
3526  huffman::table_window(group.codes.slice(), offset)
3527}
3528
3529type LiteralTable = [HuffmanCode; LITERAL_TABLE_WINDOW];
3530type InsertCopyTable = [HuffmanCode; INSERT_COPY_TABLE_WINDOW];
3531type DistanceRootTable = [HuffmanCode; DISTANCE_ROOT_WINDOW];
3532
3533// The 256-entry root tables of the 4 distance contexts at `slice_index` in the
3534// distance context map, sharing the lookup when contexts use the same tree
3535// (all 4 do below q10). Thin `&DistanceRootTable` pointers avoid carrying a
3536// fat-slice length register and per-symbol bounds check in `read_distance`.
3537#[cfg_attr(target_pointer_width = "64", inline(always))]
3538#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3539fn load_distance_roots<'a, AllocU32: alloc::Allocator<u32>, AllocHC: alloc::Allocator<HuffmanCode>>(
3540  group: &'a HuffmanTreeGroup<AllocU32, AllocHC>,
3541  map: &[u8],
3542  slice_index: usize,
3543) -> [&'a DistanceRootTable; 4] {
3544  let idx: [u8; 4] = match map.get(slice_index..).and_then(|m| m.get(..4)) {
3545    Some(m) => [m[0], m[1], m[2], m[3]],
3546    None => return EMPTY_DISTANCE_ROOTS,
3547  };
3548  let htrees = group.htrees.slice();
3549  let codes = group.codes.slice();
3550  let t0: &DistanceRootTable =
3551    huffman::table_window(codes, htrees.get(idx[0] as usize).map(|&o| o as usize));
3552  let t1 = if idx[1] == idx[0] {
3553    t0
3554  } else {
3555    huffman::table_window(codes, htrees.get(idx[1] as usize).map(|&o| o as usize))
3556  };
3557  let t2 = if idx[2] == idx[1] {
3558    t1
3559  } else if idx[2] == idx[0] {
3560    t0
3561  } else {
3562    huffman::table_window(codes, htrees.get(idx[2] as usize).map(|&o| o as usize))
3563  };
3564  let t3 = if idx[3] == idx[2] {
3565    t2
3566  } else if idx[3] == idx[1] {
3567    t1
3568  } else if idx[3] == idx[0] {
3569    t0
3570  } else {
3571    huffman::table_window(codes, htrees.get(idx[3] as usize).map(|&o| o as usize))
3572  };
3573  [t0, t1, t2, t3]
3574}
3575
3576// Fills `trees[context]` with the literal tree of each of the 64 contexts of
3577// the literal block type whose context map starts at `context_map[slice_index]`.
3578#[inline(never)]
3579fn fill_context_trees<'a, AllocU32: alloc::Allocator<u32>, AllocHC: alloc::Allocator<HuffmanCode>>(
3580  trees: &mut [&'a LiteralTable; 64],
3581  group: &'a HuffmanTreeGroup<AllocU32, AllocHC>,
3582  context_map: &[u8],
3583  slice_index: usize,
3584) {
3585  match context_map.get(slice_index..).and_then(|map| map.get(..64)) {
3586    Some(map) => {
3587      // Context maps are RLE-encoded and typically contain long runs of
3588      // identical tree indices; reuse the resolved table reference across
3589      // adjacent equal entries.
3590      let htrees = group.htrees.slice();
3591      let codes = group.codes.slice();
3592      let mut prev_index = usize::MAX;
3593      let mut prev_tree: &'a LiteralTable = &EMPTY_LITERAL_TABLE;
3594      for (tree, &index) in trees.iter_mut().zip(map.iter()) {
3595        let idx = index as usize;
3596        if idx != prev_index {
3597          prev_index = idx;
3598          prev_tree = huffman::table_window(codes, htrees.get(idx).map(|&o| o as usize));
3599        }
3600        *tree = prev_tree;
3601      }
3602    }
3603    None => *trees = EMPTY_CONTEXT_TREES,
3604  }
3605}
3606
3607// Takes `fbr` by value and returns it (like `decode_literal_batch`) so
3608// outlining on 32-bit targets does not force `fbr` into a stack `alloca` in
3609// `ProcessCommands`.
3610#[cfg_attr(target_pointer_width = "64", inline(always))]
3611#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3612fn decode_block_type_and_length_slice<'a, AllocHC: alloc::Allocator<HuffmanCode>>(
3613  btl: &mut BlockTypeAndLengthState<AllocHC>,
3614  mut fbr: bit_reader::BitReaderSlice<'a>,
3615  tree_type: i32,
3616) -> (bit_reader::BitReaderSlice<'a>, BrotliDecoderErrorCode) {
3617  // A reader over the remaining input, in the same bit layout as the slice.
3618  let mut temp_br = bit_reader::BrotliBitReader {
3619    val_: fbr.val,
3620    bit_pos_: fbr.avail_bits,
3621    next_in: 0,
3622    avail_in: fbr.rem.len() as u32,
3623  };
3624  let status = DecodeBlockTypeAndLength(false, btl, &mut temp_br, tree_type, fbr.rem);
3625  fbr.val = temp_br.val_;
3626  fbr.avail_bits = temp_br.bit_pos_;
3627  fbr.rem = &fbr.rem[temp_br.next_in as usize..];
3628  (fbr, status)
3629}
3630
3631#[derive(Clone, Copy)]
3632enum LiteralBatchStatus {
3633  Decoded,
3634  NotHandled,
3635  CorruptInput,
3636}
3637
3638#[inline(always)]
3639fn decode_literal_batch<'b>(
3640  rb: &mut [u8],
3641  pos: usize,
3642  count: usize,
3643  trivial_literal_context: i32,
3644  literal_htree: &LiteralTable,
3645  context_trees: &[&LiteralTable; 64],
3646  context_lookup: &[u8; 512],
3647  mut fbr: bit_reader::BitReaderSlice<'b>,
3648) -> (bit_reader::BitReaderSlice<'b>, LiteralBatchStatus) {
3649  if trivial_literal_context != 0 {
3650    let ring_window = match rb.get_mut(pos..).and_then(|w| w.get_mut(..count)) {
3651      Some(w) => w,
3652      None => return (fbr, LiteralBatchStatus::NotHandled),
3653    };
3654    for dst in ring_window.iter_mut() {
3655      if !fbr.fill16_checked() {
3656        mark_unlikely();
3657        return (fbr, LiteralBatchStatus::CorruptInput);
3658      }
3659      *dst = decode_symbol_no_fill(&mut fbr, literal_htree) as u8;
3660    }
3661    (fbr, LiteralBatchStatus::Decoded)
3662  } else {
3663    let start = pos.wrapping_sub(2);
3664    let len = count + 2;
3665    let (p2_init, p1_init, ring_window) =
3666      match rb.get_mut(start..).and_then(|w| w.get_mut(..len)) {
3667        Some([p2_init, p1_init, ring_window @ ..]) => (p2_init, p1_init, ring_window),
3668        _ => return (fbr, LiteralBatchStatus::NotHandled),
3669      };
3670    let mut p1: u8 = *p1_init;
3671    let mut p2: u8 = *p2_init;
3672    for dst in ring_window.iter_mut() {
3673      if !fbr.fill16_checked() {
3674        mark_unlikely();
3675        return (fbr, LiteralBatchStatus::CorruptInput);
3676      }
3677      let context = (context_lookup[p1 as usize] | context_lookup[(p2 as usize) | 256]) as usize;
3678      let hc = context_trees[context & 63];
3679      p2 = p1;
3680      p1 = decode_symbol_no_fill(&mut fbr, hc) as u8;
3681      *dst = p1;
3682    }
3683    (fbr, LiteralBatchStatus::Decoded)
3684  }
3685}
3686
3687#[cold]
3688#[inline(never)]
3689fn execute_custom_shared_dictionary_copy<AllocU8: alloc::Allocator<u8>, AllocU32: alloc::Allocator<u32>>(
3690  shared_dict: &::shared_dictionary::BrotliSharedDictionary<AllocU8, AllocU32>,
3691  context_lookup: &[u8; 512],
3692  dist_rb_idx: &mut i32,
3693  meta_block_remaining_len: &mut i32,
3694  mut pos: i32,
3695  rb: &mut [u8],
3696  rb_size: i32,
3697  rb_mask: i32,
3698  distance_code: i32,
3699  max_distance: i32,
3700  distance_context: i32,
3701  copy_len: i32,
3702  compound_dictionary_size: u32,
3703) -> Result<(i32, bool), BrotliDecoderErrorCode> {
3704  let dict_id = if shared_dict.context_based {
3705    let p1 = rb[(pos.wrapping_sub(1) as usize) & (rb_mask as usize)];
3706    let p2 = rb[(pos.wrapping_sub(2) as usize) & (rb_mask as usize)];
3707    let context = (context_lookup[p1 as usize] | context_lookup[p2 as usize | 256]) as usize;
3708    shared_dict.context_map[context]
3709  } else {
3710    0
3711  };
3712  let address = distance_code - max_distance - 1 - compound_dictionary_size as i32;
3713  *dist_rb_idx += distance_context;
3714  let lookup = shared_dict.lookup(dict_id, copy_len, address).map_err(|why| match why {
3715    DictionaryLookupError::LengthNotEncodable =>
3716      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DICTIONARY,
3717    DictionaryLookupError::AddressOutOfRange =>
3718      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM,
3719  })?;
3720  let mut len = copy_len;
3721  let word = lookup.words.word(len, lookup.word_idx);
3722  if lookup.transform_idx == lookup.transforms.cutoff_identity() {
3723    rb[pos as usize..(pos + len) as usize].clone_from_slice(word);
3724  } else {
3725    len = lookup.transforms.apply(&mut rb[pos as usize..], word, len, lookup.transform_idx);
3726    if len == 0 && distance_code <= 120 {
3727      return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
3728    }
3729  }
3730  pos += len;
3731  *meta_block_remaining_len -= len;
3732  Ok((pos, pos >= rb_size))
3733}
3734
3735// Executes a compound, custom shared, or static dictionary reference when
3736// `distance_code > max_distance`. Returns `Ok((new_pos, post_write_1))`.
3737#[inline(always)]
3738fn execute_dictionary_copy<AllocU8: alloc::Allocator<u8>, AllocU32: alloc::Allocator<u32>>(
3739  compound_dictionary: &mut state::BrotliDecoderCompoundDictionary<AllocU8>,
3740  shared_dict: &::shared_dictionary::BrotliSharedDictionary<AllocU8, AllocU32>,
3741  context_lookup: &[u8; 512],
3742  dist_rb: &mut [i32; 4],
3743  dist_rb_idx: &mut i32,
3744  meta_block_remaining_len: &mut i32,
3745  mut pos: i32,
3746  rb: &mut [u8],
3747  rb_size: i32,
3748  rb_mask: i32,
3749  distance_code: i32,
3750  max_distance: i32,
3751  distance_context: i32,
3752  copy_len: i32,
3753  external_dictionary: &[u8],
3754) -> Result<(i32, bool), BrotliDecoderErrorCode> {
3755  if distance_code > kBrotliMaxAllowedDistance as i32 {
3756    return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE);
3757  }
3758  let compound_dictionary_size = compound_dictionary.total_size as u32;
3759  // Distances in (max_distance, max_distance + compound_dictionary_size]
3760  // address the attached compound dictionary, furthest byte first.
3761  if (distance_code - max_distance) as u32 <= compound_dictionary_size {
3762    let address = compound_dictionary_size - (distance_code - max_distance) as u32;
3763    let address = address as usize;
3764    let length = copy_len as usize;
3765    // A dictionary of one chunk (the common case: one attached raw
3766    // dictionary) whose copy ends before the ring buffer does is a plain
3767    // slice copy, without the chunked block-map walk.
3768    if compound_dictionary.num_chunks == 1 && ((rb_size - pos) as usize) > length {
3769      if length > compound_dictionary.total_size - address {
3770        return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY);
3771      }
3772      let chunk = match compound_dictionary.chunks[0] {
3773        state::MaybeOwnedSlice::External(_) => external_dictionary,
3774        ref chunk => chunk.slice(),
3775      };
3776      let (dst, src) = match (rb.get_mut(pos as usize..pos as usize + length),
3777                              chunk.get(address..address + length)) {
3778        (Some(dst), Some(src)) => (dst, src),
3779        _ => return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY),
3780      };
3781      dist_rb[(*dist_rb_idx & 3) as usize] = distance_code;
3782      *dist_rb_idx += 1;
3783      *meta_block_remaining_len -= copy_len;
3784      copy_bytes(dst, src);
3785      return Ok((pos + copy_len, false));
3786    }
3787    if !InitializeCompoundDictionaryCopy(compound_dictionary, address, length) {
3788      return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY);
3789    }
3790    dist_rb[(*dist_rb_idx & 3) as usize] = distance_code;
3791    *dist_rb_idx += 1;
3792    *meta_block_remaining_len -= copy_len;
3793    pos += CopyFromCompoundDictionary(compound_dictionary, rb, rb_size, pos, external_dictionary);
3794    return Ok((pos, pos >= rb_size));
3795  }
3796  if shared_dict.is_custom()
3797    && copy_len >= SHARED_BROTLI_MIN_DICTIONARY_WORD_LENGTH as i32
3798    && copy_len <= SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH as i32
3799  {
3800    return execute_custom_shared_dictionary_copy(
3801      shared_dict,
3802      context_lookup,
3803      dist_rb_idx,
3804      meta_block_remaining_len,
3805      pos,
3806      rb,
3807      rb_size,
3808      rb_mask,
3809      distance_code,
3810      max_distance,
3811      distance_context,
3812      copy_len,
3813      compound_dictionary_size,
3814    );
3815  }
3816  if copy_len >= kBrotliMinDictionaryWordLength as i32
3817    && copy_len <= kBrotliMaxDictionaryWordLength as i32
3818  {
3819    let mut offset = fast!((kBrotliDictionaryOffsetsByLength)[copy_len as usize]) as i32;
3820    let word_id = distance_code - max_distance - 1 - compound_dictionary_size as i32;
3821    let shift = fast!((kBrotliDictionarySizeBitsByLength)[copy_len as usize]);
3822    let mask = bit_reader::BitMask(shift as u32) as i32;
3823    let word_idx = word_id & mask;
3824    let transform_idx = word_id >> shift;
3825    *dist_rb_idx += distance_context;
3826    offset += word_idx * copy_len;
3827    if transform_idx >= kNumTransforms {
3828      return Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
3829    }
3830    let mut len = copy_len;
3831    let word = fast!((kBrotliDictionary)[offset as usize ; (offset + len) as usize]);
3832    if transform_idx == 0 {
3833      copy_bytes(&mut rb[pos as usize..(pos + len) as usize], word);
3834    } else {
3835      len = TransformDictionaryWord(&mut rb[pos as usize..], word, len, transform_idx);
3836    }
3837    pos += len;
3838    *meta_block_remaining_len -= len;
3839    return Ok((pos, pos >= rb_size));
3840  }
3841  Err(BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DICTIONARY)
3842}
3843
3844// Copies `rem` bytes from `pos - distance_code` (modulo `rb_mask`) into `rb`,
3845// stopping early and returning `(new_pos, new_rem, true)` if `pos` reaches `rb_size`.
3846#[cfg_attr(target_pointer_width = "64", inline(always))]
3847#[cfg_attr(not(target_pointer_width = "64"), inline(never))]
3848fn copy_wrap_or_overlapping(
3849  rb: &mut [u8],
3850  rb_size: i32,
3851  rb_mask: i32,
3852  mut pos: i32,
3853  mut rem: i32,
3854  distance_code: i32,
3855) -> (i32, i32, bool) {
3856  let rb_mask_usize = (rb_mask as usize) & 0x7fff_ffff;
3857  if rb.len() <= rb_mask_usize {
3858    return (pos, rem, false);
3859  }
3860  let mut wrap_guard = rb_size - pos;
3861  if rem >= 16 && pos >= 0 && wrap_guard > 0 && distance_code > 0 && distance_code <= pos {
3862    let count = core::cmp::min(rem, wrap_guard);
3863    if copy_overlapping_backreference(rb, pos as usize, distance_code as usize, count as usize) {
3864      pos += count;
3865      rem -= count;
3866      wrap_guard -= count;
3867      if wrap_guard == 0 {
3868        return (pos, rem, true);
3869      }
3870    }
3871  }
3872  while rem > 0 {
3873    rem -= 1;
3874    rb[(pos as usize) & rb_mask_usize] =
3875      rb[(pos.wrapping_sub(distance_code) as usize) & rb_mask_usize];
3876    pos += 1;
3877    wrap_guard -= 1;
3878    if wrap_guard == 0 {
3879      return (pos, rem, true);
3880    }
3881  }
3882  (pos, rem, false)
3883}
3884
3885#[inline(always)]
3886fn save_mid_command_state<AllocU8: alloc::Allocator<u8>,
3887                          AllocU32: alloc::Allocator<u32>,
3888                          AllocHC: alloc::Allocator<HuffmanCode>>(
3889  s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
3890  i: i32,
3891  distance_code: i32,
3892  distance_context: i32,
3893  copy_length: i32,
3894) {
3895  s.loop_counter = i;
3896  s.distance_code = distance_code;
3897  s.distance_context = distance_context;
3898  s.copy_length = copy_length;
3899  if let Some(&idx) = s
3900    .dist_context_map
3901    .slice()
3902    .get(s.dist_context_map_slice_index + (distance_context as usize & 3))
3903  {
3904    s.dist_htree_index = idx;
3905  }
3906}
3907
3908// Unified command loop parameterized over a `CommandLoopMode`:
3909// - `FastCommandLoop`: entered from `COMMAND_BEGIN` with `>= 28` input bytes,
3910//   compiling to a single-entry loop over `BitReaderSlice` with in-place
3911//   `HuffmanTreeGroup` borrows.
3912// - `SafeCommandLoop`: streaming/tail fallback handling arbitrary command entry
3913//   states, `< 28`-byte input tails, and single-command resumption.
3914#[inline(always)]
3915fn ProcessCommandsInternal<
3916  M: CommandLoopMode,
3917  AllocU8: alloc::Allocator<u8>,
3918  AllocU32: alloc::Allocator<u32>,
3919  AllocHC: alloc::Allocator<HuffmanCode>,
3920>(
3921  single_command: bool,
3922  s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
3923  input: &[u8],
3924  dictionary: &[u8],
3925) -> BrotliDecoderErrorCode {
3926  if M::SAFE {
3927    if (!CheckInputAmount(true, &s.br, 28)) || (!WarmupBitReader(true, &mut s.br, input)) {
3928      mark_unlikely();
3929      return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
3930    }
3931    if !matches!(
3932      s.state,
3933      BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN
3934        | BrotliRunningState::BROTLI_STATE_COMMAND_INNER
3935        | BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
3936        | BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY
3937    ) {
3938      mark_unlikely();
3939      return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3940    }
3941  }
3942
3943  let rb_size = s.ringbuffer_size;
3944  let rb_mask = s.ringbuffer_mask;
3945  let mut pos = s.pos;
3946  if !M::SAFE && (rb_size < 2 || (rb_size & (rb_size - 1)) != 0 || rb_mask != rb_size - 1 || pos < 0) {
3947    mark_unlikely();
3948    return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3949  }
3950  let rb_mask_usize = (rb_mask as usize) & 0x7fff_ffff;
3951  let min_rb_len = rb_mask_usize + kRingBufferAllocationSlack;
3952  if !M::SAFE && (pos >= rb_size || s.ringbuffer.slice().len() < min_rb_len) {
3953    mark_unlikely();
3954    return SafeProcessCommands(s, input, dictionary);
3955  }
3956
3957  let mut fbr = if !M::SAFE {
3958    match bit_reader::BitReaderSlice::new(&s.br, input) {
3959      Some(r) => r,
3960      None => {
3961        mark_unlikely();
3962        return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3963      }
3964    }
3965  } else {
3966    bit_reader::BitReaderSlice::empty()
3967  };
3968  let rb: &mut [u8] = if !M::SAFE {
3969    match s.ringbuffer.slice_mut().get_mut(..min_rb_len) {
3970      Some(r) => r,
3971      None => {
3972        mark_unlikely();
3973        return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
3974      }
3975    }
3976  } else {
3977    s.ringbuffer.slice_mut()
3978  };
3979
3980  let mut insert_copy_tree: &InsertCopyTable = huffman_window(&s.insert_copy_hgroup, s.htree_command_index as usize);
3981  let mut literal_htree: &LiteralTable = huffman_window(&s.literal_hgroup, s.literal_htree_index as usize);
3982  let mut context_trees: [&LiteralTable; 64] = EMPTY_CONTEXT_TREES;
3983  let mut context_trees_slice: Option<usize> = None;
3984  let mut distance_tree_index = s.dist_htree_index;
3985  let mut distance_tree: &[HuffmanCode] = if M::SAFE {
3986    huffman_tree(&s.distance_hgroup, distance_tree_index as usize)
3987  } else {
3988    &[]
3989  };
3990  // The 256-entry root tables of the 4 distance contexts of the current
3991  // distance block type, resolved once per block type instead of reading the
3992  // distance context map and looking a tree up whenever consecutive distances
3993  // use different contexts (most distances at q10-q11).
3994  let mut distance_roots: [&DistanceRootTable; 4] = if !M::SAFE {
3995    load_distance_roots(&s.distance_hgroup, s.dist_context_map.slice(), s.dist_context_map_slice_index)
3996  } else {
3997    EMPTY_DISTANCE_ROOTS
3998  };
3999  if !M::SAFE && s.trivial_literal_context == 0 {
4000    fill_context_trees(
4001      &mut context_trees,
4002      &s.literal_hgroup,
4003      s.context_map.slice(),
4004      s.context_map_slice_index,
4005    );
4006    context_trees_slice = Some(s.context_map_slice_index);
4007  }
4008
4009  let mut state = if M::SAFE {
4010    core::mem::replace(&mut s.state, BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN)
4011  } else {
4012    BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN
4013  };
4014  if M::SAFE
4015    && !matches!(
4016      state,
4017      BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN
4018        | BrotliRunningState::BROTLI_STATE_COMMAND_INNER
4019        | BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
4020        | BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY
4021    )
4022  {
4023    s.state = state;
4024    return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
4025  }
4026  let mut i: i32 = if M::SAFE { s.loop_counter } else { 0 };
4027  let mut distance_code: i32 = if M::SAFE { s.distance_code } else { 0 };
4028  let mut distance_context: i32 = if M::SAFE { s.distance_context } else { 0 };
4029  let mut copy_length: i32 = if M::SAFE { s.copy_length } else { 0 };
4030
4031  let mut exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
4032  let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
4033  let mut mid_cmd: Option<(i32, i32, i32, i32)> = None;
4034
4035  'cmd: loop {
4036    if !M::SAFE {
4037      i = 0;
4038      distance_code = 0;
4039      distance_context = 0;
4040      copy_length = 0;
4041    }
4042    if !M::SAFE || matches!(state, BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN) {
4043      if !M::SAFE && !fbr.has_input() {
4044        mark_unlikely();
4045        result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4046        break 'cmd;
4047      }
4048      if s.block_type_length_state.block_length[1] == 0 {
4049        mark_unlikely();
4050        let status = if !M::SAFE {
4051          let (next_fbr, st) =
4052            decode_block_type_and_length_slice(&mut s.block_type_length_state, fbr, 1);
4053          fbr = next_fbr;
4054          if matches!(st, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4055            s.htree_command_index = s.block_type_length_state.block_type_rb[3] as u16;
4056            insert_copy_tree = huffman_window(&s.insert_copy_hgroup, s.htree_command_index as usize);
4057          }
4058          st
4059        } else {
4060          let st = DecodeBlockTypeAndLength(
4061            true,
4062            &mut s.block_type_length_state,
4063            &mut s.br,
4064            1,
4065            input,
4066          );
4067          if matches!(st, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4068            s.htree_command_index = s.block_type_length_state.block_type_rb[3] as u16;
4069            insert_copy_tree = huffman_window(&s.insert_copy_hgroup, s.htree_command_index as usize);
4070          }
4071          st
4072        };
4073        if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4074          result = status;
4075          break 'cmd;
4076        }
4077        continue 'cmd;
4078      }
4079
4080      if !read_command::<M>(
4081        &mut fbr,
4082        &mut s.br,
4083        input,
4084        &mut distance_code,
4085        &mut distance_context,
4086        &mut copy_length,
4087        &mut s.block_type_length_state.block_length[1],
4088        &mut i,
4089        insert_copy_tree,
4090      ) {
4091        mark_unlikely();
4092        result = if M::SAFE {
4093          BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT
4094        } else {
4095          BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE
4096        };
4097        break 'cmd;
4098      }
4099
4100      if M::SAFE {
4101        if i == 0 {
4102          state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4103        } else {
4104          s.meta_block_remaining_len -= i;
4105          state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4106        }
4107      } else if i != 0 {
4108        s.meta_block_remaining_len -= i;
4109      }
4110    }
4111
4112    if (!M::SAFE && i != 0) || (M::SAFE && matches!(state, BrotliRunningState::BROTLI_STATE_COMMAND_INNER)) {
4113      'inner: loop {
4114        if !M::SAFE {
4115          let i_u32 = i as u32;
4116          let block_len = s.block_type_length_state.block_length[0];
4117          let mut handled = false;
4118          if i > 0 && i_u32 <= block_len && pos < rb_size - i && i_u32 * 2 + 34 <= fbr.avail_in() {
4119            let (next_fbr, status) = decode_literal_batch(
4120              rb,
4121              pos as usize,
4122              i as usize,
4123              s.trivial_literal_context,
4124              literal_htree,
4125              &context_trees,
4126              s.context_lookup,
4127              fbr,
4128            );
4129            fbr = next_fbr;
4130            match status {
4131              LiteralBatchStatus::Decoded => {
4132                pos += i;
4133                s.block_type_length_state.block_length[0] -= i_u32;
4134                handled = true;
4135              }
4136              LiteralBatchStatus::NotHandled => {}
4137              LiteralBatchStatus::CorruptInput => {
4138                result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
4139                break 'cmd;
4140              }
4141            }
4142          }
4143          if handled {
4144            break 'inner;
4145          }
4146          mark_unlikely();
4147        }
4148
4149        let mut p1: u8 = if !M::SAFE {
4150          rb[(pos.wrapping_sub(1) as usize) & rb_mask_usize]
4151        } else if rb.is_empty() {
4152          0
4153        } else {
4154          fast!((rb)[((pos - 1) & rb_mask) as usize])
4155        };
4156        let mut p2: u8 = if !M::SAFE {
4157          rb[(pos.wrapping_sub(2) as usize) & rb_mask_usize]
4158        } else if rb.is_empty() {
4159          0
4160        } else {
4161          fast!((rb)[((pos - 2) & rb_mask) as usize])
4162        };
4163        loop {
4164          if !M::SAFE && !fbr.has_input() {
4165            exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4166            mid_cmd = Some((i, distance_code, distance_context, copy_length));
4167            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4168            break 'cmd;
4169          }
4170          if s.block_type_length_state.block_length[0] == 0 {
4171            if !M::SAFE {
4172              mark_unlikely();
4173              let status = if !fbr.has_input() {
4174                BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT
4175              } else {
4176                let (next_fbr, st) =
4177                  decode_block_type_and_length_slice(&mut s.block_type_length_state, fbr, 0);
4178                fbr = next_fbr;
4179                st
4180              };
4181              if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4182                exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4183                mid_cmd = Some((i, distance_code, distance_context, copy_length));
4184                result = status;
4185                break 'cmd;
4186              }
4187              update_literal_block_state(
4188                &s.block_type_length_state.block_type_rb,
4189                &s.trivial_literal_contexts,
4190                s.context_map.slice(),
4191                s.context_modes.slice(),
4192                &mut s.context_map_slice_index,
4193                &mut s.trivial_literal_context,
4194                &mut s.literal_htree_index,
4195                &mut s.context_lookup,
4196              );
4197              literal_htree = huffman_window(&s.literal_hgroup, s.literal_htree_index as usize);
4198              if s.trivial_literal_context == 0
4199                && context_trees_slice != Some(s.context_map_slice_index)
4200              {
4201                fill_context_trees(
4202                  &mut context_trees,
4203                  &s.literal_hgroup,
4204                  s.context_map.slice(),
4205                  s.context_map_slice_index,
4206                );
4207                context_trees_slice = Some(s.context_map_slice_index);
4208              }
4209              continue 'inner;
4210            } else {
4211              mark_unlikely();
4212              let status = DecodeBlockTypeAndLength(
4213                true,
4214                &mut s.block_type_length_state,
4215                &mut s.br,
4216                0,
4217                input,
4218              );
4219              if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4220                exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4221                mid_cmd = Some((i, distance_code, distance_context, copy_length));
4222                result = status;
4223                break 'cmd;
4224              }
4225              update_literal_block_state(
4226                &s.block_type_length_state.block_type_rb,
4227                &s.trivial_literal_contexts,
4228                s.context_map.slice(),
4229                s.context_modes.slice(),
4230                &mut s.context_map_slice_index,
4231                &mut s.trivial_literal_context,
4232                &mut s.literal_htree_index,
4233                &mut s.context_lookup,
4234              );
4235              literal_htree = huffman_window(&s.literal_hgroup, s.literal_htree_index as usize);
4236              if s.block_type_length_state.block_length[0] == 0 {
4237                exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4238                mid_cmd = Some((i, distance_code, distance_context, copy_length));
4239                result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
4240                break 'cmd;
4241              }
4242            }
4243          }
4244          let hc = if s.trivial_literal_context != 0 {
4245            literal_htree
4246          } else if !M::SAFE {
4247            let context = (s.context_lookup[p1 as usize] | s.context_lookup[p2 as usize | 256]) as usize;
4248            context_trees[context & 63]
4249          } else {
4250            let context = (s.context_lookup[p1 as usize] | s.context_lookup[p2 as usize | 256]) as usize;
4251            let idx = fast_slice!((s.context_map)[s.context_map_slice_index + (context & 63)]);
4252            huffman_window(&s.literal_hgroup, idx as usize)
4253          };
4254          let lit = if !M::SAFE {
4255            read_symbol_slice(&mut fbr, hc) as u8
4256          } else {
4257            let mut sym = 0u32;
4258            if !SafeReadSymbol(hc, &mut s.br, &mut sym, input) {
4259              exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
4260              mid_cmd = Some((i, distance_code, distance_context, copy_length));
4261              result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4262              break 'cmd;
4263            }
4264            sym as u8
4265          };
4266          p2 = p1;
4267          p1 = lit;
4268          if !M::SAFE {
4269            rb[(pos as usize) & rb_mask_usize] = lit;
4270          } else {
4271            fast_mut!((rb)[pos as usize]) = lit;
4272          }
4273          s.block_type_length_state.block_length[0] -= 1;
4274          pos += 1;
4275          if pos == rb_size {
4276            exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE;
4277            mid_cmd = Some((i - 1, distance_code, distance_context, copy_length));
4278            break 'cmd;
4279          }
4280          i -= 1;
4281          if i == 0 {
4282            break 'inner;
4283          }
4284        }
4285      }
4286      if s.meta_block_remaining_len <= 0 {
4287        mark_unlikely();
4288        exit_state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4289        break 'cmd;
4290      }
4291      if M::SAFE {
4292        state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4293      }
4294    }
4295
4296    if !M::SAFE || matches!(state, BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) {
4297      if distance_code >= 0 {
4298        distance_context = if distance_code != 0 { 0 } else { 1 };
4299        s.dist_rb_idx -= 1;
4300        distance_code = s.dist_rb[(s.dist_rb_idx & 3) as usize];
4301      } else {
4302        if s.block_type_length_state.block_length[2] == 0 {
4303          mark_unlikely();
4304          let status = if !M::SAFE {
4305            if !fbr.has_input() {
4306              BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT
4307            } else {
4308              let (next_fbr, st) =
4309                decode_block_type_and_length_slice(&mut s.block_type_length_state, fbr, 2);
4310              fbr = next_fbr;
4311              st
4312            }
4313          } else {
4314            DecodeBlockTypeAndLength(
4315              true,
4316              &mut s.block_type_length_state,
4317              &mut s.br,
4318              2,
4319              input,
4320            )
4321          };
4322          if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS) {
4323            exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4324            mid_cmd = Some((0, distance_code, distance_context, copy_length));
4325            result = status;
4326            break 'cmd;
4327          }
4328          s.dist_context_map_slice_index =
4329            (s.block_type_length_state.block_type_rb[5] << kDistanceContextBits) as usize;
4330          if !M::SAFE {
4331            distance_roots = load_distance_roots(
4332              &s.distance_hgroup,
4333              s.dist_context_map.slice(),
4334              s.dist_context_map_slice_index,
4335            );
4336          }
4337        }
4338        let memento = if M::SAFE {
4339          bit_reader::BrotliBitReaderSaveState(&s.br)
4340        } else {
4341          bit_reader::BrotliBitReaderState::default()
4342        };
4343        let dist_sym = if !M::SAFE {
4344          let distance_root = distance_roots[(distance_context as usize) & 3];
4345          fbr.fill16();
4346          let bits = fbr.val as u32;
4347          let table_index = (bits & HUFFMAN_TABLE_MASK) as usize;
4348          let root = distance_root.entry(table_index);
4349          let (sym, consumed) = if root.bits > HUFFMAN_TABLE_BITS as u8 {
4350            decode_distance_subtable(
4351              bits,
4352              table_index,
4353              root,
4354              &s.distance_hgroup,
4355              s.dist_context_map.slice(),
4356              s.dist_context_map_slice_index,
4357              distance_context,
4358            )
4359          } else {
4360            (root.value as usize, root.bits as u32)
4361          };
4362          fbr.avail_bits = fbr.avail_bits.wrapping_sub(consumed);
4363          fbr.val >>= consumed & bit_reader::SLICE_SHIFT_MASK;
4364          sym
4365        } else {
4366          let idx = fast_slice!((s.dist_context_map)[s.dist_context_map_slice_index + (distance_context as usize & 3)]);
4367          s.dist_htree_index = idx;
4368          if idx != distance_tree_index {
4369            distance_tree_index = idx;
4370            distance_tree = huffman_tree(&s.distance_hgroup, idx as usize);
4371          }
4372          let mut sym: u32 = 0;
4373          if !SafeReadSymbol(distance_tree, &mut s.br, &mut sym, input) {
4374            exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4375            mid_cmd = Some((0, distance_code, distance_context, copy_length));
4376            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4377            break 'cmd;
4378          }
4379          sym as usize
4380        };
4381        if !read_distance::<M>(
4382          dist_sym,
4383          &memento,
4384          &mut fbr,
4385          &mut s.br,
4386          input,
4387          &mut distance_code,
4388          &mut distance_context,
4389          &mut s.dist_rb_idx,
4390          &s.dist_rb,
4391          &mut s.block_type_length_state.block_length[2],
4392          s.distance_postfix_bits,
4393          s.distance_postfix_mask,
4394          s.num_direct_distance_codes,
4395        ) {
4396          exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
4397          mid_cmd = Some((0, distance_code, distance_context, copy_length));
4398          result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4399          break 'cmd;
4400        }
4401      }
4402
4403      let max_backward_distance = s.max_backward_distance;
4404      let mut max_distance = s.max_distance;
4405      if max_distance != max_backward_distance {
4406        max_distance = if pos < max_backward_distance {
4407          pos
4408        } else {
4409          max_backward_distance
4410        };
4411        s.max_distance = max_distance;
4412      }
4413
4414      i = copy_length;
4415      if distance_code > max_distance {
4416        mark_unlikely();
4417        match execute_dictionary_copy(
4418          &mut s.compound_dictionary,
4419          &s.dictionary,
4420          s.context_lookup,
4421          &mut s.dist_rb,
4422          &mut s.dist_rb_idx,
4423          &mut s.meta_block_remaining_len,
4424          pos,
4425          rb,
4426          rb_size,
4427          rb_mask,
4428          distance_code,
4429          max_distance,
4430          distance_context,
4431          i,
4432          dictionary,
4433        ) {
4434          Ok((next_pos, true)) => {
4435            pos = next_pos;
4436            exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1;
4437            mid_cmd = Some((i, distance_code, distance_context, copy_length));
4438            break 'cmd;
4439          }
4440          Ok((next_pos, false)) => {
4441            pos = next_pos;
4442            if s.meta_block_remaining_len <= 0 {
4443              exit_state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4444              break 'cmd;
4445            }
4446            if M::SAFE {
4447              state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
4448              if single_command {
4449                break 'cmd;
4450              }
4451            }
4452            continue 'cmd;
4453          }
4454          Err(err) => {
4455            result = err;
4456            break 'cmd;
4457          }
4458        }
4459      }
4460
4461      s.dist_rb[(s.dist_rb_idx & 3) as usize] = distance_code;
4462      s.dist_rb_idx += 1;
4463      s.meta_block_remaining_len -= i;
4464
4465      let src_start = (pos.wrapping_sub(distance_code) as usize) & rb_mask_usize;
4466      let dst_start = (pos as usize) & rb_mask_usize;
4467      let src_start_u32 = src_start as u32;
4468      let dst_start_u32 = pos as u32;
4469      let copy_len_u32 = i as u32;
4470      let lo = core::cmp::min(dst_start_u32, src_start_u32);
4471      let hi = core::cmp::max(dst_start_u32, src_start_u32);
4472      // Check if the copy extends over the ringbuffer end or overlaps with
4473      // itself before the speculative 16-byte copy. `copy_wrap_or_overlapping`
4474      // overwrites `[pos..pos + i]` from the beginning, so skipping the
4475      // 16-byte copy on the wrap/overlap path is semantically identical and
4476      // lets the wrap check (`hi + copy_len_u32`), overlap check (`hi - lo <
4477      // copy_len_u32`), and slice bounds check (`hi <= len - 32`) share
4478      // `hi = max(dst_start_u32, src_start_u32)`.
4479      if hi - lo < copy_len_u32 || hi.wrapping_add(copy_len_u32) >= rb_size as u32 {
4480        mark_unlikely();
4481        if M::SAFE {
4482          if rb.len() < 32 {
4483            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE;
4484            break 'cmd;
4485          }
4486          state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
4487        } else {
4488          let (next_pos, next_i, wrapped) =
4489            copy_wrap_or_overlapping(rb, rb_size, rb_mask, pos, i, distance_code);
4490          pos = next_pos;
4491          i = next_i;
4492          if wrapped {
4493            exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2;
4494            mid_cmd = Some((i, distance_code, distance_context, copy_length));
4495            break 'cmd;
4496          }
4497        }
4498      } else {
4499        if !memmove16_from_ringbuffer(rb, dst_start_u32, src_start_u32) {
4500          mark_unlikely();
4501          result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE;
4502          break 'cmd;
4503        }
4504        pos += i;
4505        if i > 16 {
4506          let copy_ok = if i > 32 {
4507            memcpy_within_slice(rb, dst_start + 16, src_start + 16, (i - 16) as usize)
4508          } else {
4509            memmove16_offset16(rb, dst_start_u32, src_start_u32)
4510          };
4511          if !copy_ok {
4512            mark_unlikely();
4513            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE;
4514            break 'cmd;
4515          }
4516        }
4517      }
4518    }
4519
4520    if M::SAFE && matches!(state, BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY) {
4521      let (next_pos, next_i, wrapped) =
4522        copy_wrap_or_overlapping(rb, rb_size, rb_mask, pos, i, distance_code);
4523      pos = next_pos;
4524      i = next_i;
4525      if wrapped {
4526        exit_state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2;
4527        mid_cmd = Some((i, distance_code, distance_context, copy_length));
4528        break 'cmd;
4529      }
4530    }
4531
4532    if s.meta_block_remaining_len <= 0 {
4533      mark_unlikely();
4534      exit_state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4535      break 'cmd;
4536    }
4537    if M::SAFE {
4538      state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
4539      if single_command {
4540        break 'cmd;
4541      }
4542    }
4543  }
4544
4545  if !M::SAFE {
4546    fbr.sync_to(&mut s.br);
4547  }
4548  s.state = exit_state;
4549  s.pos = pos;
4550  if let Some((rem_i, d_code, d_ctx, c_len)) = mid_cmd {
4551    save_mid_command_state(s, rem_i, d_code, d_ctx, c_len);
4552  }
4553  result
4554}
4555
4556// Kept out of line: inlined into BrotliDecompressStream, the command loop would
4557// share registers with the whole stream state machine and reload its state
4558// from the stack.
4559#[inline(never)]
4560fn ProcessCommands<AllocU8: alloc::Allocator<u8>,
4561                   AllocU32: alloc::Allocator<u32>,
4562                   AllocHC: alloc::Allocator<HuffmanCode>>
4563  (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
4564   input: &[u8],
4565   dictionary: &[u8])
4566   -> BrotliDecoderErrorCode {
4567  if (!CheckInputAmount(false, &s.br, 28)) || (!WarmupBitReader(false, &mut s.br, input)) {
4568    mark_unlikely();
4569    return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4570  }
4571  if !matches!(s.state, BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN) {
4572    mark_unlikely();
4573    let status = SafeProcessCommandsEntry(true, s, input, dictionary);
4574    if !matches!(status, BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS)
4575      || !matches!(s.state, BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN)
4576    {
4577      return status;
4578    }
4579    if (!CheckInputAmount(false, &s.br, 28)) || (!WarmupBitReader(false, &mut s.br, input)) {
4580      return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4581    }
4582  }
4583  ProcessCommandsInternal::<FastCommandLoop, _, _, _>(false, s, input, dictionary)
4584}
4585
4586#[inline(never)]
4587fn SafeProcessCommandsEntry<AllocU8: alloc::Allocator<u8>,
4588                            AllocU32: alloc::Allocator<u32>,
4589                            AllocHC: alloc::Allocator<HuffmanCode>>
4590  (single_command: bool,
4591   s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
4592   input: &[u8],
4593   dictionary: &[u8])
4594   -> BrotliDecoderErrorCode {
4595  ProcessCommandsInternal::<SafeCommandLoop, _, _, _>(single_command, s, input, dictionary)
4596}
4597
4598#[inline(always)]
4599fn SafeProcessCommands<AllocU8: alloc::Allocator<u8>,
4600                       AllocU32: alloc::Allocator<u32>,
4601                       AllocHC: alloc::Allocator<HuffmanCode>>
4602  (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
4603   input: &[u8],
4604   dictionary: &[u8])
4605   -> BrotliDecoderErrorCode {
4606  SafeProcessCommandsEntry(false, s, input, dictionary)
4607}
4608
4609/* Returns the maximum number of distance symbols which can only represent
4610   distances not exceeding BROTLI_MAX_ALLOWED_DISTANCE. */
4611pub fn BrotliMaxDistanceSymbol(ndirect: u32, npostfix: u32) -> u32{
4612  let bound:[u32;kBrotliMaxPostfix + 1] = [0, 4, 12, 28];
4613  let diff:[u32;kBrotliMaxPostfix + 1] = [73, 126, 228, 424];
4614  let postfix = 1 << npostfix;
4615  if (ndirect < bound[npostfix as usize ]) {
4616    return ndirect + diff[npostfix as usize] + postfix;
4617  } else if (ndirect > bound[npostfix as usize] + postfix) {
4618    return ndirect + diff[npostfix as usize];
4619  } else {
4620    return bound[npostfix as usize] + diff[npostfix as usize] + postfix;
4621  }
4622}
4623
4624pub fn BrotliDecompressStream<AllocU8: alloc::Allocator<u8>,
4625                              AllocU32: alloc::Allocator<u32>,
4626                              AllocHC: alloc::Allocator<HuffmanCode>>
4627  (available_in: &mut usize,
4628   input_offset: &mut usize,
4629   xinput: &[u8],
4630   available_out: &mut usize,
4631   output_offset: &mut usize,
4632   output: &mut [u8],
4633   total_out: &mut usize,
4634   s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
4635   -> BrotliResult {
4636  BrotliDecompressStreamWithDictionaryAndMetadata(
4637      available_in, input_offset, xinput,
4638      available_out, output_offset, output,
4639      total_out, &[], None, s)
4640}
4641
4642// As BrotliDecompressStream, lending the decoder `dictionary` for this call:
4643// the dictionary attached with BrotliState::attach_external_dictionary, or an
4644// empty slice if there is none. Any other size fails with
4645// BROTLI_DECODER_ERROR_INVALID_ARGUMENTS.
4646pub fn BrotliDecompressStreamWithDictionary<AllocU8: alloc::Allocator<u8>,
4647                                            AllocU32: alloc::Allocator<u32>,
4648                                            AllocHC: alloc::Allocator<HuffmanCode>>
4649  (available_in: &mut usize,
4650   input_offset: &mut usize,
4651   xinput: &[u8],
4652   available_out: &mut usize,
4653   output_offset: &mut usize,
4654   output: &mut [u8],
4655   total_out: &mut usize,
4656   dictionary: &[u8],
4657   s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
4658   -> BrotliResult {
4659  BrotliDecompressStreamWithDictionaryAndMetadata(
4660      available_in, input_offset, xinput,
4661      available_out, output_offset, output,
4662      total_out, dictionary, None, s)
4663}
4664
4665
4666// As BrotliDecompressStream, lending the decoder `dictionary` for this call:
4667// the dictionary attached with BrotliState::attach_external_dictionary, or an
4668// empty slice if there is none. Also pass in a callback to be called back with any
4669// metadata metablocks that are encountered.
4670pub fn BrotliDecompressStreamWithDictionaryAndMetadata<AllocU8: alloc::Allocator<u8>,
4671                                                       AllocU32: alloc::Allocator<u32>,
4672                                                       AllocHC: alloc::Allocator<HuffmanCode>>
4673  (available_in: &mut usize,
4674   input_offset: &mut usize,
4675   xinput: &[u8],
4676   mut available_out: &mut usize,
4677   mut output_offset: &mut usize,
4678   mut output: &mut [u8],
4679   mut total_out: &mut usize,
4680   dictionary: &[u8],
4681   mut metadata_cb: Option<&mut dyn state::BrotliMetadataCallback>,
4682   mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
4683   -> BrotliResult {
4684
4685  let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
4686
4687  let mut saved_buffer: [u8; 8] = s.buffer;
4688  let mut local_input: &[u8];
4689  if is_fatal(s.error_code) {
4690    return BrotliResult::ResultFailure;
4691  }
4692  if !bit_reader::is_valid_input_range(*input_offset, *available_in, xinput.len()) {
4693    return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
4694  }
4695  if dictionary.len() != s.external_dictionary_len() {
4696    return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
4697  }
4698  match output_offset.checked_add(*available_out) {
4699    Some(end) if end <= output.len() => {}
4700    _ => return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS),
4701  }
4702  if s.buffer_length as usize > s.buffer.len() {
4703    return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE);
4704  }
4705  if s.buffer_length == 0 {
4706    local_input = xinput;
4707    s.br.avail_in = *available_in as u32;
4708    s.br.next_in = *input_offset as u32;
4709    bit_reader::BrotliBitReaderClearUnclaimed(&mut s.br);
4710  } else {
4711    result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4712    let copy_len = core::cmp::min(saved_buffer.len() - s.buffer_length as usize, *available_in);
4713    if copy_len > 0 {
4714      fast_mut!((saved_buffer)[s.buffer_length as usize ; (s.buffer_length as usize + copy_len)])
4715        .clone_from_slice(fast!((xinput)[*input_offset ; copy_len + *input_offset]));
4716      fast_mut!((s.buffer)[s.buffer_length as usize ; (s.buffer_length as usize + copy_len)])
4717        .clone_from_slice(fast!((xinput)[*input_offset ; copy_len + *input_offset]));
4718    }
4719    local_input = &saved_buffer[..];
4720    s.br.next_in = 0;
4721    bit_reader::BrotliBitReaderClearUnclaimed(&mut s.br);
4722  }
4723  loop {
4724    match result {
4725      BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4726      _ => {
4727        match result {
4728          BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT => {
4729            if s.ringbuffer.slice().len() != 0 {
4730              let (intermediate_result, _) = WriteRingBuffer(available_out,
4731                                                             Some(&mut output),
4732                                                             &mut output_offset,
4733                                                             &mut total_out,
4734                                                             true,
4735                                                             &mut s);
4736              if is_fatal(intermediate_result) {
4737                result = intermediate_result;
4738                break;
4739              }
4740            }
4741            if s.buffer_length != 0 {
4742              // Used with internal buffer.
4743              if s.br.avail_in == 0 {
4744                // Successfully finished read transaction.
4745                // Accamulator contains less than 8 bits, because internal buffer
4746                // is expanded byte-by-byte until it is enough to complete read.
4747                s.buffer_length = 0;
4748                // Switch to input stream and restart.
4749                result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
4750                local_input = xinput;
4751                s.br.avail_in = *available_in as u32;
4752                s.br.next_in = *input_offset as u32;
4753                bit_reader::BrotliBitReaderClearUnclaimed(&mut s.br);
4754                continue;
4755              } else if *available_in != 0 {
4756                // Not enough data in buffer, but can take one more byte from
4757                // input stream.
4758                result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
4759                let new_byte = fast!((xinput)[*input_offset]);
4760                let buffer_length = s.buffer_length as usize;
4761                // This byte was copied into saved_buffer at function entry.
4762                if saved_buffer.get(buffer_length) != Some(&new_byte) {
4763                  result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
4764                  break;
4765                }
4766                s.buffer[buffer_length] = new_byte;
4767                s.buffer_length += 1;
4768                s.br.avail_in = s.buffer_length;
4769                (*input_offset) += 1;
4770                (*available_in) -= 1;
4771                // Retry with more data in buffer.
4772                // we can't re-borrow the saved buffer...so we have to do this recursively
4773                continue;
4774              }
4775              // Can't finish reading and no more input.
4776
4777              // FIXME :: NOT SURE WHAT THIS MEANT
4778              // saved_buffer = core::mem::replace(
4779              //  &mut s.br.input_,
4780              //  &mut[]); // clear input
4781              break;
4782            } else {
4783              // Input stream doesn't contain enough input.
4784              // Copy tail to internal buffer and return.
4785              *input_offset = s.br.next_in as usize;
4786              *available_in = s.br.avail_in as usize;
4787              let buffer_length = s.buffer_length as usize;
4788              let input_end = *input_offset as u64 + *available_in as u64;
4789              let buffer_end = buffer_length as u64 + *available_in as u64;
4790              if input_end > xinput.len() as u64 || buffer_end > s.buffer.len() as u64 {
4791                result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
4792                break;
4793              }
4794              let (input_end, buffer_end) = (input_end as usize, buffer_end as usize);
4795              s.buffer[buffer_length..buffer_end]
4796                .clone_from_slice(&xinput[*input_offset..input_end]);
4797              s.buffer_length = buffer_end as u32;
4798              *input_offset = input_end;
4799              *available_in = 0;
4800              break;
4801            }
4802            // unreachable!(); <- dead code
4803          }
4804          _ => {
4805            // Fail or needs more output.
4806            if s.buffer_length != 0 {
4807              // Just consumed the buffered input and produced some output. Otherwise
4808              // it would result in "needs more input". Reset internal buffer.
4809              s.buffer_length = 0;
4810            } else {
4811              // Using input stream in last iteration. When decoder switches to input
4812              // stream it has less than 8 bits in accamulator, so it is safe to
4813              // return unused accamulator bits there.
4814              bit_reader::BrotliBitReaderUnload(&mut s.br);
4815              *available_in = s.br.avail_in as usize;
4816              *input_offset = s.br.next_in as usize;
4817            }
4818          }
4819        }
4820        break;
4821      }
4822    }
4823    if !bit_reader::is_valid_bit_reader(&s.br, local_input) {
4824      result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
4825      continue;
4826    }
4827    loop {
4828      // this emulates fallthrough behavior
4829      match s.state {
4830        BrotliRunningState::BROTLI_STATE_UNINITED => {
4831          // Prepare to the first read.
4832          if (!bit_reader::BrotliWarmupBitReader(&mut s.br, local_input)) {
4833            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4834            break;
4835          }
4836          // Decode window size.
4837          /* Reads 1..8 bits. */
4838          result = DecodeWindowBits(&mut s.large_window, &mut s.window_bits, &mut s.br);
4839          match result {
4840            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4841            _ => break,
4842          }
4843          if s.large_window {
4844              s.state = BrotliRunningState::BROTLI_STATE_LARGE_WINDOW_BITS;
4845          } else {
4846              s.state = BrotliRunningState::BROTLI_STATE_INITIALIZE;
4847          }
4848        }
4849        BrotliRunningState::BROTLI_STATE_LARGE_WINDOW_BITS => {
4850          if (!bit_reader::BrotliSafeReadBits(&mut s.br, 6, &mut s.window_bits, local_input)) {
4851            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
4852            break;
4853          }
4854          if (s.window_bits < kBrotliLargeMinWbits ||
4855              s.window_bits > kBrotliLargeMaxWbits) {
4856            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
4857            break;
4858          }
4859          s.state = BrotliRunningState::BROTLI_STATE_INITIALIZE;
4860        }
4861        BrotliRunningState::BROTLI_STATE_INITIALIZE => {
4862          s.max_backward_distance = (1 << s.window_bits) - kBrotliWindowGap as i32;
4863          // A dictionary passed at construction time becomes a compound
4864          // dictionary chunk; it is kept in its own buffer rather than
4865          // prepended to the ring buffer so that it remains addressable
4866          // after the ring buffer wraps.
4867          if s.custom_dict.slice().len() != 0 {
4868            let dict = mem::replace(&mut s.custom_dict, AllocU8::AllocatedMemory::default());
4869            if !s.attach_compound_dictionary_chunk(state::MaybeOwnedSlice::Owned(dict)) {
4870              result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY;
4871              break;
4872            }
4873          }
4874
4875          // block_type_trees and block_len_trees are allocated when first
4876          // needed; see EnsureBlockTrees.
4877
4878          s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
4879          // No break, continue to next state
4880        }
4881        BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN => {
4882          s.BrotliStateMetablockBegin();
4883          BROTLI_LOG_UINT!(s.pos);
4884          s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER;
4885          // No break, continue to next state
4886        }
4887        BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER => {
4888          result = DecodeMetaBlockLength(&mut s, local_input); // Reads 2 - 31 bits.
4889          match result {
4890            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4891            _ => break,
4892          }
4893          debug_assert!(s.meta_block_remaining_len <= 1 << 24);
4894          BROTLI_LOG_UINT!(s.is_last_metablock);
4895          BROTLI_LOG_UINT!(s.meta_block_remaining_len);
4896          BROTLI_LOG_UINT!(s.is_metadata);
4897          BROTLI_LOG_UINT!(s.is_uncompressed);
4898          if (s.is_metadata != 0 || s.is_uncompressed != 0) &&
4899             !bit_reader::BrotliJumpToByteBoundary(&mut s.br) {
4900            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_1;
4901            break;
4902          }
4903          if s.is_metadata != 0 {
4904            s.state = BrotliRunningState::BROTLI_STATE_METADATA;
4905
4906            if let Some(ref mut callback) = metadata_cb {
4907              callback.start(s.meta_block_remaining_len as usize);
4908            }
4909            break;
4910          }
4911          if s.meta_block_remaining_len == 0 {
4912            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4913            break;
4914          }
4915          BrotliCalculateRingBufferSize(s, local_input);
4916          if s.is_uncompressed != 0 {
4917            s.state = BrotliRunningState::BROTLI_STATE_UNCOMPRESSED;
4918            break;
4919          }
4920          s.loop_counter = 0;
4921          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0;
4922          break;
4923        }
4924        BrotliRunningState::BROTLI_STATE_UNCOMPRESSED => {
4925          let mut _bytes_copied = s.meta_block_remaining_len;
4926          result = CopyUncompressedBlockToOutput(&mut available_out,
4927                                                 &mut output,
4928                                                 &mut output_offset,
4929                                                 &mut total_out,
4930                                                 &mut s,
4931                                                 local_input);
4932          _bytes_copied -= s.meta_block_remaining_len;
4933          match result {
4934            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4935            _ => break,
4936          }
4937          s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
4938          break;
4939        }
4940        BrotliRunningState::BROTLI_STATE_METADATA => {
4941          result = read_metadata_block(
4942              &mut s.br,
4943              &mut s.meta_block_remaining_len,
4944              local_input,
4945              &mut metadata_cb);
4946          if let BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS = result {
4947            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE
4948          }
4949          break;
4950        }
4951        BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0 => {
4952          if s.loop_counter >= 3 {
4953            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER_2;
4954            break;
4955          }
4956          // Reads 1..11 bits.
4957          {
4958            let index = s.loop_counter as usize;
4959            result =
4960              DecodeVarLenUint8(&mut s.substate_decode_uint8,
4961                                &mut s.br,
4962                                &mut fast_mut!((s.block_type_length_state.num_block_types)[index]),
4963                                local_input);
4964          }
4965          match result {
4966            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
4967            _ => break,
4968          }
4969          fast_mut!((s.block_type_length_state.num_block_types)[s.loop_counter as usize]) += 1;
4970          BROTLI_LOG_UINT!(s.block_type_length_state.num_block_types[s.loop_counter as usize]);
4971          if fast!((s.block_type_length_state.num_block_types)[s.loop_counter as usize]) < 2 {
4972            s.loop_counter += 1;
4973            break;
4974          }
4975          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_1;
4976          // No break, continue to next state
4977        }
4978        BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_1 => {
4979          // Only a metablock with more than one block type of some kind needs
4980          // the block type and block length trees, so a stream without block
4981          // switches, as most short ones are, may never allocate them.
4982          if !EnsureBlockTrees(&mut s) {
4983            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES;
4984            break;
4985          }
4986          let tree_offset = s.loop_counter as u32 * huffman::BROTLI_HUFFMAN_MAX_SIZE_258 as u32;
4987          let mut new_huffman_table = mem::replace(&mut s.block_type_length_state.block_type_trees,
4988                                                   AllocHC::AllocatedMemory::default());
4989          let loop_counter = s.loop_counter as usize;
4990          let alphabet_size = fast!((s.block_type_length_state.num_block_types)[loop_counter]) + 2;
4991          result =
4992            ReadHuffmanCode(alphabet_size, alphabet_size,
4993                            new_huffman_table.slice_mut(),
4994                            tree_offset as usize,
4995                            None,
4996                            &mut s,
4997                            local_input);
4998          let _ = mem::replace(&mut s.block_type_length_state.block_type_trees,
4999                       new_huffman_table);
5000          match result {
5001            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5002            _ => break,
5003          }
5004          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_2;
5005          // No break, continue to next state
5006        }
5007        BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_2 => {
5008          let tree_offset = s.loop_counter * huffman::BROTLI_HUFFMAN_MAX_SIZE_26 as i32;
5009          let mut new_huffman_table = mem::replace(&mut s.block_type_length_state.block_len_trees,
5010                                                   AllocHC::AllocatedMemory::default());
5011          result = ReadHuffmanCode(kNumBlockLengthCodes, kNumBlockLengthCodes,
5012                                   new_huffman_table.slice_mut(),
5013                                   tree_offset as usize,
5014                                   None,
5015                                   &mut s,
5016                                   local_input);
5017          let _ = mem::replace(&mut s.block_type_length_state.block_len_trees,
5018                       new_huffman_table);
5019          match result {
5020            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5021            _ => break,
5022          }
5023          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_3;
5024          // No break, continue to next state
5025        }
5026        BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_3 => {
5027          let tree_offset = s.loop_counter * huffman::BROTLI_HUFFMAN_MAX_SIZE_26 as i32;
5028
5029          let mut block_length_out: u32 = 0;
5030          let ind_ret: (bool, u32);
5031          
5032          ind_ret = SafeReadBlockLengthIndex(&s.block_type_length_state.substate_read_block_length,
5033                                             s.block_type_length_state.block_length_index,
5034                                             fast_slice!((s.block_type_length_state.block_len_trees)
5035                                                           [tree_offset as usize;]),
5036                                             &mut s.br, local_input);
5037
5038          if !SafeReadBlockLengthFromIndex(&mut s.block_type_length_state,
5039                                           &mut s.br,
5040                                           &mut block_length_out,
5041                                           ind_ret,
5042                                           local_input) {
5043            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
5044            break;
5045          }
5046          fast_mut!((s.block_type_length_state.block_length)[s.loop_counter as usize]) =
5047            block_length_out;
5048          BROTLI_LOG_UINT!(s.block_type_length_state.block_length[s.loop_counter as usize]);
5049          s.loop_counter += 1;
5050          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0;
5051          break;
5052        }
5053        BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER_2 => {
5054          let mut bits: u32 = 0;
5055          if (!bit_reader::BrotliSafeReadBits(&mut s.br, 6, &mut bits, local_input)) {
5056            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
5057            break;
5058          }
5059          s.distance_postfix_bits = bits & bit_reader::BitMask(2);
5060          bits >>= 2;
5061          s.num_direct_distance_codes = NUM_DISTANCE_SHORT_CODES +
5062                                        (bits << s.distance_postfix_bits);
5063          BROTLI_LOG_UINT!(s.num_direct_distance_codes);
5064          BROTLI_LOG_UINT!(s.distance_postfix_bits);
5065          s.distance_postfix_mask = bit_reader::BitMask(s.distance_postfix_bits) as i32;
5066          let num_literal_block_types =
5067            fast!((s.block_type_length_state.num_block_types)[0]) as usize;
5068          if s.context_modes.slice().len() < num_literal_block_types {
5069            s.alloc_u8.free_cell(core::mem::take(&mut s.context_modes));
5070            s.context_modes = s.alloc_u8.alloc_cell(num_literal_block_types);
5071            if s.context_modes.slice().len() < num_literal_block_types {
5072              result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES;
5073              break;
5074            }
5075          }
5076          s.loop_counter = 0;
5077          s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MODES;
5078          // No break, continue to next state
5079        }
5080        BrotliRunningState::BROTLI_STATE_CONTEXT_MODES => {
5081          result = ReadContextModes(&mut s, local_input);
5082          match result {
5083            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5084            _ => break,
5085          }
5086          s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1;
5087          // No break, continue to next state
5088        }
5089        BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1 => {
5090          result =
5091            DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[0]) as usize) <<
5092                             kLiteralContextBits as usize,
5093                             false,
5094                             &mut s,
5095                             local_input);
5096          match result {
5097            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5098            _ => break,
5099          }
5100          DetectTrivialLiteralBlockTypes(s);
5101          s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2;
5102          // No break, continue to next state
5103        }
5104        BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2 => {
5105            let num_direct_codes =
5106              s.num_direct_distance_codes - NUM_DISTANCE_SHORT_CODES;
5107            let num_distance_codes = BROTLI_DISTANCE_ALPHABET_SIZE(
5108              s.distance_postfix_bits, num_direct_codes,
5109                (if s.large_window { BROTLI_LARGE_MAX_DISTANCE_BITS } else {
5110                    BROTLI_MAX_DISTANCE_BITS}));
5111            let max_distance_symbol = if s.large_window {
5112                BrotliMaxDistanceSymbol(
5113                    num_direct_codes, s.distance_postfix_bits)
5114            } else {
5115                num_distance_codes
5116            };
5117            result =
5118              DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[2]) as usize) <<
5119                               kDistanceContextBits as usize,
5120                               true,
5121                               s,
5122                               local_input);
5123            match result {
5124              BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5125              _ => break,
5126            }
5127            let num_command_htrees =
5128              fast!((s.block_type_length_state.num_block_types)[1]) as u16;
5129            // Growing a tree group frees its old `codes` buffer. Block trees
5130            // must not be allocated after a free (see `EnsureBlockTrees`), so
5131            // allocate them first when a group from an earlier metablock needs
5132            // a larger `codes` buffer.
5133            if (s.literal_hgroup.needs_codes_growth(
5134                  kNumLiteralCodes, kNumLiteralCodes, s.num_literal_htrees as u16) ||
5135                s.insert_copy_hgroup.needs_codes_growth(
5136                  kNumInsertAndCopyCodes, kNumInsertAndCopyCodes, num_command_htrees) ||
5137                s.distance_hgroup.needs_codes_growth(
5138                  num_distance_codes as u16, max_distance_symbol as u16, s.num_dist_htrees as u16)) &&
5139               !EnsureBlockTrees(s) {
5140              return SaveErrorCode!(
5141                s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES);
5142            }
5143            s.literal_hgroup.init(&mut s.alloc_u32,
5144                                  &mut s.alloc_hc,
5145                                  kNumLiteralCodes,
5146                                  kNumLiteralCodes,
5147                                  s.num_literal_htrees as u16);
5148            s.insert_copy_hgroup.init(&mut s.alloc_u32,
5149                                      &mut s.alloc_hc,
5150                                      kNumInsertAndCopyCodes,
5151                                      kNumInsertAndCopyCodes,
5152                                      num_command_htrees);
5153            s.distance_hgroup.init(&mut s.alloc_u32,
5154                                   &mut s.alloc_hc,
5155                                   num_distance_codes as u16,
5156                                   max_distance_symbol as u16,
5157                                   s.num_dist_htrees as u16);
5158            if (s.literal_hgroup.htrees.slice().len() == 0 ||
5159                s.literal_hgroup.codes.slice().len() == 0 ||
5160                s.insert_copy_hgroup.htrees.slice().len() == 0 ||
5161                s.insert_copy_hgroup.codes.slice().len() == 0 ||
5162                s.distance_hgroup.htrees.slice().len() == 0 ||
5163                s.distance_hgroup.codes.slice().len() == 0) {
5164              return SaveErrorCode!(
5165                s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS);
5166            }
5167
5168          /*{
5169            let num_distance_codes: u32 = s.num_direct_distance_codes +
5170                                          (48u32 << s.distance_postfix_bits);
5171            result =
5172              DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[2]) as usize) <<
5173                               kDistanceContextBits as usize,
5174                               true,
5175                               s,
5176                               local_input);
5177            match result {
5178              BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5179              _ => break,
5180            }
5181            s.literal_hgroup.init(&mut s.alloc_u32,
5182                                  &mut s.alloc_hc,
5183                                  kNumLiteralCodes,
5184                                  s.num_literal_htrees as u16);
5185            s.insert_copy_hgroup.init(&mut s.alloc_u32,
5186                                      &mut s.alloc_hc,
5187                                      kNumInsertAndCopyCodes,
5188                                      fast!((s.block_type_length_state.num_block_types)[1]) as u16);
5189            s.distance_hgroup.init(&mut s.alloc_u32,
5190                                   &mut s.alloc_hc,
5191                                   num_distance_codes as u16,
5192                                   s.num_dist_htrees as u16);
5193            if (s.literal_hgroup.codes.slice().len() == 0 ||
5194                s.insert_copy_hgroup.codes.slice().len() == 0 ||
5195                s.distance_hgroup.codes.slice().len() == 0) {
5196              return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS);
5197            }
5198          }*/
5199          s.loop_counter = 0;
5200          s.state = BrotliRunningState::BROTLI_STATE_TREE_GROUP;
5201          // No break, continue to next state
5202        }
5203        BrotliRunningState::BROTLI_STATE_TREE_GROUP => {
5204          result = HuffmanTreeGroupDecode(s.loop_counter, &mut s, local_input);
5205          match result {
5206            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5207            _ => break,
5208          }
5209          s.loop_counter += 1;
5210          if (s.loop_counter >= 3) {
5211            PrepareLiteralDecoding(s);
5212            s.dist_context_map_slice_index = 0;
5213              /*
5214            s.context_map_slice_index = 0;
5215            let context_mode_index = fast!((s.block_type_length_state.block_type_rb)[1]);
5216            let context_mode = fast_slice!((s.context_modes)[context_mode_index as usize]);
5217            s.context_lookup = &kContextLookup[context_mode as usize & 3];
5218               */
5219            s.htree_command_index = 0;
5220            // look it up each time s.literal_htree=s.literal_hgroup.htrees[s.literal_htree_index];
5221            // The header is fully decoded: size the ring buffer for the body.
5222            result = BrotliEnsureRingBuffer(
5223              s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2);
5224            match result {
5225              BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5226              _ => break,
5227            }
5228            s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
5229          }
5230          break;
5231        }
5232        BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN |
5233        BrotliRunningState::BROTLI_STATE_COMMAND_INNER |
5234        BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS |
5235        BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY => {
5236          result = ProcessCommands(s, local_input, dictionary);
5237          if let BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT = result {
5238            result = SafeProcessCommands(s, local_input, dictionary)
5239          }
5240          break;
5241        }
5242        BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE |
5243        BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1 |
5244        BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2 => {
5245          let (xresult, _) = WriteRingBuffer(&mut available_out,
5246                                             Some(&mut output),
5247                                             &mut output_offset,
5248                                             &mut total_out,
5249                                             false,
5250                                             &mut s);
5251          result = xresult;
5252          match result {
5253            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5254            _ => break,
5255          }
5256          if !WrapRingBuffer(s) {
5257            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
5258            break;
5259          }
5260          if s.ringbuffer_size == 1 << s.window_bits {
5261            s.max_distance = s.max_backward_distance;
5262          }
5263          match s.state {
5264            BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1 => {
5265              if s.compound_dictionary.br_length != s.compound_dictionary.br_copied {
5266                // Resume an interrupted copy from the compound dictionary.
5267                let pos = s.pos;
5268                let rb_size = s.ringbuffer_size;
5269                let copied = CopyFromCompoundDictionary(
5270                  &mut s.compound_dictionary,
5271                  s.ringbuffer.slice_mut(),
5272                  rb_size,
5273                  pos,
5274                  dictionary,
5275                );
5276                s.pos += copied;
5277                if s.pos >= s.ringbuffer_size {
5278                  // Ring buffer is full again; flush it and continue copying.
5279                  continue;
5280                }
5281              }
5282              if (s.meta_block_remaining_len <= 0) {
5283                // Next metablock, if any
5284                s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
5285              } else {
5286                s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
5287              }
5288              break;
5289            }
5290            BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2 => {
5291              s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
5292            }
5293            _ => {
5294              // BROTLI_STATE_COMMAND_INNER_WRITE
5295              if (s.loop_counter == 0) {
5296                if (s.meta_block_remaining_len <= 0) {
5297                  s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
5298                } else {
5299                  s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
5300                }
5301                break;
5302              }
5303              s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
5304            }
5305          }
5306          break;
5307        }
5308        BrotliRunningState::BROTLI_STATE_METABLOCK_DONE => {
5309          // RFC 7932 §9.3: "if the number of literals to insert, the copy
5310          // length, or the resulting dictionary word length would cause MLEN to
5311          // be exceeded, then the stream should be rejected as invalid." When a
5312          // command overshoots the declared meta-block length, the command loop
5313          // exits to this state with meta_block_remaining_len < 0. The only
5314          // negative-length guard was in WriteRingBuffer, which is not reached
5315          // when the whole output fits in the ring buffer before the final
5316          // flush, so such malformed streams decoded as success. The C
5317          // reference and andybalholm/brotli (Go) reject them as BLOCK_LENGTH_2;
5318          // mirror that check here, before cleanup.
5319          if (s.meta_block_remaining_len < 0) {
5320            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2;
5321            break;
5322          }
5323          if (s.is_last_metablock == 0) {
5324            // Keep `context_modes`, `context_map`, `dist_context_map`, and the
5325            // Huffman tree groups allocated so the next metablock can reuse
5326            // their buffers when they are large enough.
5327            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
5328            break;
5329          }
5330          s.BrotliStateCleanupAfterMetablock();
5331          if (!bit_reader::BrotliJumpToByteBoundary(&mut s.br)) {
5332            // RFC 7932 §9.2: padding bits at the end of the final metablock
5333            // must be zero. Without `break`, control falls through to
5334            // BROTLI_STATE_DONE which calls WriteRingBuffer and unconditionally
5335            // overwrites `result` with that call's return value, silently
5336            // dropping the padding error.
5337            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_2;
5338            break;
5339          }
5340          if (s.buffer_length == 0) {
5341            bit_reader::BrotliBitReaderUnload(&mut s.br);
5342            *available_in = s.br.avail_in as usize;
5343            *input_offset = s.br.next_in as usize;
5344          }
5345          s.state = BrotliRunningState::BROTLI_STATE_DONE;
5346          // No break, continue to next state
5347        }
5348        BrotliRunningState::BROTLI_STATE_DONE => {
5349          if (s.ringbuffer.slice().len() != 0) {
5350            let (xresult, _) = WriteRingBuffer(&mut available_out,
5351                                               Some(&mut output),
5352                                               &mut output_offset,
5353                                               &mut total_out,
5354                                               true,
5355                                               &mut s);
5356            result = xresult;
5357            match result {
5358              BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
5359              _ => break,
5360            }
5361          }
5362          return SaveErrorCode!(s, result);
5363        }
5364      }
5365    }
5366  }
5367
5368  SaveErrorCode!(s, result)
5369}
5370
5371fn read_metadata_block(
5372    br: &mut bit_reader::BrotliBitReader,
5373    meta_block_remaining_len: &mut i32,
5374    local_input: &[u8],
5375    metadata_cb: &mut Option<&mut dyn state::BrotliMetadataCallback>,
5376) -> BrotliDecoderErrorCode {
5377    if *meta_block_remaining_len <= 0 {
5378        return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
5379    }
5380
5381    let bit_reader_bits_avail = bit_reader::BrotliGetAvailableBits(br);
5382    debug_assert_eq!(bit_reader_bits_avail & 7, 0);
5383    let amt_in_bit_reader = core::cmp::min(
5384        (bit_reader_bits_avail / 8) as usize,
5385        *meta_block_remaining_len as usize);
5386
5387    if amt_in_bit_reader > 0 {
5388        let mut scratch = [0u8; core::mem::size_of::<bit_reader::BrotliBitReader>()];
5389        bit_reader::BrotliCopyBytes(&mut scratch[..], br, amt_in_bit_reader as u32, local_input);
5390        *meta_block_remaining_len -= amt_in_bit_reader as i32;
5391        if let Some(callback) = metadata_cb {
5392            callback.chunk(&scratch[..amt_in_bit_reader]);
5393        }
5394    }
5395    let remaining_bytes = core::cmp::min(*meta_block_remaining_len as usize,
5396                                         br.avail_in as usize);
5397    if remaining_bytes != 0 {
5398        if let Some(callback) = metadata_cb {
5399            let all_remaining_input = local_input.split_at(br.next_in as usize).1;
5400            callback.chunk(&all_remaining_input.split_at(remaining_bytes).0);
5401        }
5402        br.next_in += remaining_bytes as u32;
5403        bit_reader::BrotliBitReaderClearUnclaimed(br);
5404        br.avail_in -= remaining_bytes as u32;
5405        *meta_block_remaining_len -= remaining_bytes as i32;
5406    }
5407    if *meta_block_remaining_len == 0 {
5408        return BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
5409    }
5410    BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT
5411}
5412
5413#[cfg(test)]
5414mod safeguard_tests {
5415  use super::{copy_overlapping_backreference, memcpy_within_slice, memmove16_from_ringbuffer,
5416              memmove16_offset16};
5417
5418  // ProcessCommandsInternal indexes the 64 literal trees of a block type with
5419  // `context & 63` for context = lookup[p1] | lookup[p2 + 256]: the mask
5420  // changes nothing only while every entry is below 64.
5421  #[test]
5422  fn context_lookup_values_fit_the_context_map() {
5423    for table in super::kContextLookup.iter() {
5424      for value in table.iter() {
5425        assert!(*value < 64);
5426      }
5427    }
5428  }
5429
5430  #[test]
5431  fn overlapping_backreferences_match_sequential_copy() {
5432    for distance in 1..65 {
5433      for size in 0..257 {
5434        let mut data = [0u8; 384];
5435        for (index, byte) in data.iter_mut().enumerate() {
5436          *byte = (index.wrapping_mul(73) ^ (index >> 3)) as u8;
5437        }
5438        let mut expected = data;
5439        for index in 64..64 + size {
5440          expected[index] = expected[index - distance];
5441        }
5442        assert!(copy_overlapping_backreference(&mut data, 64, distance, size));
5443        assert_eq!(&data[..], &expected[..]);
5444      }
5445    }
5446  }
5447
5448  #[test]
5449  fn overlapping_backreferences_reject_invalid_ranges() {
5450    let original = [37u8; 32];
5451    for &(dst, distance, size) in &[
5452        (8, 0, 4), (8, 9, 4), (33, 1, 0), (31, 1, 2),
5453        (usize::MAX, 1, 0), (8, usize::MAX, 1), (8, 1, usize::MAX)] {
5454      let mut data = original;
5455      assert!(!copy_overlapping_backreference(&mut data, dst, distance, size));
5456      assert_eq!(data, original);
5457    }
5458  }
5459
5460  #[test]
5461  fn memmove16_helpers_reject_out_of_bounds_ranges() {
5462    // Both require 32 readable and writable bytes from each offset.
5463    let mut short = [0u8; 31];
5464    assert!(!memmove16_from_ringbuffer(&mut short, 0, 0));
5465    assert!(!memmove16_offset16(&mut short, 0, 0));
5466    let mut data = [7u8; 64];
5467    for &(dst, src) in &[(33u32, 0u32), (0, 33), (u32::MAX, 0), (0, u32::MAX)] {
5468      assert!(!memmove16_from_ringbuffer(&mut data, dst, src));
5469      assert!(!memmove16_offset16(&mut data, dst, src));
5470    }
5471    assert_eq!(data, [7u8; 64]);
5472    // The last offsets that fit.
5473    assert!(memmove16_from_ringbuffer(&mut data, 32, 0));
5474    assert!(memmove16_offset16(&mut data, 0, 32));
5475  }
5476
5477  #[test]
5478  fn memmove16_helpers_copy_with_memmove_semantics() {
5479    let mut pattern = [0u8; 80];
5480    for (i, b) in pattern.iter_mut().enumerate() {
5481      *b = i as u8;
5482    }
5483    // Disjoint and overlapping ranges in both directions, including the
5484    // distances below 16 that LZ77 copies hit.
5485    for &(dst, src) in &[(40u32, 0u32), (0, 40), (20, 16), (16, 20), (17, 16), (5, 5)] {
5486      let mut data = pattern;
5487      let mut expected = pattern;
5488      expected.copy_within(src as usize..src as usize + 16, dst as usize);
5489      assert!(memmove16_from_ringbuffer(&mut data, dst, src));
5490      assert_eq!(&data[..], &expected[..], "memmove16_from_ringbuffer({}, {})", dst, src);
5491
5492      let mut data = pattern;
5493      let mut expected = pattern;
5494      expected.copy_within(src as usize + 16..src as usize + 32, dst as usize + 16);
5495      assert!(memmove16_offset16(&mut data, dst, src));
5496      assert_eq!(&data[..], &expected[..], "memmove16_offset16({}, {})", dst, src);
5497    }
5498  }
5499
5500  #[test]
5501  fn memcpy_within_slice_validates_nonoverlapping_ranges() {
5502    let mut data = [0u8, 1, 2, 3, 4, 5, 6, 7];
5503    assert!(memcpy_within_slice(&mut data, 4, 0, 2));
5504    assert_eq!(data, [0, 1, 2, 3, 0, 1, 6, 7]);
5505
5506    let unchanged = data;
5507    assert!(!memcpy_within_slice(&mut data, 1, 0, 4));
5508    assert!(!memcpy_within_slice(&mut data, 7, 0, 2));
5509    assert!(!memcpy_within_slice(&mut data, usize::MAX, 0, 2));
5510    assert!(!memcpy_within_slice(&mut data, 0, usize::MAX, 2));
5511    assert_eq!(data, unchanged);
5512  }
5513}
5514
5515// These need a live BrotliState, so they need an allocator: StandardAlloc is
5516// std-only, as in the `tests` module above.
5517#[cfg(all(test, feature="std"))]
5518mod state_guard_tests {
5519  use super::{CheckRingBufferConsistency, DecodeContextMap, ReadHuffmanCode, UnwrittenBytes,
5520              WrapRingBuffer, WriteRingBuffer};
5521  use super::{decode_block_type_and_length_slice, DecodeBlockTypeAndLength};
5522  use bit_reader::BitReaderSlice;
5523  use super::{BrotliDecoderErrorCode, BrotliRunningState, BrotliState, HuffmanCode};
5524  use ::state::BrotliRunningHuffmanState;
5525  use ::alloc::Allocator;
5526  use ::StandardAlloc;
5527
5528  type TestState = BrotliState<StandardAlloc, StandardAlloc, StandardAlloc>;
5529
5530  fn state() -> TestState {
5531    BrotliState::new(StandardAlloc::default(), StandardAlloc::default(), StandardAlloc::default())
5532  }
5533
5534  // A decoder whose ring buffer is consistent: size is a power of two, mask is
5535  // size - 1, and the allocation is at least that long.
5536  fn state_with_ringbuffer(size: i32, window_bits: u32) -> TestState {
5537    let mut s = state();
5538    s.ringbuffer = s.alloc_u8.alloc_cell(size as usize);
5539    s.ringbuffer_size = size;
5540    s.ringbuffer_mask = size - 1;
5541    s.new_ringbuffer_size = size;
5542    s.window_bits = window_bits;
5543    s
5544  }
5545
5546  // None of the guards below is reachable through BrotliDecompressStream, so
5547  // each is driven directly from an inconsistent decoder state. They exist
5548  // because the `unsafe` build turns an out-of-range index into an out-of-bounds
5549  // access rather than a panic.
5550
5551  #[test]
5552  fn ring_buffer_consistency_rejects_inconsistent_state() {
5553    let mut s = state_with_ringbuffer(16, 4);
5554    assert!(CheckRingBufferConsistency(&s));
5555
5556    s.pos = -1;
5557    assert!(!CheckRingBufferConsistency(&s));
5558    s.pos = 0;
5559
5560    s.ringbuffer_size = 0;
5561    assert!(!CheckRingBufferConsistency(&s));
5562    s.ringbuffer_size = 16;
5563
5564    s.ringbuffer_mask = -1;
5565    assert!(!CheckRingBufferConsistency(&s));
5566
5567    // mask that does not match the size
5568    s.ringbuffer_mask = 7;
5569    assert!(!CheckRingBufferConsistency(&s));
5570    s.ringbuffer_mask = 15;
5571
5572    // size larger than the allocation
5573    s.ringbuffer_size = 32;
5574    s.ringbuffer_mask = 31;
5575    assert!(!CheckRingBufferConsistency(&s));
5576  }
5577
5578  #[test]
5579  fn unwritten_bytes_is_exact_past_a_32_bit_wrap() {
5580    // rb_roundtrips * ringbuffer_size alone overflows a 32-bit usize, so this
5581    // only stays exact because the counters are u64.
5582    let mut s = state_with_ringbuffer(1 << 16, 16);
5583    s.rb_roundtrips = 1 << 17; // 2^17 * 2^16 == 2^33 bytes decoded
5584    s.pos = 100;
5585    s.partial_pos_out = (1u64 << 33) + 40;
5586    assert_eq!(UnwrittenBytes(&s, false), 60);
5587  }
5588
5589  #[test]
5590  fn write_ring_buffer_rejects_inconsistent_ring_buffer() {
5591    let mut s = state_with_ringbuffer(16, 4);
5592    s.ringbuffer_mask = 7; // no longer size - 1
5593    let mut available_out = 8usize;
5594    let mut output = [0u8; 8];
5595    let mut output_offset = 0usize;
5596    let mut total_out = 0usize;
5597    let (code, out) = WriteRingBuffer(&mut available_out, Some(&mut output[..]),
5598                                      &mut output_offset, &mut total_out, false, &mut s);
5599    match code {
5600      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5601      other => panic!("expected UNREACHABLE, got {:?}", other),
5602    }
5603    assert!(out.is_empty());
5604  }
5605
5606  #[test]
5607  fn write_ring_buffer_rejects_negative_block_length() {
5608    let mut s = state_with_ringbuffer(16, 4);
5609    s.meta_block_remaining_len = -1;
5610    let mut available_out = 0usize;
5611    let mut output_offset = 0usize;
5612    let mut total_out = 0usize;
5613    let (code, _) = WriteRingBuffer(&mut available_out, None, &mut output_offset,
5614                                    &mut total_out, false, &mut s);
5615    match code {
5616      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1 => {}
5617      other => panic!("expected BLOCK_LENGTH_1, got {:?}", other),
5618    }
5619  }
5620
5621  #[test]
5622  fn write_ring_buffer_rejects_output_slice_that_cannot_hold_the_write() {
5623    let mut s = state_with_ringbuffer(16, 4);
5624    s.pos = 8; // 8 bytes pending
5625    let mut available_out = 8usize;
5626    let mut output = [0u8; 8];
5627    // output_offset past the end of the caller's buffer: available_out claims
5628    // room the slice does not have.
5629    let mut output_offset = 4usize;
5630    let mut total_out = 0usize;
5631    let (code, _) = WriteRingBuffer(&mut available_out, Some(&mut output[..]),
5632                                    &mut output_offset, &mut total_out, false, &mut s);
5633    match code {
5634      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS => {}
5635      other => panic!("expected INVALID_ARGUMENTS, got {:?}", other),
5636    }
5637  }
5638
5639  #[test]
5640  fn wrap_ring_buffer_rejects_state_it_cannot_split() {
5641    let mut s = state_with_ringbuffer(16, 4);
5642    s.should_wrap_ringbuffer = true;
5643
5644    s.pos = -1;
5645    assert!(!WrapRingBuffer(&mut s));
5646
5647    s.pos = 0;
5648    s.ringbuffer_size = -1;
5649    assert!(!WrapRingBuffer(&mut s));
5650
5651    // size beyond the allocation
5652    s.ringbuffer_size = 64;
5653    s.pos = 1;
5654    assert!(!WrapRingBuffer(&mut s));
5655
5656    // pos past the tail region the wrap copies from
5657    s.ringbuffer_size = 16;
5658    s.pos = 8;
5659    assert!(!WrapRingBuffer(&mut s));
5660
5661    // and a state it can handle: half the buffer is the tail region
5662    let mut ok = state_with_ringbuffer(16, 4);
5663    ok.ringbuffer_size = 8;
5664    ok.ringbuffer_mask = 7;
5665    ok.pos = 4;
5666    ok.should_wrap_ringbuffer = true;
5667    assert!(WrapRingBuffer(&mut ok));
5668    assert!(!ok.should_wrap_ringbuffer);
5669  }
5670
5671  #[test]
5672  fn read_huffman_code_rejects_offset_past_table() {
5673    let mut s = state();
5674    let mut table = [HuffmanCode::default(); 4];
5675    let code = ReadHuffmanCode(256, 256, &mut table, 5, None, &mut s, &[]);
5676    match code {
5677      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => {}
5678      other => panic!("expected HUFFMAN_SPACE, got {:?}", other),
5679    }
5680  }
5681
5682  #[test]
5683  fn read_huffman_code_reports_a_simple_table_that_will_not_fit() {
5684    // The simple-code builder needs 1 << HUFFMAN_TABLE_BITS entries; a caller
5685    // slice shorter than that must surface as an error, not a partial table.
5686    let mut s = state();
5687    s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
5688    s.symbol = 0;
5689    let mut table = [HuffmanCode::default(); 8];
5690    match ReadHuffmanCode(256, 256, &mut table, 0, None, &mut s, &[]) {
5691      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => {}
5692      other => panic!("expected HUFFMAN_SPACE, got {:?}", other),
5693    }
5694  }
5695
5696  #[test]
5697  fn read_huffman_code_reports_a_complex_table_that_will_not_fit() {
5698    let mut s = state();
5699    s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
5700    // Nothing left to read, and a complete code, so the builder runs.
5701    s.symbol = 256;
5702    s.space = 0;
5703    s.code_length_histo[1] = 2;
5704    let mut table = [HuffmanCode::default(); 8];
5705    match ReadHuffmanCode(256, 256, &mut table, 0, None, &mut s, &[]) {
5706      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => {}
5707      other => panic!("expected HUFFMAN_SPACE, got {:?}", other),
5708    }
5709  }
5710
5711  #[test]
5712  fn read_huffman_code_reports_a_code_length_histogram_mismatch() {
5713    // Resuming BROTLI_STATE_HUFFMAN_COMPLEX with a histogram that does not
5714    // describe code_length_code_lengths is exactly what the builder's
5715    // consistency check exists to catch: without it the sort loop indexes
5716    // `sorted` out of bounds.
5717    let mut s = state();
5718    s.substate_huffman = BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_COMPLEX;
5719    // Resume with every code-length code already read (sub_loop_counter at the
5720    // end of kCodeLengthCodeOrder) and a single code recorded, so
5721    // ReadCodeLengthCodeLengths returns success without consuming input.
5722    s.sub_loop_counter = super::CODE_LENGTH_CODES as u32;
5723    s.repeat = 1;
5724    s.space = 32;
5725    // ...but claim a length that code_length_code_lengths does not contain.
5726    s.code_length_histo[2] = 9;
5727    let mut table = [HuffmanCode::default(); 1080];
5728    match ReadHuffmanCode(256, 256, &mut table, 0, None, &mut s, &[]) {
5729      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => {}
5730      other => panic!("expected HUFFMAN_SPACE, got {:?}", other),
5731    }
5732  }
5733
5734  #[test]
5735  fn write_ring_buffer_rejects_a_pending_run_longer_than_the_ring() {
5736    // partial_pos_out lagging by more than one full ring makes `to_write`
5737    // exceed what actually lives in the buffer.
5738    let mut s = state_with_ringbuffer(16, 4);
5739    s.rb_roundtrips = 1;
5740    s.pos = 16;
5741    s.partial_pos_out = 4;
5742    let mut available_out = 64usize;
5743    let mut output = [0u8; 64];
5744    let mut output_offset = 0usize;
5745    let mut total_out = 0usize;
5746    let (code, _) = WriteRingBuffer(&mut available_out, Some(&mut output[..]),
5747                                    &mut output_offset, &mut total_out, false, &mut s);
5748    match code {
5749      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5750      other => panic!("expected UNREACHABLE, got {:?}", other),
5751    }
5752  }
5753
5754  #[test]
5755  fn write_ring_buffer_rejects_output_offset_that_would_overflow() {
5756    let mut s = state_with_ringbuffer(16, 4);
5757    s.pos = 8;
5758    let mut available_out = 8usize;
5759    let mut output_offset = usize::MAX - 1;
5760    let mut total_out = 0usize;
5761    let (code, _) = WriteRingBuffer(&mut available_out, None, &mut output_offset,
5762                                    &mut total_out, false, &mut s);
5763    match code {
5764      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS => {}
5765      other => panic!("expected INVALID_ARGUMENTS, got {:?}", other),
5766    }
5767  }
5768
5769  #[test]
5770  fn decode_context_map_rejects_mismatched_state() {
5771    let mut s = state();
5772    // Neither CONTEXT_MAP_1 with is_dist=false nor CONTEXT_MAP_2 with true.
5773    s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1;
5774    match DecodeContextMap(4, true, &mut s, &[]) {
5775      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5776      other => panic!("expected UNREACHABLE, got {:?}", other),
5777    }
5778    s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2;
5779    match DecodeContextMap(4, false, &mut s, &[]) {
5780      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5781      other => panic!("expected UNREACHABLE, got {:?}", other),
5782    }
5783    s.state = BrotliRunningState::BROTLI_STATE_UNINITED;
5784    match DecodeContextMap(4, false, &mut s, &[]) {
5785      BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => {}
5786      other => panic!("expected UNREACHABLE, got {:?}", other),
5787    }
5788  }
5789
5790  // CVE-2026-111497: the C decoder reported a block switch in a category with
5791  // a single block type as needing more input, and the streaming loop then
5792  // overran its 8-byte input buffer waiting for input that could not help.
5793  #[test]
5794  fn block_switch_with_one_block_type_is_a_format_error() {
5795    let mut s = state();
5796    s.block_type_length_state.num_block_types = [1, 1, 1];
5797    s.block_type_length_state.block_length = [0, 0, 0];
5798    for &safe in [false, true].iter() {
5799      for category in 0..3 {
5800        let result = DecodeBlockTypeAndLength(
5801          safe,
5802          &mut s.block_type_length_state,
5803          &mut s.br,
5804          category,
5805          &[],
5806        );
5807        match result {
5808          BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH => {}
5809          other => panic!("category {} safe {}: expected FORMAT_BLOCK_SWITCH, got {:?}",
5810                          category, safe, other),
5811        }
5812      }
5813    }
5814    for category in 0..3 {
5815      let fbr = BitReaderSlice::new(&s.br, &[]).unwrap();
5816      let (fbr, status) =
5817        decode_block_type_and_length_slice(&mut s.block_type_length_state, fbr, category);
5818      fbr.sync_to(&mut s.br);
5819      match status {
5820        BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH => {}
5821        other => panic!("category {} slice: expected FORMAT_BLOCK_SWITCH, got {:?}",
5822                        category, other),
5823      }
5824    }
5825    assert_eq!(s.br.avail_in, 0);
5826    assert_eq!(s.buffer_length, 0);
5827  }
5828}
5829
5830// read_metadata_block driven directly from bit readers holding 0..=8 whole
5831// bytes in the accumulator, as a byte-aligned metadata header can leave them.
5832#[cfg(all(test, feature="std"))]
5833mod metadata_block_tests {
5834  use super::{read_metadata_block, BrotliDecoderErrorCode};
5835  use ::bit_reader::{self, BrotliBitReader};
5836  use ::state::BrotliMetadataCallback;
5837  use std::vec::Vec;
5838
5839  #[derive(Default)]
5840  struct Chunks(Vec<Vec<u8>>);
5841
5842  impl BrotliMetadataCallback for Chunks {
5843    fn start(&mut self, _size: usize) {
5844      panic!("read_metadata_block must not start a block");
5845    }
5846    fn chunk(&mut self, data: &[u8]) {
5847      assert!(!data.is_empty());
5848      self.0.push(data.to_vec());
5849    }
5850  }
5851
5852  // Bytes the bit reader's accumulator holds: 8 on 64-bit targets, 4 on
5853  // 32-bit ones.
5854  const ACCUMULATOR_BYTES: u32 = ::core::mem::size_of::<bit_reader::reg_t>() as u32;
5855
5856  fn input() -> Vec<u8> {
5857    (0..64u32).map(|i| (i * 37 + 11) as u8).collect()
5858  }
5859
5860  // A reader over all of `input` with its first `buffered` bytes pulled into
5861  // the accumulator.
5862  fn reader(input: &[u8], buffered: u32) -> BrotliBitReader {
5863    let mut br = BrotliBitReader::default();
5864    bit_reader::BrotliInitBitReader(&mut br);
5865    br.avail_in = input.len() as u32;
5866    for _ in 0..buffered {
5867      assert!(bit_reader::BrotliPullByte(&mut br, input));
5868    }
5869    br
5870  }
5871
5872  fn copy(br: &BrotliBitReader) -> BrotliBitReader {
5873    let mut copy = BrotliBitReader::default();
5874    bit_reader::BrotliBitReaderRestoreState(&mut copy, &bit_reader::BrotliBitReaderSaveState(br));
5875    copy
5876  }
5877
5878  fn fields(br: &BrotliBitReader) -> (u64, u32, u32, u32) {
5879    (br.val_ as u64, br.bit_pos_, br.next_in, br.avail_in)
5880  }
5881
5882  fn run(br: &mut BrotliBitReader, remaining: &mut i32, input: &[u8], with_callback: bool)
5883         -> (bool, Vec<Vec<u8>>) {
5884    let mut chunks = Chunks::default();
5885    let result = {
5886      let mut cb: Option<&mut dyn BrotliMetadataCallback> =
5887        if with_callback { Some(&mut chunks) } else { None };
5888      read_metadata_block(br, remaining, input, &mut cb)
5889    };
5890    let done = match result {
5891      BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => true,
5892      BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT => false,
5893      other => panic!("unexpected {:?}", other),
5894    };
5895    (done, chunks.0)
5896  }
5897
5898  #[test]
5899  fn zero_length_block_touches_nothing() {
5900    let input = input();
5901    for buffered in 0..ACCUMULATOR_BYTES + 1 {
5902      let mut br = reader(&input, buffered);
5903      let before = fields(&br);
5904      let mut remaining = 0;
5905      let (done, chunks) = run(&mut br, &mut remaining, &input, true);
5906      assert!(done);
5907      assert!(chunks.is_empty());
5908      assert_eq!(fields(&br), before);
5909    }
5910  }
5911
5912  #[test]
5913  fn block_inside_the_accumulator_leaves_the_rest_buffered() {
5914    let input = input();
5915    for buffered in 1..ACCUMULATOR_BYTES + 1 {
5916      for len in 1..buffered + 1 {
5917        let mut br = reader(&input, buffered);
5918        let mut remaining = len as i32;
5919        let (done, chunks) = run(&mut br, &mut remaining, &input, true);
5920        assert!(done);
5921        assert_eq!(remaining, 0);
5922        assert_eq!(chunks, vec![input[..len as usize].to_vec()]);
5923        // Input untouched; the bytes after the block are still buffered, in
5924        // order, ahead of the input.
5925        assert_eq!((br.next_in, br.avail_in), (buffered, input.len() as u32 - buffered));
5926        assert_eq!(bit_reader::BrotliGetAvailableBits(&br), (buffered - len) * 8);
5927        for expected in &input[len as usize..buffered as usize + 4] {
5928          let mut byte = 0u32;
5929          assert!(bit_reader::BrotliSafeReadBits(&mut br, 8, &mut byte, &input));
5930          assert_eq!(byte, *expected as u32);
5931        }
5932      }
5933    }
5934  }
5935
5936  #[test]
5937  fn longer_block_drains_the_accumulator_then_reads_input_directly() {
5938    let input = input();
5939    for buffered in 0..ACCUMULATOR_BYTES + 1 {
5940      for len in buffered + 1..48 {
5941        let mut br = reader(&input, buffered);
5942        let mut remaining = len as i32;
5943        let (done, chunks) = run(&mut br, &mut remaining, &input, true);
5944        assert!(done);
5945        assert_eq!(remaining, 0);
5946        let mut expected = Vec::new();
5947        if buffered != 0 {
5948          expected.push(input[..buffered as usize].to_vec());
5949        }
5950        expected.push(input[buffered as usize..len as usize].to_vec());
5951        assert_eq!(chunks, expected);
5952        assert_eq!((br.next_in, br.avail_in), (len, input.len() as u32 - len));
5953        assert_eq!(bit_reader::BrotliGetAvailableBits(&br), 0);
5954
5955        // The accumulator is now cold. Both ways the decoder reads next must
5956        // resume at the first byte after the block: the safe byte-at-a-time
5957        // reads of a meta-block header, and the warmed-up, window-filling
5958        // reads of the compressed fast path.
5959        let mut safe = copy(&br);
5960        let mut byte = 0u32;
5961        assert!(bit_reader::BrotliSafeReadBits(&mut safe, 8, &mut byte, &input));
5962        assert_eq!(byte, input[len as usize] as u32);
5963
5964        let mut fast = copy(&br);
5965        assert!(bit_reader::BrotliWarmupBitReader(&mut fast, &input));
5966        for expected in &input[len as usize..len as usize + 8] {
5967          bit_reader::BrotliFillBitWindow(&mut fast, 8, &input);
5968          assert_eq!(bit_reader::BrotliReadBits(&mut fast, 8, &input), *expected as u32);
5969        }
5970      }
5971    }
5972  }
5973
5974  #[test]
5975  fn block_longer_than_the_input_resumes_on_the_next_call() {
5976    let input = input();
5977    for buffered in 0..ACCUMULATOR_BYTES + 1 {
5978      for available in buffered..buffered + 6 {
5979        let len = available + 5;
5980        let first = &input[..available as usize];
5981        let mut br = reader(first, buffered);
5982        let mut remaining = len as i32;
5983        let (done, mut chunks) = run(&mut br, &mut remaining, first, true);
5984        assert!(!done);
5985        assert_eq!(remaining, 5);
5986        assert_eq!(br.avail_in, 0);
5987        assert_eq!(bit_reader::BrotliGetAvailableBits(&br), 0);
5988        assert!(chunks.iter().all(|c| !c.is_empty()));
5989
5990        // The decoder hands over more input the same way: same buffer
5991        // extended, cursor where it stopped.
5992        br.avail_in = (input.len() - available as usize) as u32;
5993        let (done, more) = run(&mut br, &mut remaining, &input, true);
5994        assert!(done);
5995        assert_eq!(more, vec![input[available as usize..len as usize].to_vec()]);
5996        chunks.extend(more);
5997        assert_eq!(chunks.concat(), &input[..len as usize]);
5998        assert_eq!(br.next_in, len);
5999      }
6000    }
6001  }
6002
6003  #[test]
6004  fn no_callback_has_the_same_effect_on_the_reader() {
6005    let input = input();
6006    for buffered in 0..ACCUMULATOR_BYTES + 1 {
6007      for len in 0..20i32 {
6008        for &available in [input.len() as u32, buffered + 2].iter() {
6009          let limited = &input[..available as usize];
6010          let mut with = reader(limited, buffered);
6011          let mut without = copy(&with);
6012          let (mut with_remaining, mut without_remaining) = (len, len);
6013          let (with_done, _) = run(&mut with, &mut with_remaining, limited, true);
6014          let (without_done, chunks) = run(&mut without, &mut without_remaining, limited, false);
6015          assert!(chunks.is_empty());
6016          assert_eq!(with_done, without_done);
6017          assert_eq!(with_remaining, without_remaining);
6018          assert_eq!(fields(&with), fields(&without));
6019        }
6020      }
6021    }
6022  }
6023
6024  #[cfg(debug_assertions)]
6025  #[test]
6026  #[should_panic(expected = "assertion")]
6027  fn unaligned_accumulator_is_a_precondition_violation() {
6028    let input = input();
6029    let mut br = reader(&input, 2);
6030    let mut bits = 0u32;
6031    assert!(bit_reader::BrotliSafeReadBits(&mut br, 3, &mut bits, &input));
6032    let mut remaining = 4;
6033    run(&mut br, &mut remaining, &input, true);
6034  }
6035}