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 i32;
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 >= (s.custom_dict_size + s.meta_block_remaining_len) * 2 && s.ringbuffer_size > 32) {
1847        s.ringbuffer_size >>= 1;
1848      }
1849    }
1850    if s.ringbuffer_size > (1 << s.window_bits) {
1851      s.ringbuffer_size = (1 << s.window_bits);
1852    }
1853
1854    s.ringbuffer_mask = s.ringbuffer_size - 1;
1855    s.ringbuffer = s.alloc_u8
1856      .alloc_cell((s.ringbuffer_size as usize + kRingBufferWriteAheadSlack as usize +
1857                   kBrotliMaxDictionaryWordLength as usize));
1858    if (s.ringbuffer.slice().len() == 0) {
1859      return false;
1860    }
1861    fast_mut!((s.ringbuffer.slice_mut())[s.ringbuffer_size as usize - 1]) = 0;
1862    fast_mut!((s.ringbuffer.slice_mut())[s.ringbuffer_size as usize - 2]) = 0;
1863    if custom_dict.len() != 0 {
1864      let offset = ((-s.custom_dict_size) & s.ringbuffer_mask) as usize;
1865      fast_mut!((s.ringbuffer.slice_mut())[offset ; offset + s.custom_dict_size as usize]).clone_from_slice(custom_dict);
1866    }
1867  }
1868  if s.custom_dict.slice().len() != 0 {
1869    s.alloc_u8.free_cell(core::mem::replace(&mut s.custom_dict,
1870                         AllocU8::AllocatedMemory::default()));
1871  }
1872  true
1873}
1874
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 i32 + offset +
1992                        bit_reader::BrotliReadBits(&mut s.br, nbits, input) 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 = ((offset + bits as i32) << s.distance_postfix_bits).wrapping_add(postfix).wrapping_add(s.num_direct_distance_codes as i32);
2010    }
2011  }
2012  s.distance_code = s.distance_code.wrapping_sub(NUM_DISTANCE_SHORT_CODES as i32).wrapping_add(1);
2013  fast_mut!((s.block_type_length_state.block_length)[2]) -= 1;
2014  true
2015}
2016
2017
2018pub fn ReadCommandInternal<AllocU8: alloc::Allocator<u8>,
2019                           AllocU32: alloc::Allocator<u32>,
2020                           AllocHC: alloc::Allocator<HuffmanCode>>
2021  (safe: bool,
2022   s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2023   insert_length: &mut i32,
2024   input: &[u8],
2025   insert_copy_hgroup: &[&[HuffmanCode]; 256])
2026   -> bool {
2027  let mut cmd_code: u32 = 0;
2028  let mut insert_len_extra: u32 = 0;
2029  let mut copy_length: u32 = 0;
2030  let v: prefix::CmdLutElement;
2031  let mut memento = bit_reader::BrotliBitReaderState::default();
2032  if (!safe) {
2033    cmd_code = ReadSymbol(fast!((insert_copy_hgroup)[s.htree_command_index as usize]),
2034                          &mut s.br,
2035                          input);
2036  } else {
2037    memento = bit_reader::BrotliBitReaderSaveState(&s.br);
2038    if (!SafeReadSymbol(fast!((insert_copy_hgroup)[s.htree_command_index as usize]),
2039                        &mut s.br,
2040                        &mut cmd_code,
2041                        input)) {
2042      return false;
2043    }
2044  }
2045  v = fast!((prefix::kCmdLut)[cmd_code as usize]);
2046  s.distance_code = v.distance_code as i32;
2047  s.distance_context = v.context as i32;
2048  s.dist_htree_index = fast_slice!((s.dist_context_map)[s.dist_context_map_slice_index
2049                                                  + s.distance_context as usize]);
2050  *insert_length = v.insert_len_offset as i32;
2051  if (!safe) {
2052    if v.insert_len_extra_bits != 0 {
2053      mark_unlikely();
2054      insert_len_extra =
2055        bit_reader::BrotliReadBits(&mut s.br, v.insert_len_extra_bits as u32, input);
2056    }
2057    copy_length = bit_reader::BrotliReadBits(&mut s.br, v.copy_len_extra_bits as u32, input);
2058  } else if (!SafeReadBits(&mut s.br,
2059                    v.insert_len_extra_bits as u32,
2060                    &mut insert_len_extra,
2061                    input)) ||
2062     (!SafeReadBits(&mut s.br,
2063                    v.copy_len_extra_bits as u32,
2064                    &mut copy_length,
2065                    input)) {
2066    bit_reader::BrotliBitReaderRestoreState(&mut s.br, &memento);
2067    return false;
2068  }
2069  s.copy_length = copy_length as i32 + v.copy_len_offset as i32;
2070  fast_mut!((s.block_type_length_state.block_length)[1]) -= 1;
2071  *insert_length += insert_len_extra as i32;
2072  true
2073}
2074
2075
2076fn WarmupBitReader(safe: bool, br: &mut bit_reader::BrotliBitReader, input: &[u8]) -> bool {
2077  safe || bit_reader::BrotliWarmupBitReader(br, input)
2078}
2079
2080fn CheckInputAmount(safe: bool, br: &bit_reader::BrotliBitReader, num: u32) -> bool {
2081  safe || bit_reader::BrotliCheckInputAmount(br, num)
2082}
2083
2084#[inline(always)]
2085fn memmove16(data: &mut [u8], u32off_dst: u32, u32off_src: u32) {
2086  let off_dst = u32off_dst as usize;
2087  let off_src = u32off_src as usize;
2088  // 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
2185pub fn BrotliDecoderIsUsed<AllocU8: alloc::Allocator<u8>,
2186                           AllocU32: alloc::Allocator<u32>,
2187                           AllocHC: alloc::Allocator<HuffmanCode>>(
2188  s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
2189  if let BrotliRunningState::BROTLI_STATE_UNINITED = s.state {
2190    false
2191  } else {
2192    bit_reader::BrotliGetAvailableBits(&s.br) != 0
2193  }
2194}
2195
2196pub fn BrotliDecoderIsFinished<AllocU8: alloc::Allocator<u8>,
2197                               AllocU32: alloc::Allocator<u32>,
2198                               AllocHC: alloc::Allocator<HuffmanCode>>(
2199  s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> bool {
2200  if let BrotliRunningState::BROTLI_STATE_DONE = s.state {
2201    !BrotliDecoderHasMoreOutput(s)
2202  } else {
2203    false
2204  }
2205}
2206
2207pub fn BrotliDecoderGetErrorCode<AllocU8: alloc::Allocator<u8>,
2208                               AllocU32: alloc::Allocator<u32>,
2209                               AllocHC: alloc::Allocator<HuffmanCode>>(
2210  s: &BrotliState<AllocU8, AllocU32, AllocHC>) -> BrotliDecoderErrorCode {
2211  s.error_code
2212}
2213
2214fn ProcessCommandsInternal<AllocU8: alloc::Allocator<u8>,
2215                           AllocU32: alloc::Allocator<u32>,
2216                           AllocHC: alloc::Allocator<HuffmanCode>>
2217  (safe: bool,
2218   s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2219   input: &[u8])
2220   -> BrotliDecoderErrorCode {
2221  if (!CheckInputAmount(safe, &s.br, 28)) || (!WarmupBitReader(safe, &mut s.br, input)) {
2222    mark_unlikely();
2223    return BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2224  }
2225  let mut pos = s.pos;
2226  let mut i: i32 = s.loop_counter; // important that this is signed
2227  let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2228  let mut saved_literal_hgroup =
2229    core::mem::replace(&mut s.literal_hgroup,
2230                       HuffmanTreeGroup::<AllocU32, AllocHC>::default());
2231  let mut saved_distance_hgroup =
2232    core::mem::replace(&mut s.distance_hgroup,
2233                       HuffmanTreeGroup::<AllocU32, AllocHC>::default());
2234  let mut saved_insert_copy_hgroup =
2235    core::mem::replace(&mut s.insert_copy_hgroup,
2236                       HuffmanTreeGroup::<AllocU32, AllocHC>::default());
2237  {
2238
2239    let literal_hgroup = saved_literal_hgroup.build_hgroup_cache();
2240    let distance_hgroup = saved_distance_hgroup.build_hgroup_cache();
2241    let insert_copy_hgroup = saved_insert_copy_hgroup.build_hgroup_cache();
2242
2243    loop {
2244      match s.state {
2245        BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN => {
2246          if (!CheckInputAmount(safe, &s.br, 28)) {
2247            // 156 bits + 7 bytes
2248            mark_unlikely();
2249            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2250            break; // return
2251          }
2252          if (fast_mut!((s.block_type_length_state.block_length)[1]) == 0) {
2253            mark_unlikely();
2254            if !DecodeCommandBlockSwitchInternal(safe, s, input) {
2255              result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2256              break; // return
2257            }
2258            s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
2259            continue; // goto CommandBegin;
2260          }
2261          // Read the insert/copy length in the command
2262          if (!ReadCommandInternal(safe, s, &mut i, input, &insert_copy_hgroup)) && safe {
2263            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2264            break; // return
2265          }
2266          BROTLI_LOG!("[ProcessCommandsInternal] pos = %d insert = %d copy = %d distance = %d\n",
2267              pos, i, s.copy_length, s.distance_code);
2268          if (i == 0) {
2269            s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2270            continue; // goto CommandPostDecodeLiterals;
2271          }
2272          s.meta_block_remaining_len -= i;
2273          s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
2274        }
2275        BrotliRunningState::BROTLI_STATE_COMMAND_INNER => {
2276          // Read the literals in the command
2277          if (s.trivial_literal_context != 0) {
2278            let mut bits: u32 = 0;
2279            let mut value: u32 = 0;
2280            let mut literal_htree = &fast!((literal_hgroup)[s.literal_htree_index as usize]);
2281            PreloadSymbol(safe, literal_htree, &mut s.br, &mut bits, &mut value, input);
2282            let mut inner_return: bool = false;
2283            let mut inner_continue: bool = false;
2284            loop {
2285              if (!CheckInputAmount(safe, &s.br, 28)) {
2286                // 162 bits + 7 bytes
2287                result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2288                inner_return = true;
2289                break;
2290              }
2291              if (fast!((s.block_type_length_state.block_length)[0]) == 0) {
2292                mark_unlikely();
2293                if (!DecodeLiteralBlockSwitchInternal(safe, s, input)) && safe {
2294                  result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2295                  inner_return = true;
2296                  break;
2297                }
2298                literal_htree = fast_ref!((literal_hgroup)[s.literal_htree_index as usize]);
2299                PreloadSymbol(safe, literal_htree, &mut s.br, &mut bits, &mut value, input);
2300                if (s.trivial_literal_context == 0) {
2301                  s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
2302                  inner_continue = true;
2303                  break; // goto StateCommandInner
2304                }
2305              }
2306              if (!safe) {
2307                fast_mut!((s.ringbuffer.slice_mut())[pos as usize]) =
2308                  ReadPreloadedSymbol(literal_htree, &mut s.br, &mut bits, &mut value, input) as u8;
2309              } else {
2310                let mut literal: u32 = 0;
2311                if (!SafeReadSymbol(literal_htree, &mut s.br, &mut literal, input)) {
2312                  result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2313                  inner_return = true;
2314                  break;
2315                }
2316                fast_mut!((s.ringbuffer.slice_mut())[pos as usize]) = literal as u8;
2317              }
2318              fast_mut!((s.block_type_length_state.block_length)[0]) -= 1;
2319              BROTLI_LOG_UINT!(s.literal_htree_index);
2320              BROTLI_LOG_ARRAY_INDEX!(s.ringbuffer.slice(), pos);
2321              pos += 1;
2322              if (pos == s.ringbuffer_size) {
2323                mark_unlikely();
2324                s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE;
2325                i -= 1;
2326                inner_return = true;
2327                break;
2328              }
2329              i -= 1;
2330              if i == 0 {
2331                break;
2332              }
2333            }
2334            if inner_return {
2335              break; // return
2336            }
2337            if inner_continue {
2338              mark_unlikely();
2339              continue;
2340            }
2341          } else {
2342            let mut p1 = fast_slice!((s.ringbuffer)[((pos - 1) & s.ringbuffer_mask) as usize]);
2343            let mut p2 = fast_slice!((s.ringbuffer)[((pos - 2) & s.ringbuffer_mask) as usize]);
2344            let mut inner_return: bool = false;
2345            let mut inner_continue: bool = false;
2346            loop {
2347              if (!CheckInputAmount(safe, &s.br, 28)) {
2348                // 162 bits + 7 bytes
2349                s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
2350                result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2351                inner_return = true;
2352                break;
2353              }
2354              if (fast!((s.block_type_length_state.block_length)[0]) == 0) {
2355                mark_unlikely();
2356                if (!DecodeLiteralBlockSwitchInternal(safe, s, input)) && safe {
2357                  result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2358                  inner_return = true;
2359                  break;
2360                }
2361                if s.trivial_literal_context != 0 {
2362                  s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
2363                  inner_continue = true;
2364                  break;
2365                }
2366              }
2367              let context = s.context_lookup[p1 as usize] | s.context_lookup[p2 as usize |256];
2368              BROTLI_LOG_UINT!(p1);
2369              BROTLI_LOG_UINT!(p2);
2370              BROTLI_LOG_UINT!(context);
2371              let hc: &[HuffmanCode];
2372              {
2373                let i = fast_slice!((s.context_map)[s.context_map_slice_index + context as usize]);
2374                hc = fast!((literal_hgroup)[i as usize]);
2375              }
2376              p2 = p1;
2377              if (!safe) {
2378                p1 = ReadSymbol(hc, &mut s.br, input) as u8;
2379              } else {
2380                let mut literal: u32 = 0;
2381                if (!SafeReadSymbol(hc, &mut s.br, &mut literal, input)) {
2382                  result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2383                  inner_return = true;
2384                  break;
2385                }
2386                p1 = literal as u8;
2387              }
2388              fast_slice_mut!((s.ringbuffer)[pos as usize]) = p1;
2389              fast_mut!((s.block_type_length_state.block_length)[0]) -= 1;
2390              BROTLI_LOG_UINT!(s.context_map.slice()[s.context_map_slice_index as usize +
2391                                                     context as usize]);
2392              BROTLI_LOG_ARRAY_INDEX!(s.ringbuffer.slice(), pos & s.ringbuffer_mask);
2393              pos += 1;
2394              if (pos == s.ringbuffer_size) {
2395                mark_unlikely();
2396                s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE;
2397                i -= 1;
2398                inner_return = true;
2399                break;
2400              }
2401              i -= 1;
2402              if i == 0 {
2403                break;
2404              }
2405            }
2406            if inner_return {
2407              break; // return
2408            }
2409            if inner_continue {
2410              mark_unlikely();
2411              continue;
2412            }
2413          }
2414          if (s.meta_block_remaining_len <= 0) {
2415            mark_unlikely();
2416            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2417            break; // return
2418          }
2419          s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2420        }
2421        BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS => {
2422          if s.distance_code >= 0 {
2423            let not_distance_code = if s.distance_code != 0 { 0 } else { 1 };
2424            s.distance_context = not_distance_code;
2425            s.dist_rb_idx -= 1;
2426            s.distance_code = fast!((s.dist_rb)[(s.dist_rb_idx & 3) as usize]);
2427            // goto postReadDistance
2428          } else {
2429            if fast!((s.block_type_length_state.block_length)[2]) == 0 {
2430              mark_unlikely();
2431              if (!DecodeDistanceBlockSwitchInternal(safe, s, input)) && safe {
2432                result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2433                break; // return
2434              }
2435            }
2436            if (!ReadDistanceInternal(safe, s, input, &distance_hgroup)) && safe {
2437              result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2438              break; // return
2439            }
2440          }
2441          // postReadDistance:
2442          BROTLI_LOG!("[ProcessCommandsInternal] pos = %d distance = %d\n",
2443                      pos, s.distance_code);
2444
2445          if (s.max_distance != s.max_backward_distance) {
2446            if (pos < s.max_backward_distance_minus_custom_dict_size) {
2447              s.max_distance = pos + s.custom_dict_size;
2448            } else {
2449              s.max_distance = s.max_backward_distance;
2450            }
2451          }
2452          i = s.copy_length;
2453          // Apply copy of LZ77 back-reference, or static dictionary reference if
2454          // the distance is larger than the max LZ77 distance
2455          if (s.distance_code > s.max_distance) {
2456            if s.distance_code > kBrotliMaxAllowedDistance as i32 {
2457              return BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE;
2458            }
2459            if (i >= kBrotliMinDictionaryWordLength as i32 &&
2460                i <= kBrotliMaxDictionaryWordLength as i32) {
2461              let mut offset = fast!((kBrotliDictionaryOffsetsByLength)[i as usize]) as i32;
2462              let word_id = s.distance_code - s.max_distance - 1;
2463              let shift = fast!((kBrotliDictionarySizeBitsByLength)[i as usize]);
2464              let mask = bit_reader::BitMask(shift as u32) as i32;
2465              let word_idx = word_id & mask;
2466              let transform_idx = word_id >> shift;
2467              s.dist_rb_idx += s.distance_context;
2468              offset += word_idx * i;
2469              if (transform_idx < kNumTransforms) {
2470                let mut len = i;
2471                let word = fast!((kBrotliDictionary)[offset as usize ; (offset + len) as usize]);
2472                if (transform_idx == 0) {
2473                  fast_slice_mut!((s.ringbuffer)[pos as usize ; ((pos + len) as usize)])
2474                    .clone_from_slice(word);
2475                } else {
2476                  len = TransformDictionaryWord(fast_slice_mut!((s.ringbuffer)[pos as usize;]),
2477                                                word,
2478                                                len,
2479                                                transform_idx);
2480                }
2481                pos += len;
2482                s.meta_block_remaining_len -= len;
2483                if (pos >= s.ringbuffer_size) {
2484                  // s.partial_pos_rb += (size_t)s.ringbuffer_size;
2485                  s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1;
2486                  break; // return return
2487                }
2488              } else {
2489                BROTLI_LOG!(
2490                  "Invalid backward reference. pos: %d distance: %d len: %d bytes left: %d\n",
2491                  pos, s.distance_code, i,
2492                  s.meta_block_remaining_len);
2493                result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM;
2494                break; // return
2495              }
2496            } else {
2497              BROTLI_LOG!(
2498                "Invalid backward reference. pos:%d distance:%d len:%d bytes left:%d\n",
2499                pos, s.distance_code, i, s.meta_block_remaining_len);
2500              result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DICTIONARY;
2501              break; // return
2502            }
2503          } else {
2504            // update the recent distances cache
2505            fast_mut!((s.dist_rb)[(s.dist_rb_idx & 3) as usize]) = s.distance_code;
2506            s.dist_rb_idx += 1;
2507            s.meta_block_remaining_len -= i;
2508            // There is 128+ bytes of slack in the ringbuffer allocation.
2509            // Also, we have 16 short codes, that make these 16 bytes irrelevant
2510            // in the ringbuffer. Let's copy over them as a first guess.
2511            //
2512            let src_start = ((pos - s.distance_code) & s.ringbuffer_mask) as u32;
2513            let dst_start = pos as u32;
2514            let dst_end = pos as u32 + i as u32;
2515            let src_end = src_start + i as u32;
2516            memmove16(&mut s.ringbuffer.slice_mut(), dst_start, src_start);
2517            // Now check if the copy extends over the ringbuffer end,
2518            // or if the copy overlaps with itself, if yes, do wrap-copy.
2519            if (src_end > pos as u32 && dst_end > src_start) {
2520              s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
2521              continue; //goto CommandPostWrapCopy;
2522            }
2523            if (dst_end >= s.ringbuffer_size as u32 || src_end >= s.ringbuffer_size as u32) {
2524              s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
2525              continue; //goto CommandPostWrapCopy;
2526            }
2527            pos += i;
2528            if (i > 16) {
2529              if (i > 32) {
2530                memcpy_within_slice(s.ringbuffer.slice_mut(),
2531                                    dst_start as usize + 16,
2532                                    src_start as usize + 16,
2533                                    (i - 16) as usize);
2534              } else {
2535                // This branch covers about 45% cases.
2536                // Fixed size short copy allows more compiler optimizations.
2537                memmove16(&mut s.ringbuffer.slice_mut(),
2538                          dst_start + 16,
2539                          src_start + 16);
2540              }
2541            }
2542          }
2543          if (s.meta_block_remaining_len <= 0) {
2544            // Next metablock, if any
2545            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2546            break; // return
2547          } else {
2548            s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
2549            continue; // goto CommandBegin
2550          }
2551        }
2552        BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY => {
2553          let mut wrap_guard = s.ringbuffer_size - pos;
2554          let mut inner_return: bool = false;
2555          while i > 0 {
2556            i -= 1;
2557            fast_slice_mut!((s.ringbuffer)[pos as usize]) =
2558              fast_slice!((s.ringbuffer)[((pos - s.distance_code) & s.ringbuffer_mask) as usize]);
2559            pos += 1;
2560            wrap_guard -= 1;
2561            if (wrap_guard == 0) {
2562              mark_unlikely();
2563              // s.partial_pos_rb += (size_t)s.ringbuffer_size;
2564              s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2;
2565              inner_return = true;
2566              break; //return
2567            }
2568          }
2569          if inner_return {
2570            mark_unlikely();
2571            break;
2572          }
2573          i -= 1;
2574          if (s.meta_block_remaining_len <= 0) {
2575            // Next metablock, if any
2576            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2577            break; // return
2578          } else {
2579            s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
2580            continue;
2581          }
2582        }
2583        _ => {
2584          result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE;
2585          break; // return
2586        }
2587      }
2588    }
2589  }
2590  s.pos = pos;
2591  s.loop_counter = i;
2592
2593  let _ = core::mem::replace(&mut s.literal_hgroup,
2594                     core::mem::replace(&mut saved_literal_hgroup,
2595                                        HuffmanTreeGroup::<AllocU32, AllocHC>::default()));
2596
2597  let _ = core::mem::replace(&mut s.distance_hgroup,
2598                     core::mem::replace(&mut saved_distance_hgroup,
2599                                        HuffmanTreeGroup::<AllocU32, AllocHC>::default()));
2600
2601  let _ = core::mem::replace(&mut s.insert_copy_hgroup,
2602                     core::mem::replace(&mut saved_insert_copy_hgroup,
2603                                        HuffmanTreeGroup::<AllocU32, AllocHC>::default()));
2604
2605  result
2606}
2607
2608fn ProcessCommands<AllocU8: alloc::Allocator<u8>,
2609                   AllocU32: alloc::Allocator<u32>,
2610                   AllocHC: alloc::Allocator<HuffmanCode>>
2611  (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2612   input: &[u8])
2613   -> BrotliDecoderErrorCode {
2614  ProcessCommandsInternal(false, s, input)
2615}
2616
2617fn SafeProcessCommands<AllocU8: alloc::Allocator<u8>,
2618                       AllocU32: alloc::Allocator<u32>,
2619                       AllocHC: alloc::Allocator<HuffmanCode>>
2620  (s: &mut BrotliState<AllocU8, AllocU32, AllocHC>,
2621   input: &[u8])
2622   -> BrotliDecoderErrorCode {
2623  ProcessCommandsInternal(true, s, input)
2624}
2625
2626/* Returns the maximum number of distance symbols which can only represent
2627   distances not exceeding BROTLI_MAX_ALLOWED_DISTANCE. */
2628pub fn BrotliMaxDistanceSymbol(ndirect: u32, npostfix: u32) -> u32{
2629  let bound:[u32;kBrotliMaxPostfix + 1] = [0, 4, 12, 28];
2630  let diff:[u32;kBrotliMaxPostfix + 1] = [73, 126, 228, 424];
2631  let postfix = 1 << npostfix;
2632  if (ndirect < bound[npostfix as usize ]) {
2633    return ndirect + diff[npostfix as usize] + postfix;
2634  } else if (ndirect > bound[npostfix as usize] + postfix) {
2635    return ndirect + diff[npostfix as usize];
2636  } else {
2637    return bound[npostfix as usize] + diff[npostfix as usize] + postfix;
2638  }
2639}
2640
2641pub fn BrotliDecompressStream<AllocU8: alloc::Allocator<u8>,
2642                              AllocU32: alloc::Allocator<u32>,
2643                              AllocHC: alloc::Allocator<HuffmanCode>>
2644  (available_in: &mut usize,
2645   input_offset: &mut usize,
2646   xinput: &[u8],
2647   mut available_out: &mut usize,
2648   mut output_offset: &mut usize,
2649   mut output: &mut [u8],
2650   mut total_out: &mut usize,
2651   mut s: &mut BrotliState<AllocU8, AllocU32, AllocHC>)
2652   -> BrotliResult {
2653
2654  let mut result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2655
2656  let mut saved_buffer: [u8; 8] = s.buffer;
2657  let mut local_input: &[u8];
2658  if is_fatal(s.error_code) {
2659    return BrotliResult::ResultFailure;
2660  }
2661  if *available_in as u64 >= (1u64 << 32) {
2662    return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
2663  }
2664  if *input_offset as u64 >= (1u64 << 32) {
2665    return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
2666  }
2667  if *input_offset + *available_in > xinput.len() {
2668    return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
2669  }
2670  if *output_offset + *available_out > output.len() {
2671    return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS);
2672  }
2673  if s.buffer_length == 0 {
2674    local_input = xinput;
2675    s.br.avail_in = *available_in as u32;
2676    s.br.next_in = *input_offset as u32;
2677  } else {
2678    result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2679    let copy_len = core::cmp::min(saved_buffer.len() - s.buffer_length as usize, *available_in);
2680    if copy_len > 0 {
2681      fast_mut!((saved_buffer)[s.buffer_length as usize ; (s.buffer_length as usize + copy_len)])
2682        .clone_from_slice(fast!((xinput)[*input_offset ; copy_len + *input_offset]));
2683      fast_mut!((s.buffer)[s.buffer_length as usize ; (s.buffer_length as usize + copy_len)])
2684        .clone_from_slice(fast!((xinput)[*input_offset ; copy_len + *input_offset]));
2685    }
2686    local_input = &saved_buffer[..];
2687    s.br.next_in = 0;
2688  }
2689  loop {
2690    match result {
2691      BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2692      _ => {
2693        match result {
2694          BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT => {
2695            if s.ringbuffer.slice().len() != 0 {
2696              let (intermediate_result, _) = WriteRingBuffer(available_out,
2697                                                             Some(&mut output),
2698                                                             &mut output_offset,
2699                                                             &mut total_out,
2700                                                             true,
2701                                                             &mut s);
2702              if is_fatal(intermediate_result) {
2703                result = intermediate_result;
2704                break;
2705              }
2706            }
2707            if s.buffer_length != 0 {
2708              // Used with internal buffer.
2709              if s.br.avail_in == 0 {
2710                // Successfully finished read transaction.
2711                // Accamulator contains less than 8 bits, because internal buffer
2712                // is expanded byte-by-byte until it is enough to complete read.
2713                s.buffer_length = 0;
2714                // Switch to input stream and restart.
2715                result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2716                local_input = xinput;
2717                s.br.avail_in = *available_in as u32;
2718                s.br.next_in = *input_offset as u32;
2719                continue;
2720              } else if *available_in != 0 {
2721                // Not enough data in buffer, but can take one more byte from
2722                // input stream.
2723                result = BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS;
2724                let new_byte = fast!((xinput)[*input_offset]);
2725                fast_mut!((s.buffer)[s.buffer_length as usize]) = new_byte;
2726                // we did the following copy upfront, so we wouldn't have to do it here
2727                // since saved_buffer[s.buffer_length as usize] = new_byte violates borrow rules
2728                assert_eq!(fast!((saved_buffer)[s.buffer_length as usize]), new_byte);
2729                s.buffer_length += 1;
2730                s.br.avail_in = s.buffer_length;
2731                (*input_offset) += 1;
2732                (*available_in) -= 1;
2733                // Retry with more data in buffer.
2734                // we can't re-borrow the saved buffer...so we have to do this recursively
2735                continue;
2736              }
2737              // Can't finish reading and no more input.
2738
2739              // FIXME :: NOT SURE WHAT THIS MEANT
2740              // saved_buffer = core::mem::replace(
2741              //  &mut s.br.input_,
2742              //  &mut[]); // clear input
2743              break;
2744            } else {
2745              // Input stream doesn't contain enough input.
2746              // Copy tail to internal buffer and return.
2747              *input_offset = s.br.next_in as usize;
2748              *available_in = s.br.avail_in as usize;
2749              while *available_in != 0 {
2750                fast_mut!((s.buffer)[s.buffer_length as usize]) = fast!((xinput)[*input_offset]);
2751                s.buffer_length += 1;
2752                (*input_offset) += 1;
2753                (*available_in) -= 1;
2754              }
2755              break;
2756            }
2757            // unreachable!(); <- dead code
2758          }
2759          _ => {
2760            // Fail or needs more output.
2761            if s.buffer_length != 0 {
2762              // Just consumed the buffered input and produced some output. Otherwise
2763              // it would result in "needs more input". Reset internal buffer.
2764              s.buffer_length = 0;
2765            } else {
2766              // Using input stream in last iteration. When decoder switches to input
2767              // stream it has less than 8 bits in accamulator, so it is safe to
2768              // return unused accamulator bits there.
2769              bit_reader::BrotliBitReaderUnload(&mut s.br);
2770              *available_in = s.br.avail_in as usize;
2771              *input_offset = s.br.next_in as usize;
2772            }
2773          }
2774        }
2775        break;
2776      }
2777    }
2778    loop {
2779      // this emulates fallthrough behavior
2780      match s.state {
2781        BrotliRunningState::BROTLI_STATE_UNINITED => {
2782          // Prepare to the first read.
2783          if (!bit_reader::BrotliWarmupBitReader(&mut s.br, local_input)) {
2784            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2785            break;
2786          }
2787          // Decode window size.
2788          /* Reads 1..8 bits. */
2789          result = DecodeWindowBits(&mut s.large_window, &mut s.window_bits, &mut s.br);
2790          match result {
2791            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2792            _ => break,
2793          }
2794          if s.large_window {
2795              s.state = BrotliRunningState::BROTLI_STATE_LARGE_WINDOW_BITS;
2796          } else {
2797              s.state = BrotliRunningState::BROTLI_STATE_INITIALIZE;
2798          }
2799        }
2800        BrotliRunningState::BROTLI_STATE_LARGE_WINDOW_BITS => {
2801          if (!bit_reader::BrotliSafeReadBits(&mut s.br, 6, &mut s.window_bits, local_input)) {
2802            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2803            break;
2804          }
2805          if (s.window_bits < kBrotliLargeMinWbits ||
2806              s.window_bits > kBrotliLargeMaxWbits) {
2807            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS;
2808            break;
2809          }
2810          s.state = BrotliRunningState::BROTLI_STATE_INITIALIZE;
2811        }
2812        BrotliRunningState::BROTLI_STATE_INITIALIZE => {
2813          s.max_backward_distance = (1 << s.window_bits) - kBrotliWindowGap as i32;
2814          s.max_backward_distance_minus_custom_dict_size = s.max_backward_distance -
2815                                                           s.custom_dict_size;
2816
2817          // (formerly) Allocate memory for both block_type_trees and block_len_trees.
2818          s.block_type_length_state.block_type_trees = s.alloc_hc
2819            .alloc_cell(3 * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as usize);
2820          if (s.block_type_length_state.block_type_trees.slice().len() == 0) {
2821            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES;
2822            break;
2823          }
2824          s.block_type_length_state.block_len_trees = s.alloc_hc
2825            .alloc_cell(3 * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as usize);
2826
2827          s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
2828          // No break, continue to next state
2829        }
2830        BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN => {
2831          s.BrotliStateMetablockBegin();
2832          BROTLI_LOG_UINT!(s.pos);
2833          s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER;
2834          // No break, continue to next state
2835        }
2836        BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER => {
2837          result = DecodeMetaBlockLength(&mut s, local_input); // Reads 2 - 31 bits.
2838          match result {
2839            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2840            _ => break,
2841          }
2842          BROTLI_LOG_UINT!(s.is_last_metablock);
2843          BROTLI_LOG_UINT!(s.meta_block_remaining_len);
2844          BROTLI_LOG_UINT!(s.is_metadata);
2845          BROTLI_LOG_UINT!(s.is_uncompressed);
2846          if (s.is_metadata != 0 || s.is_uncompressed != 0) &&
2847             !bit_reader::BrotliJumpToByteBoundary(&mut s.br) {
2848            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_2;
2849            break;
2850          }
2851          if s.is_metadata != 0 {
2852            s.state = BrotliRunningState::BROTLI_STATE_METADATA;
2853            break;
2854          }
2855          if s.meta_block_remaining_len == 0 {
2856            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2857            break;
2858          }
2859          if s.ringbuffer.slice().len() == 0 && !BrotliAllocateRingBuffer(&mut s, local_input) {
2860            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2;
2861            break;
2862          }
2863          if s.is_uncompressed != 0 {
2864            s.state = BrotliRunningState::BROTLI_STATE_UNCOMPRESSED;
2865            break;
2866          }
2867          s.loop_counter = 0;
2868          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0;
2869          break;
2870        }
2871        BrotliRunningState::BROTLI_STATE_UNCOMPRESSED => {
2872          let mut _bytes_copied = s.meta_block_remaining_len;
2873          result = CopyUncompressedBlockToOutput(&mut available_out,
2874                                                 &mut output,
2875                                                 &mut output_offset,
2876                                                 &mut total_out,
2877                                                 &mut s,
2878                                                 local_input);
2879          _bytes_copied -= s.meta_block_remaining_len;
2880          match result {
2881            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2882            _ => break,
2883          }
2884          s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
2885          break;
2886        }
2887        BrotliRunningState::BROTLI_STATE_METADATA => {
2888          while s.meta_block_remaining_len > 0 {
2889            let mut bits = 0u32;
2890            // Read one byte and ignore it.
2891            if !bit_reader::BrotliSafeReadBits(&mut s.br, 8, &mut bits, local_input) {
2892              result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2893              break;
2894            }
2895            s.meta_block_remaining_len -= 1;
2896          }
2897          if let BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS = result {
2898            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE
2899          }
2900          break;
2901        }
2902        BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0 => {
2903          if s.loop_counter >= 3 {
2904            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER_2;
2905            break;
2906          }
2907          // Reads 1..11 bits.
2908          {
2909            let index = s.loop_counter as usize;
2910            result =
2911              DecodeVarLenUint8(&mut s.substate_decode_uint8,
2912                                &mut s.br,
2913                                &mut fast_mut!((s.block_type_length_state.num_block_types)[index]),
2914                                local_input);
2915          }
2916          match result {
2917            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2918            _ => break,
2919          }
2920          fast_mut!((s.block_type_length_state.num_block_types)[s.loop_counter as usize]) += 1;
2921          BROTLI_LOG_UINT!(s.block_type_length_state.num_block_types[s.loop_counter as usize]);
2922          if fast!((s.block_type_length_state.num_block_types)[s.loop_counter as usize]) < 2 {
2923            s.loop_counter += 1;
2924            break;
2925          }
2926          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_1;
2927          // No break, continue to next state
2928        }
2929        BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_1 => {
2930          let tree_offset = s.loop_counter as u32 * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as u32;
2931          let mut new_huffman_table = mem::replace(&mut s.block_type_length_state.block_type_trees,
2932                                                   AllocHC::AllocatedMemory::default());
2933          let loop_counter = s.loop_counter as usize;
2934          let alphabet_size = fast!((s.block_type_length_state.num_block_types)[loop_counter]) + 2;
2935          result =
2936            ReadHuffmanCode(alphabet_size, alphabet_size,
2937                            new_huffman_table.slice_mut(),
2938                            tree_offset as usize,
2939                            None,
2940                            &mut s,
2941                            local_input);
2942          let _ = mem::replace(&mut s.block_type_length_state.block_type_trees,
2943                       new_huffman_table);
2944          match result {
2945            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2946            _ => break,
2947          }
2948          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_2;
2949          // No break, continue to next state
2950        }
2951        BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_2 => {
2952          let tree_offset = s.loop_counter * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as i32;
2953          let mut new_huffman_table = mem::replace(&mut s.block_type_length_state.block_len_trees,
2954                                                   AllocHC::AllocatedMemory::default());
2955          result = ReadHuffmanCode(kNumBlockLengthCodes, kNumBlockLengthCodes,
2956                                   new_huffman_table.slice_mut(),
2957                                   tree_offset as usize,
2958                                   None,
2959                                   &mut s,
2960                                   local_input);
2961          let _ = mem::replace(&mut s.block_type_length_state.block_len_trees,
2962                       new_huffman_table);
2963          match result {
2964            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
2965            _ => break,
2966          }
2967          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_3;
2968          // No break, continue to next state
2969        }
2970        BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_3 => {
2971          let tree_offset = s.loop_counter * huffman::BROTLI_HUFFMAN_MAX_TABLE_SIZE as i32;
2972
2973          let mut block_length_out: u32 = 0;
2974          let ind_ret: (bool, u32);
2975          
2976          ind_ret = SafeReadBlockLengthIndex(&s.block_type_length_state.substate_read_block_length,
2977                                             s.block_type_length_state.block_length_index,
2978                                             fast_slice!((s.block_type_length_state.block_len_trees)
2979                                                           [tree_offset as usize;]),
2980                                             &mut s.br, local_input);
2981
2982          if !SafeReadBlockLengthFromIndex(&mut s.block_type_length_state,
2983                                           &mut s.br,
2984                                           &mut block_length_out,
2985                                           ind_ret,
2986                                           local_input) {
2987            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
2988            break;
2989          }
2990          fast_mut!((s.block_type_length_state.block_length)[s.loop_counter as usize]) =
2991            block_length_out;
2992          BROTLI_LOG_UINT!(s.block_type_length_state.block_length[s.loop_counter as usize]);
2993          s.loop_counter += 1;
2994          s.state = BrotliRunningState::BROTLI_STATE_HUFFMAN_CODE_0;
2995          break;
2996        }
2997        BrotliRunningState::BROTLI_STATE_METABLOCK_HEADER_2 => {
2998          let mut bits: u32 = 0;
2999          if (!bit_reader::BrotliSafeReadBits(&mut s.br, 6, &mut bits, local_input)) {
3000            result = BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT;
3001            break;
3002          }
3003          s.distance_postfix_bits = bits & bit_reader::BitMask(2);
3004          bits >>= 2;
3005          s.num_direct_distance_codes = NUM_DISTANCE_SHORT_CODES +
3006                                        (bits << s.distance_postfix_bits);
3007          BROTLI_LOG_UINT!(s.num_direct_distance_codes);
3008          BROTLI_LOG_UINT!(s.distance_postfix_bits);
3009          s.distance_postfix_mask = bit_reader::BitMask(s.distance_postfix_bits) as i32;
3010          s.context_modes = s.alloc_u8
3011            .alloc_cell(fast!((s.block_type_length_state.num_block_types)[0]) as usize);
3012          if (s.context_modes.slice().len() == 0) {
3013            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES;
3014            break;
3015          }
3016          s.loop_counter = 0;
3017          s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MODES;
3018          // No break, continue to next state
3019        }
3020        BrotliRunningState::BROTLI_STATE_CONTEXT_MODES => {
3021          result = ReadContextModes(&mut s, local_input);
3022          match result {
3023            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3024            _ => break,
3025          }
3026          s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1;
3027          // No break, continue to next state
3028        }
3029        BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_1 => {
3030          result =
3031            DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[0]) as usize) <<
3032                             kLiteralContextBits as usize,
3033                             false,
3034                             &mut s,
3035                             local_input);
3036          match result {
3037            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3038            _ => break,
3039          }
3040          DetectTrivialLiteralBlockTypes(s);
3041          s.state = BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2;
3042          // No break, continue to next state
3043        }
3044        BrotliRunningState::BROTLI_STATE_CONTEXT_MAP_2 => {
3045            let num_direct_codes =
3046              s.num_direct_distance_codes - NUM_DISTANCE_SHORT_CODES;
3047            let num_distance_codes = BROTLI_DISTANCE_ALPHABET_SIZE(
3048              s.distance_postfix_bits, num_direct_codes,
3049                (if s.large_window { BROTLI_LARGE_MAX_DISTANCE_BITS } else {
3050                    BROTLI_MAX_DISTANCE_BITS}));
3051            let max_distance_symbol = if s.large_window {
3052                BrotliMaxDistanceSymbol(
3053                    num_direct_codes, s.distance_postfix_bits)
3054            } else {
3055                num_distance_codes
3056            };
3057            result =
3058              DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[2]) as usize) <<
3059                               kDistanceContextBits as usize,
3060                               true,
3061                               s,
3062                               local_input);
3063            match result {
3064              BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3065              _ => break,
3066            }
3067            s.literal_hgroup.init(&mut s.alloc_u32,
3068                                  &mut s.alloc_hc,
3069                                  kNumLiteralCodes,
3070                                  kNumLiteralCodes,
3071                                  s.num_literal_htrees as u16);
3072            s.insert_copy_hgroup.init(&mut s.alloc_u32,
3073                                      &mut s.alloc_hc,
3074                                      kNumInsertAndCopyCodes,
3075                                      kNumInsertAndCopyCodes,
3076                                      fast!((s.block_type_length_state.num_block_types)[1]) as u16);
3077            s.distance_hgroup.init(&mut s.alloc_u32,
3078                                   &mut s.alloc_hc,
3079                                   num_distance_codes as u16,
3080                                   max_distance_symbol as u16,
3081                                   s.num_dist_htrees as u16);
3082            if (s.literal_hgroup.codes.slice().len() == 0 ||
3083                s.insert_copy_hgroup.codes.slice().len() == 0 ||
3084                s.distance_hgroup.codes.slice().len() == 0) {
3085              return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE);
3086            }
3087
3088          /*{
3089            let num_distance_codes: u32 = s.num_direct_distance_codes +
3090                                          (48u32 << s.distance_postfix_bits);
3091            result =
3092              DecodeContextMap((fast!((s.block_type_length_state.num_block_types)[2]) as usize) <<
3093                               kDistanceContextBits as usize,
3094                               true,
3095                               s,
3096                               local_input);
3097            match result {
3098              BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3099              _ => break,
3100            }
3101            s.literal_hgroup.init(&mut s.alloc_u32,
3102                                  &mut s.alloc_hc,
3103                                  kNumLiteralCodes,
3104                                  s.num_literal_htrees as u16);
3105            s.insert_copy_hgroup.init(&mut s.alloc_u32,
3106                                      &mut s.alloc_hc,
3107                                      kNumInsertAndCopyCodes,
3108                                      fast!((s.block_type_length_state.num_block_types)[1]) as u16);
3109            s.distance_hgroup.init(&mut s.alloc_u32,
3110                                   &mut s.alloc_hc,
3111                                   num_distance_codes as u16,
3112                                   s.num_dist_htrees as u16);
3113            if (s.literal_hgroup.codes.slice().len() == 0 ||
3114                s.insert_copy_hgroup.codes.slice().len() == 0 ||
3115                s.distance_hgroup.codes.slice().len() == 0) {
3116              return SaveErrorCode!(s, BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS);
3117            }
3118          }*/
3119          s.loop_counter = 0;
3120          s.state = BrotliRunningState::BROTLI_STATE_TREE_GROUP;
3121          // No break, continue to next state
3122        }
3123        BrotliRunningState::BROTLI_STATE_TREE_GROUP => {
3124          result = HuffmanTreeGroupDecode(s.loop_counter, &mut s, local_input);
3125          match result {
3126            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3127            _ => break,
3128          }
3129          s.loop_counter += 1;
3130          if (s.loop_counter >= 3) {
3131            PrepareLiteralDecoding(s);
3132            s.dist_context_map_slice_index = 0;
3133              /*
3134            s.context_map_slice_index = 0;
3135            let context_mode_index = fast!((s.block_type_length_state.block_type_rb)[1]);
3136            let context_mode = fast_slice!((s.context_modes)[context_mode_index as usize]);
3137            s.context_lookup = &kContextLookup[context_mode as usize & 3];
3138               */
3139            s.htree_command_index = 0;
3140            // look it up each time s.literal_htree=s.literal_hgroup.htrees[s.literal_htree_index];
3141            s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
3142          }
3143          break;
3144        }
3145        BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN |
3146        BrotliRunningState::BROTLI_STATE_COMMAND_INNER |
3147        BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS |
3148        BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY => {
3149          result = ProcessCommands(s, local_input);
3150          if let BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT = result {
3151            result = SafeProcessCommands(s, local_input)
3152          }
3153          break;
3154        }
3155        BrotliRunningState::BROTLI_STATE_COMMAND_INNER_WRITE |
3156        BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1 |
3157        BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2 => {
3158          let (xresult, _) = WriteRingBuffer(&mut available_out,
3159                                             Some(&mut output),
3160                                             &mut output_offset,
3161                                             &mut total_out,
3162                                             false,
3163                                             &mut s);
3164          result = xresult;
3165          match result {
3166            BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3167            _ => break,
3168          }
3169          WrapRingBuffer(s);
3170          if s.ringbuffer_size == 1 << s.window_bits {
3171            s.max_distance = s.max_backward_distance;
3172          }
3173          match s.state {
3174            BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_1 => {
3175              if (s.meta_block_remaining_len <= 0) {
3176                // Next metablock, if any
3177                s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
3178              } else {
3179                s.state = BrotliRunningState::BROTLI_STATE_COMMAND_BEGIN;
3180              }
3181              break;
3182            }
3183            BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRITE_2 => {
3184              s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_WRAP_COPY;
3185            }
3186            _ => {
3187              // BROTLI_STATE_COMMAND_INNER_WRITE
3188              if (s.loop_counter == 0) {
3189                if (s.meta_block_remaining_len <= 0) {
3190                  s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_DONE;
3191                } else {
3192                  s.state = BrotliRunningState::BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
3193                }
3194                break;
3195              }
3196              s.state = BrotliRunningState::BROTLI_STATE_COMMAND_INNER;
3197            }
3198          }
3199          break;
3200        }
3201        BrotliRunningState::BROTLI_STATE_METABLOCK_DONE => {
3202          s.BrotliStateCleanupAfterMetablock();
3203          if (s.is_last_metablock == 0) {
3204            s.state = BrotliRunningState::BROTLI_STATE_METABLOCK_BEGIN;
3205            break;
3206          }
3207          if (!bit_reader::BrotliJumpToByteBoundary(&mut s.br)) {
3208            result = BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_2;
3209          }
3210          if (s.buffer_length == 0) {
3211            bit_reader::BrotliBitReaderUnload(&mut s.br);
3212            *available_in = s.br.avail_in as usize;
3213            *input_offset = s.br.next_in as usize;
3214          }
3215          s.state = BrotliRunningState::BROTLI_STATE_DONE;
3216          // No break, continue to next state
3217        }
3218        BrotliRunningState::BROTLI_STATE_DONE => {
3219          if (s.ringbuffer.slice().len() != 0) {
3220            let (xresult, _) = WriteRingBuffer(&mut available_out,
3221                                               Some(&mut output),
3222                                               &mut output_offset,
3223                                               &mut total_out,
3224                                               true,
3225                                               &mut s);
3226            result = xresult;
3227            match result {
3228              BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => {}
3229              _ => break,
3230            }
3231          }
3232          return SaveErrorCode!(s, result);
3233        }
3234      }
3235    }
3236  }
3237
3238  SaveErrorCode!(s, result)
3239}
3240