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