Skip to main content

brotli_decompressor/
state.rs

1#![allow(non_camel_case_types)]
2#![allow(non_snake_case)]
3#![allow(non_upper_case_globals)]
4
5
6use alloc;
7use core;
8use context::kContextLookup;
9use bit_reader::{BrotliBitReader, BrotliGetAvailableBits, BrotliInitBitReader};
10use huffman::{BROTLI_HUFFMAN_MAX_CODE_LENGTH, BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE,
11              BROTLI_HUFFMAN_MAX_SIZE_272, HuffmanCode, HuffmanTreeGroup};
12use alloc::SliceWrapper;
13use alloc::SliceWrapperMut;
14use shared_dictionary;
15use shared_dictionary::{BrotliSharedDictionary, TRANSFORM_LIST_STRIDE, WORD_LIST_STRIDE};
16
17#[allow(dead_code)]
18pub enum WhichTreeGroup {
19  LITERAL,
20  INSERT_COPY,
21  DISTANCE,
22}
23// Options for BrotliState::set_parameter and the C API's
24// BrotliDecoderSetParameter, with the C header's values.
25#[repr(C)]
26#[derive(Clone,Copy, Debug)]
27pub enum BrotliDecoderParameter {
28  BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION = 0,
29  BROTLI_DECODER_PARAM_LARGE_WINDOW = 1,
30}
31#[repr(C)]
32#[derive(Clone,Copy, Debug)]
33pub enum BrotliDecoderErrorCode{
34  BROTLI_DECODER_NO_ERROR = 0,
35  /* Same as BrotliDecoderResult values */
36  BROTLI_DECODER_SUCCESS = 1,
37  BROTLI_DECODER_NEEDS_MORE_INPUT = 2,
38  BROTLI_DECODER_NEEDS_MORE_OUTPUT = 3,
39
40  /* Errors caused by invalid input */
41  BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE = -1,
42  BROTLI_DECODER_ERROR_FORMAT_RESERVED = -2,
43  BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE = -3,
44  BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET = -4,
45  BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME = -5,
46  BROTLI_DECODER_ERROR_FORMAT_CL_SPACE = -6,
47  BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE = -7,
48  BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT = -8,
49  BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1 = -9,
50  BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2 = -10,
51  BROTLI_DECODER_ERROR_FORMAT_TRANSFORM = -11,
52  BROTLI_DECODER_ERROR_FORMAT_DICTIONARY = -12,
53  BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS = -13,
54  BROTLI_DECODER_ERROR_FORMAT_PADDING_1 = -14,
55  BROTLI_DECODER_ERROR_FORMAT_PADDING_2 = -15,
56  BROTLI_DECODER_ERROR_FORMAT_DISTANCE = -16,
57  BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH = -17,
58
59  BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY = -18,
60  BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET = -19,
61  BROTLI_DECODER_ERROR_INVALID_ARGUMENTS = -20,
62
63  /* Memory allocation problems */
64  BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES = -21,
65  /* Literal = insert and distance trees together */
66  BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS = -22,
67  /* -23..-24 codes are reserved for distinct tree groups */
68  BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP = -25,
69  BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1 = -26,
70  BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2 = -27,
71  /* -28..-29 codes are reserved for dynamic ring-buffer allocation */
72  BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES = -30,
73
74  /* "Impossible" states */
75  BROTLI_DECODER_ERROR_UNREACHABLE = -31,
76}
77
78#[derive(Debug)]
79pub enum BrotliRunningState {
80  BROTLI_STATE_UNINITED,
81  BROTLI_STATE_LARGE_WINDOW_BITS,
82  BROTLI_STATE_INITIALIZE,
83  BROTLI_STATE_METABLOCK_BEGIN,
84  BROTLI_STATE_METABLOCK_HEADER,
85  BROTLI_STATE_METABLOCK_HEADER_2,
86  BROTLI_STATE_CONTEXT_MODES,
87  BROTLI_STATE_COMMAND_BEGIN,
88  BROTLI_STATE_COMMAND_INNER,
89  BROTLI_STATE_COMMAND_POST_DECODE_LITERALS,
90  BROTLI_STATE_COMMAND_POST_WRAP_COPY,
91  BROTLI_STATE_UNCOMPRESSED,
92  BROTLI_STATE_METADATA,
93  BROTLI_STATE_COMMAND_INNER_WRITE,
94  BROTLI_STATE_METABLOCK_DONE,
95  BROTLI_STATE_COMMAND_POST_WRITE_1,
96  BROTLI_STATE_COMMAND_POST_WRITE_2,
97  BROTLI_STATE_HUFFMAN_CODE_0,
98  BROTLI_STATE_HUFFMAN_CODE_1,
99  BROTLI_STATE_HUFFMAN_CODE_2,
100  BROTLI_STATE_HUFFMAN_CODE_3,
101  BROTLI_STATE_CONTEXT_MAP_1,
102  BROTLI_STATE_CONTEXT_MAP_2,
103  BROTLI_STATE_TREE_GROUP,
104  BROTLI_STATE_DONE,
105}
106
107pub enum BrotliRunningMetablockHeaderState {
108  BROTLI_STATE_METABLOCK_HEADER_NONE,
109  BROTLI_STATE_METABLOCK_HEADER_EMPTY,
110  BROTLI_STATE_METABLOCK_HEADER_NIBBLES,
111  BROTLI_STATE_METABLOCK_HEADER_SIZE,
112  BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED,
113  BROTLI_STATE_METABLOCK_HEADER_RESERVED,
114  BROTLI_STATE_METABLOCK_HEADER_BYTES,
115  BROTLI_STATE_METABLOCK_HEADER_METADATA,
116}
117pub enum BrotliRunningUncompressedState {
118  BROTLI_STATE_UNCOMPRESSED_NONE,
119  BROTLI_STATE_UNCOMPRESSED_WRITE,
120}
121
122pub enum BrotliRunningTreeGroupState {
123  BROTLI_STATE_TREE_GROUP_NONE,
124  BROTLI_STATE_TREE_GROUP_LOOP,
125}
126
127pub enum BrotliRunningContextMapState {
128  BROTLI_STATE_CONTEXT_MAP_NONE,
129  BROTLI_STATE_CONTEXT_MAP_READ_PREFIX,
130  BROTLI_STATE_CONTEXT_MAP_HUFFMAN,
131  BROTLI_STATE_CONTEXT_MAP_DECODE,
132  BROTLI_STATE_CONTEXT_MAP_TRANSFORM,
133}
134
135pub enum BrotliRunningHuffmanState {
136  BROTLI_STATE_HUFFMAN_NONE,
137  BROTLI_STATE_HUFFMAN_SIMPLE_SIZE,
138  BROTLI_STATE_HUFFMAN_SIMPLE_READ,
139  BROTLI_STATE_HUFFMAN_SIMPLE_BUILD,
140  BROTLI_STATE_HUFFMAN_COMPLEX,
141  BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS,
142}
143
144pub enum BrotliRunningDecodeUint8State {
145  BROTLI_STATE_DECODE_UINT8_NONE,
146  BROTLI_STATE_DECODE_UINT8_SHORT,
147  BROTLI_STATE_DECODE_UINT8_LONG,
148}
149
150pub enum BrotliRunningReadBlockLengthState {
151  BROTLI_STATE_READ_BLOCK_LENGTH_NONE,
152  BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX,
153}
154
155pub const kLiteralContextBits: usize = 6;
156
157// Maximum number of compound dictionary chunks that may be attached to a
158// decoder instance, per the shared-brotli draft
159// (https://datatracker.ietf.org/doc/draft-vandevenne-shared-brotli-format/).
160pub const SHARED_BROTLI_MAX_COMPOUND_DICTS: usize = 15;
161// Practical limit for the total size of attached raw dictionaries; matches
162// SHARED_BROTLI_MAX_RAW_DICT_SIZE in the C implementation.
163#[cfg(target_pointer_width = "64")]
164pub const SHARED_BROTLI_MAX_RAW_DICT_SIZE: usize = 1usize << 31;
165#[cfg(not(target_pointer_width = "64"))]
166pub const SHARED_BROTLI_MAX_RAW_DICT_SIZE: usize = 1usize << 27;
167
168// Backing store for an attached dictionary: either memory this decoder owns
169// (allocated through AllocU8, freed on cleanup) or memory the caller owns and
170// has promised to keep alive and unmodified for as long as the decoder lives.
171//
172// The borrowed variant exists so that the FFI can honor the C API's contract
173// -- "Attached dictionary ownership is not transferred. Data provided to this
174// method should be kept accessible until decoding is finished and decoder
175// instance is destroyed." (c/include/brotli/decode.h) -- which lets many
176// decoder instances share one dictionary image at zero marginal cost instead
177// of each holding a private copy.
178#[allow(dead_code)]
179pub enum MaybeOwnedSlice<AllocU8: alloc::Allocator<u8>> {
180  Owned(AllocU8::AllocatedMemory),
181  // The 'static here is a lie maintained by the unsafe constructors below:
182  // the referent only has to outlive the BrotliState that holds it. It is
183  // spelled 'static rather than as a raw pointer so that BrotliState keeps
184  // its automatic Send/Sync.
185  Borrowed(&'static [u8]),
186  // A dictionary of this length whose bytes are lent to every
187  // BrotliDecompressStreamWithDictionary call instead.
188  External(usize),
189}
190
191impl<AllocU8: alloc::Allocator<u8>> Default for MaybeOwnedSlice<AllocU8> {
192  fn default() -> Self {
193    MaybeOwnedSlice::Owned(AllocU8::AllocatedMemory::default())
194  }
195}
196
197impl<AllocU8: alloc::Allocator<u8>> alloc::SliceWrapper<u8> for MaybeOwnedSlice<AllocU8> {
198  fn slice(&self) -> &[u8] {
199    match *self {
200      MaybeOwnedSlice::Owned(ref mem) => mem.slice(),
201      MaybeOwnedSlice::Borrowed(data) => data,
202      MaybeOwnedSlice::External(_) => &[],
203    }
204  }
205}
206
207// Sentinel stored in BrotliDecoderCompoundDictionary::block_bits while the
208// block map is stale, i.e. a marker rather than a shift amount. Real shift
209// amounts computed by EnsureCompoundDictionaryInitialized are in 0..=23
210// (total_size is capped at SHARED_BROTLI_MAX_RAW_DICT_SIZE), so this value can
211// never collide with one. The C implementation uses -1 for the same purpose;
212// the field is unsigned here.
213pub const COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED: u32 = 255;
214
215
216pub trait BrotliMetadataCallback {
217    fn start(&mut self, _size: usize) {}
218    fn chunk(&mut self, _data: &[u8]) {}
219}
220
221// LZ77 prefix ("compound") dictionaries attached to the decoder. Unlike the
222// historical approach of copying the dictionary into the ring buffer, chunks
223// are kept in their own buffers and referenced by backward distances in
224// (max_distance, max_distance + total_size], so they stay addressable even
225// after the ring buffer wraps (issue #42).
226pub struct BrotliDecoderCompoundDictionary<AllocU8: alloc::Allocator<u8>> {
227  pub num_chunks: usize,
228  pub total_size: usize,
229  // Map from address >> block_bits to the first chunk that might contain that
230  // address; COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED means "not yet
231  // computed".
232  pub block_bits: u32,
233  pub block_map: [u8; 256],
234  // chunk_offsets[i] is the address of the first byte of chunk i;
235  // chunk_offsets[num_chunks] == total_size.
236  pub chunk_offsets: [u32; SHARED_BROTLI_MAX_COMPOUND_DICTS + 1],
237  pub chunks: [MaybeOwnedSlice<AllocU8>; SHARED_BROTLI_MAX_COMPOUND_DICTS],
238  // Cursor for an in-progress copy from the dictionary into the ring buffer:
239  // a single copy command may be interrupted to flush the ring buffer.
240  pub br_index: usize,
241  pub br_offset: usize,
242  pub br_length: usize,
243  pub br_copied: usize,
244}
245
246impl<AllocU8: alloc::Allocator<u8>> Default for BrotliDecoderCompoundDictionary<AllocU8> {
247  fn default() -> Self {
248    BrotliDecoderCompoundDictionary::<AllocU8> {
249      num_chunks: 0,
250      total_size: 0,
251      block_bits: COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED,
252      block_map: [0; 256],
253      chunk_offsets: [0; SHARED_BROTLI_MAX_COMPOUND_DICTS + 1],
254      chunks: Default::default(),
255      br_index: 0,
256      br_offset: 0,
257      br_length: 0,
258      br_copied: 0,
259    }
260  }
261}
262
263pub struct BlockTypeAndLengthState<AllocHC: alloc::Allocator<HuffmanCode>> {
264  pub substate_read_block_length: BrotliRunningReadBlockLengthState,
265  pub num_block_types: [u32; 3],
266  pub block_length_index: u32,
267  pub block_length: [u32; 3],
268  pub block_type_trees: AllocHC::AllocatedMemory,
269  pub block_len_trees: AllocHC::AllocatedMemory,
270  pub block_type_rb: [u32; 6],
271}
272
273pub struct BrotliState<AllocU8: alloc::Allocator<u8>,
274                       AllocU32: alloc::Allocator<u32>,
275                       AllocHC: alloc::Allocator<HuffmanCode>>
276{
277  pub state: BrotliRunningState,
278
279  // This counter is reused for several disjoint loops.
280  pub loop_counter: i32,
281  pub br: BrotliBitReader,
282  pub alloc_u8: AllocU8,
283  pub alloc_u32: AllocU32,
284  pub alloc_hc: AllocHC,
285  // void* memory_manager_opaque,
286  pub buffer: [u8; 8],
287  pub buffer_length: u32,
288  pub pos: i32,
289  pub max_backward_distance: i32,
290  pub max_distance: i32,
291  pub ringbuffer_size: i32,
292  pub ringbuffer_mask: i32,
293  // Size the ring buffer must grow to before the current metablock is
294  // decoded, as computed from its header by BrotliCalculateRingBufferSize.
295  // It differs from ringbuffer_size only until BrotliEnsureRingBuffer runs.
296  pub(crate) new_ringbuffer_size: i32,
297  // Size of the pool that alloc_u8 draws from when it is a fixed pool that
298  // never merges freed blocks, as in brotli_decode_prealloc; 0 otherwise.
299  // Growing the ring buffer takes up to twice the window from such a pool, so
300  // BrotliCalculateRingBufferSize then sizes it to never need more of the pool
301  // than before the ring buffer grew on demand.
302  pub(crate) u8_pool_size: usize,
303  // Smallest size the ring buffer starts from, as set by
304  // set_initial_ring_buffer_size; 0 for the default.
305  pub(crate) initial_ringbuffer_size: u32,
306  // Output capacity of a one-shot decode. This is only a speculative sizing
307  // hint: a caller may provide much more space than the stream needs.
308  pub(crate) one_shot_output_size: u32,
309  pub dist_rb_idx: i32,
310  pub dist_rb: [i32; 4],
311  pub ringbuffer: AllocU8::AllocatedMemory,
312  // pub ringbuffer_end : usize,
313  pub htree_command_index: u16,
314  pub context_lookup: &'static [u8;512],
315  pub context_map_slice_index: usize,
316  pub dist_context_map_slice_index: usize,
317
318  pub sub_loop_counter: u32,
319
320  // This ring buffer holds a few past copy distances that will be used by */
321  // some special distance codes.
322  pub literal_hgroup: HuffmanTreeGroup<AllocU32, AllocHC>,
323  pub insert_copy_hgroup: HuffmanTreeGroup<AllocU32, AllocHC>,
324  pub distance_hgroup: HuffmanTreeGroup<AllocU32, AllocHC>,
325  // This is true if the literal context map histogram type always matches the
326  // block type. It is then not needed to keep the context (faster decoding).
327  pub trivial_literal_context: i32,
328  // Distance context is actual after command is decoded and before distance
329  // is computed. After distance computation it is used as a temporary variable
330  pub distance_context: i32,
331  pub meta_block_remaining_len: i32,
332  pub block_type_length_state: BlockTypeAndLengthState<AllocHC>,
333  pub distance_postfix_bits: u32,
334  pub num_direct_distance_codes: u32,
335  pub distance_postfix_mask: i32,
336  pub num_dist_htrees: u32,
337  pub dist_context_map: AllocU8::AllocatedMemory,
338  // NOT NEEDED? the index below seems to supersede it pub literal_htree : AllocHC::AllocatedMemory,
339  pub literal_htree_index: u8,
340  pub dist_htree_index: u8,
341  pub large_window: bool,
342  pub(crate) canny_ringbuffer_allocation: bool,
343  pub should_wrap_ringbuffer: bool,
344  pub error_code: BrotliDecoderErrorCode,
345  pub repeat_code_len: u32,
346  pub prev_code_len: u32,
347
348  pub copy_length: i32,
349  pub distance_code: i32,
350
351  // For partial write operations
352  // u64, not usize: as usize these would wrap after 4GiB of output on a 32-bit
353  // target, and WriteRingBuffer works from their difference.
354  pub rb_roundtrips: u64, // How many times we went around the ringbuffer
355  pub partial_pos_out: u64, // How much output to the user in total (<= rb)
356
357  // For ReadHuffmanCode
358  pub symbol: u32,
359  pub repeat: u32,
360  pub space: u32,
361
362  pub table: [HuffmanCode; 32],
363  // List of of symbol chains.
364  pub symbol_lists_index: usize, // AllocU16::AllocatedMemory,
365  // Storage from symbol_lists.
366  pub symbols_lists_array: [u16; BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1 +
367                                 BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE],
368  // Tails of symbol chains.
369  pub next_symbol: [i32; 32],
370  pub code_length_code_lengths: [u8; 18],
371  // Population counts for the code lengths
372  pub code_length_histo: [u16; 16],
373
374  // For HuffmanTreeGroupDecode
375  pub htree_index: i32,
376  pub htree_next_offset: u32,
377
378  // For DecodeContextMap
379  pub context_index: u32,
380  pub max_run_length_prefix: u32,
381  pub code: u32,
382  // always pre-allocated on state creation
383  pub context_map_table: AllocHC::AllocatedMemory,
384
385  // For InverseMoveToFrontTransform
386  pub mtf_upper_bound: u32,
387  pub mtf_or_error_string: Result<[u8; 256], [u8; 256]>,
388
389  // For custom dictionaries
390  pub custom_dict: AllocU8::AllocatedMemory,
391  pub compound_dictionary: BrotliDecoderCompoundDictionary<AllocU8>,
392  // Custom word/transform lists from an attached serialized shared
393  // dictionary; selects the built-in static dictionary when empty.
394  pub dictionary: BrotliSharedDictionary<AllocU8, AllocU32>,
395  // less used attributes are in the end of this struct */
396  // States inside function calls
397  pub substate_metablock_header: BrotliRunningMetablockHeaderState,
398  pub substate_tree_group: BrotliRunningTreeGroupState,
399  pub substate_context_map: BrotliRunningContextMapState,
400  pub substate_uncompressed: BrotliRunningUncompressedState,
401  pub substate_huffman: BrotliRunningHuffmanState,
402  pub substate_decode_uint8: BrotliRunningDecodeUint8State,
403
404  pub is_last_metablock: u8,
405  pub is_uncompressed: u8,
406  pub is_metadata: u8,
407  pub size_nibbles: u8,
408  pub window_bits: u32,
409
410  pub num_literal_htrees: u32,
411  pub context_map: AllocU8::AllocatedMemory,
412  pub context_modes: AllocU8::AllocatedMemory,
413  pub trivial_literal_contexts: [u32; 8],
414}
415macro_rules! make_brotli_state {
416 ($alloc_u8 : expr, $alloc_u32 : expr, $alloc_hc : expr, $custom_dict : expr) => (BrotliState::<AllocU8, AllocU32, AllocHC>{
417            state : BrotliRunningState::BROTLI_STATE_UNINITED,
418            loop_counter : 0,
419            br : BrotliBitReader::default(),
420            alloc_u8 : $alloc_u8,
421            alloc_u32 : $alloc_u32,
422            alloc_hc : $alloc_hc,
423            buffer : [0u8; 8],
424            buffer_length : 0,
425            pos : 0,
426            max_backward_distance : 0,
427            max_distance : 0,
428            ringbuffer_size : 0,
429            ringbuffer_mask: 0,
430            new_ringbuffer_size : 0,
431            u8_pool_size : 0,
432            initial_ringbuffer_size : 0,
433            one_shot_output_size : 0,
434            dist_rb_idx : 0,
435            dist_rb : [16, 15, 11, 4],
436            ringbuffer : AllocU8::AllocatedMemory::default(),
437            htree_command_index : 0,
438            context_lookup : &kContextLookup[0],
439            context_map_slice_index : 0,
440            dist_context_map_slice_index : 0,
441            sub_loop_counter : 0,
442
443            literal_hgroup : HuffmanTreeGroup::<AllocU32, AllocHC>::default(),
444            insert_copy_hgroup : HuffmanTreeGroup::<AllocU32, AllocHC>::default(),
445            distance_hgroup : HuffmanTreeGroup::<AllocU32, AllocHC>::default(),
446            trivial_literal_context : 0,
447            distance_context : 0,
448            meta_block_remaining_len : 0,
449            block_type_length_state : BlockTypeAndLengthState::<AllocHC> {
450              block_length_index : 0,
451              block_length : [0; 3],
452              num_block_types : [0;3],
453              block_type_rb: [0;6],
454              substate_read_block_length : BrotliRunningReadBlockLengthState::BROTLI_STATE_READ_BLOCK_LENGTH_NONE,
455              block_type_trees : AllocHC::AllocatedMemory::default(),
456              block_len_trees : AllocHC::AllocatedMemory::default(),
457            },
458            distance_postfix_bits : 0,
459            num_direct_distance_codes : 0,
460            distance_postfix_mask : 0,
461            num_dist_htrees : 0,
462            dist_context_map : AllocU8::AllocatedMemory::default(),
463            //// not needed literal_htree : AllocHC::AllocatedMemory::default(),
464            literal_htree_index : 0,
465            dist_htree_index : 0,
466            repeat_code_len : 0,
467            prev_code_len : 0,
468            copy_length : 0,
469            distance_code : 0,
470            rb_roundtrips : 0,  /* How many times we went around the ringbuffer */
471            partial_pos_out : 0,  /* How much output to the user in total (<= rb) */
472            symbol : 0,
473            repeat : 0,
474            space : 0,
475            table : [HuffmanCode::default(); 32],
476            //symbol_lists: AllocU16::AllocatedMemory::default(),
477            symbol_lists_index : BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1,
478            symbols_lists_array : [0;BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1 +
479                              BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE],
480            next_symbol : [0; 32],
481            code_length_code_lengths : [0; 18],
482            code_length_histo : [0; 16],
483            htree_index : 0,
484            htree_next_offset : 0,
485
486            /* For DecodeContextMap */
487           context_index : 0,
488           max_run_length_prefix : 0,
489           code : 0,
490           context_map_table : AllocHC::AllocatedMemory::default(),
491
492           /* For InverseMoveToFrontTransform */
493           mtf_upper_bound : 255,
494           mtf_or_error_string : Ok([0; 256]),
495
496           /* For custom dictionaries */
497           custom_dict : $custom_dict,
498           compound_dictionary : BrotliDecoderCompoundDictionary::default(),
499           dictionary : BrotliSharedDictionary::default(),
500           /* less used attributes are in the end of this struct */
501           /* States inside function calls */
502           substate_metablock_header : BrotliRunningMetablockHeaderState::BROTLI_STATE_METABLOCK_HEADER_NONE,
503           substate_tree_group : BrotliRunningTreeGroupState::BROTLI_STATE_TREE_GROUP_NONE,
504           substate_context_map : BrotliRunningContextMapState::BROTLI_STATE_CONTEXT_MAP_NONE,
505           substate_uncompressed : BrotliRunningUncompressedState::BROTLI_STATE_UNCOMPRESSED_NONE,
506           substate_huffman : BrotliRunningHuffmanState::BROTLI_STATE_HUFFMAN_NONE,
507           substate_decode_uint8 : BrotliRunningDecodeUint8State::BROTLI_STATE_DECODE_UINT8_NONE,
508
509           is_last_metablock : 0,
510           is_uncompressed : 0,
511           is_metadata : 0,
512           size_nibbles : 0,
513           window_bits : 0,
514           large_window: false,
515           canny_ringbuffer_allocation: true,
516           should_wrap_ringbuffer: false,
517           error_code: BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS,
518           num_literal_htrees : 0,
519           context_map : AllocU8::AllocatedMemory::default(),
520           context_modes : AllocU8::AllocatedMemory::default(),
521           trivial_literal_contexts : [0u32; 8],
522        }
523    );
524}
525impl <'brotli_state,
526      AllocU8 : alloc::Allocator<u8>,
527      AllocU32 : alloc::Allocator<u32>,
528      AllocHC : alloc::Allocator<HuffmanCode> > BrotliState<AllocU8, AllocU32, AllocHC> {
529    pub fn new(alloc_u8 : AllocU8,
530           alloc_u32 : AllocU32,
531           alloc_hc : AllocHC) -> Self{
532        let mut retval = make_brotli_state!(alloc_u8, alloc_u32, alloc_hc, AllocU8::AllocatedMemory::default());
533        retval.large_window = true;
534        BrotliInitBitReader(&mut retval.br);
535        retval
536    }
537    pub fn new_with_custom_dictionary(alloc_u8 : AllocU8,
538           alloc_u32 : AllocU32,
539           alloc_hc : AllocHC,
540           custom_dict: AllocU8::AllocatedMemory) -> Self{
541        let custom_dict_len = custom_dict.slice().len();
542        let mut retval = make_brotli_state!(alloc_u8, alloc_u32, alloc_hc, custom_dict);
543        retval.large_window =  true;
544        BrotliInitBitReader(&mut retval.br);
545        // The dictionary becomes the furthest compound dictionary chunk;
546        // any subsequently attach_dictionary'd ones are nearer in distance
547        // space.
548        if custom_dict_len != 0 && custom_dict_len <= SHARED_BROTLI_MAX_RAW_DICT_SIZE {
549            let dict = core::mem::replace(&mut retval.custom_dict,
550                                          AllocU8::AllocatedMemory::default());
551            // A fresh state has no chunks, so the size check above makes this
552            // infallible. Oversized dictionaries remain in `custom_dict` and
553            // are rejected through the normal decoder error path at startup.
554            let attached = retval.attach_compound_dictionary_chunk(MaybeOwnedSlice::Owned(dict));
555            debug_assert!(attached);
556        }
557        retval
558    }
559    pub fn new_strict(alloc_u8 : AllocU8,
560           alloc_u32 : AllocU32,
561           alloc_hc : AllocHC) -> Self{
562        let mut retval = make_brotli_state!(alloc_u8, alloc_u32, alloc_hc, AllocU8::AllocatedMemory::default());
563        retval.large_window =  false;
564        BrotliInitBitReader(&mut retval.br);
565        retval
566    }
567    // Sets a decoder parameter, the equivalent of the C API
568    // BrotliDecoderSetParameter: a nonzero value disables ring buffer
569    // reallocation (the whole window is allocated at once) or accepts
570    // large-window streams. Allowed only before any compressed data has been
571    // processed; returns false, changing nothing, afterwards.
572    pub fn set_parameter(self : &mut Self,
573                         param: BrotliDecoderParameter,
574                         value: u32) -> bool {
575        match self.state {
576            BrotliRunningState::BROTLI_STATE_UNINITED => {},
577            _ => return false,
578        }
579        match param {
580            BrotliDecoderParameter::BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION =>
581                self.canny_ringbuffer_allocation = value == 0,
582            BrotliDecoderParameter::BROTLI_DECODER_PARAM_LARGE_WINDOW =>
583                self.large_window = value != 0,
584        }
585        true
586    }
587    // Sets the smallest ring buffer the decoder starts from, rounded up to a
588    // power of two of at least 32 bytes and capped at the stream's window,
589    // which is only known once decoding starts; 0 restores the default of
590    // 1 KiB. With u32::MAX the whole window is allocated at once and never
591    // regrown, so a u8 allocator that is a fixed pool that never merges freed
592    // blocks needs only the window from it, rather than up to twice that. If
593    // the stream's first metablock of data is its last, the ring buffer is
594    // still sized to just hold it, as it is for small or incompressible
595    // input, which encoders store as one uncompressed metablock and an
596    // empty last one, when that empty metablock is already in the input as
597    // the uncompressed one starts. Disabling ring buffer reallocation with
598    // set_parameter overrides this. Allowed only before any compressed data
599    // has been processed; returns false, changing nothing, afterwards.
600    pub fn set_initial_ring_buffer_size(self : &mut Self, size: u32) -> bool {
601        match self.state {
602            BrotliRunningState::BROTLI_STATE_UNINITED => {},
603            _ => return false,
604        }
605        self.initial_ringbuffer_size = size;
606        true
607    }
608    // Attaches a raw LZ77 prefix dictionary, the equivalent of the C API
609    // BrotliDecoderAttachDictionary with BROTLI_SHARED_DICTIONARY_RAW.
610    // Up to SHARED_BROTLI_MAX_COMPOUND_DICTS dictionaries may be attached,
611    // only before any compressed data has been processed. The most recently
612    // attached dictionary is the closest in backward-distance space.
613    // Returns false (and frees the dictionary) if it cannot be attached.
614    pub fn attach_dictionary(self : &mut Self,
615                             dict: AllocU8::AllocatedMemory) -> bool {
616        self.attach_dictionary_chunk(MaybeOwnedSlice::Owned(dict))
617    }
618    // As attach_dictionary, but the decoder only borrows `dict`: nothing is
619    // copied and nothing is freed on cleanup, so one dictionary image can back
620    // any number of concurrent decoder instances.
621    //
622    // The 'static bound is what makes this safe without a lifetime parameter
623    // on BrotliState: the data provably outlives the decoder. Callers holding
624    // a shorter-lived buffer can leak it (Box::leak, a leaked mmap) to obtain
625    // one, or use attach_dictionary and pay for the copy.
626    pub fn attach_dictionary_borrowed(self : &mut Self, dict: &'static [u8]) -> bool {
627        self.attach_dictionary_chunk(MaybeOwnedSlice::Borrowed(dict))
628    }
629    // As attach_dictionary_borrowed, for a dictionary of any lifetime: only
630    // its size is attached, and its bytes are lent to every
631    // BrotliDecompressStreamWithDictionary call instead, so they only have to
632    // outlive each call, not the decoder. At most one dictionary can be
633    // attached this way.
634    pub fn attach_external_dictionary(self : &mut Self, size: usize) -> bool {
635        if self.external_dictionary_len() != 0 {
636            return false;
637        }
638        self.attach_dictionary_chunk(MaybeOwnedSlice::External(size))
639    }
640    // The size of the external dictionary every call must lend, or 0.
641    pub(crate) fn external_dictionary_len(&self) -> usize {
642        let addon = &self.compound_dictionary;
643        for chunk in addon.chunks.iter().take(addon.num_chunks) {
644            if let MaybeOwnedSlice::External(len) = *chunk {
645                return len;
646            }
647        }
648        0
649    }
650    fn attach_dictionary_chunk(self : &mut Self,
651                               dict: MaybeOwnedSlice<AllocU8>) -> bool {
652        match self.state {
653            BrotliRunningState::BROTLI_STATE_UNINITED => {},
654            _ => {
655                self.free_chunk(dict);
656                return false;
657            },
658        }
659        self.attach_compound_dictionary_chunk(dict)
660    }
661    // Attaches a serialized shared dictionary (magic bytes 0x91 0x00), the
662    // equivalent of the C API BrotliDecoderAttachDictionary with
663    // BROTLI_SHARED_DICTIONARY_SERIALIZED. An embedded LZ77 prefix dictionary
664    // becomes a compound dictionary chunk; custom word lists and transform
665    // lists replace the built-in static dictionary. Only one attached
666    // dictionary may carry custom word/transform lists. Allowed only before
667    // any compressed data has been processed. Returns false (and frees the
668    // dictionary) on failure.
669    pub fn attach_serialized_dictionary(self : &mut Self,
670                                        dict_data: AllocU8::AllocatedMemory) -> bool {
671        self.attach_serialized_dictionary_chunk(MaybeOwnedSlice::Owned(dict_data))
672    }
673    // As attach_serialized_dictionary, but the decoder only borrows
674    // `dict_data`: the blob is referenced in place and an embedded LZ77
675    // prefix becomes a borrowed chunk rather than a copy. Note that custom
676    // word/transform lists keep referencing the blob for the whole decode,
677    // not just for parsing, which is why the 'static bound covers both.
678    pub fn attach_serialized_dictionary_borrowed(self : &mut Self,
679                                                 dict_data: &'static [u8]) -> bool {
680        self.attach_serialized_dictionary_chunk(MaybeOwnedSlice::Borrowed(dict_data))
681    }
682    fn attach_serialized_dictionary_chunk(self : &mut Self,
683                                          dict_data: MaybeOwnedSlice<AllocU8>) -> bool {
684        match self.state {
685            BrotliRunningState::BROTLI_STATE_UNINITED => {},
686            _ => {
687                self.free_chunk(dict_data);
688                return false;
689            },
690        }
691        let summary = match shared_dictionary::dry_parse_serialized_dictionary(
692            dict_data.slice()) {
693            Ok(summary) => summary,
694            Err(()) => {
695                self.free_chunk(dict_data);
696                return false;
697            },
698        };
699        let is_custom = summary.num_word_lists != 0 || summary.num_transform_lists != 0;
700        // Cannot combine different custom static dictionaries, only prefix
701        // dictionaries.
702        if is_custom && self.dictionary.is_custom() {
703            self.free_chunk(dict_data);
704            return false;
705        }
706        // If the blob itself is borrowed, an embedded prefix can be handed to
707        // the compound dictionary as a subslice of it; both are shared
708        // references to caller-owned memory, so no copy is needed.
709        let borrowed_blob: Option<&'static [u8]> = match dict_data {
710            MaybeOwnedSlice::Borrowed(data) => Some(data),
711            MaybeOwnedSlice::Owned(_) | MaybeOwnedSlice::External(_) => None,
712        };
713        let mut parsed = BrotliSharedDictionary::<AllocU8, AllocU32>::default();
714        if is_custom {
715            let arena_size = summary.num_word_lists as usize * WORD_LIST_STRIDE +
716                             summary.num_transform_lists as usize * TRANSFORM_LIST_STRIDE;
717            parsed.meta = self.alloc_u32.alloc_cell(arena_size);
718            if parsed.meta.slice().len() != arena_size ||
719               shared_dictionary::parse_serialized_dictionary_into(
720                   dict_data.slice(), &summary, &mut parsed).is_err() {
721                self.alloc_u32.free_cell(core::mem::replace(&mut parsed.meta,
722                                         AllocU32::AllocatedMemory::default()));
723                self.free_chunk(dict_data);
724                return false;
725            }
726        }
727        if let Some((prefix_offset, prefix_len)) = summary.prefix {
728            let chunk = match borrowed_blob {
729                Some(blob) => MaybeOwnedSlice::Borrowed(
730                    &blob[prefix_offset..prefix_offset + prefix_len]),
731                // An owned blob is not kept around unless it carries custom
732                // lists, so the prefix is copied into its own buffer; that
733                // also leaves the parsed word/transform offsets referencing
734                // the blob unchanged.
735                None => {
736                    let mut chunk = self.alloc_u8.alloc_cell(prefix_len);
737                    if chunk.slice().len() != prefix_len {
738                        self.alloc_u8.free_cell(chunk);
739                        self.alloc_u32.free_cell(core::mem::replace(&mut parsed.meta,
740                                                 AllocU32::AllocatedMemory::default()));
741                        self.free_chunk(dict_data);
742                        return false;
743                    }
744                    chunk.slice_mut().clone_from_slice(
745                        &dict_data.slice()[prefix_offset..prefix_offset + prefix_len]);
746                    MaybeOwnedSlice::Owned(chunk)
747                },
748            };
749            if !self.attach_compound_dictionary_chunk(chunk) {
750                self.alloc_u32.free_cell(core::mem::replace(&mut parsed.meta,
751                                         AllocU32::AllocatedMemory::default()));
752                self.free_chunk(dict_data);
753                return false;
754            }
755        }
756        if is_custom {
757            parsed.blob = dict_data;
758            let old = core::mem::replace(&mut self.dictionary, parsed);
759            self.free_chunk(old.blob);
760            self.alloc_u32.free_cell(old.meta);
761        } else {
762            // Nothing references the blob: a prefix chunk, if any, either
763            // borrows the caller's memory or was copied out.
764            self.free_chunk(dict_data);
765        }
766        true
767    }
768    // Attaches one LZ77 prefix ("compound") dictionary chunk. Chunks must be
769    // attached before any data is decompressed; the most recently attached
770    // chunk is the closest in backward-distance space. Returns false (and
771    // frees the chunk) if the chunk cannot be attached.
772    // Releases a dictionary backing store: owned memory goes back to the
773    // allocator, borrowed memory belongs to the caller and is left alone.
774    pub(crate) fn free_chunk(self : &mut Self, chunk: MaybeOwnedSlice<AllocU8>) {
775        if let MaybeOwnedSlice::Owned(mem) = chunk {
776            self.alloc_u8.free_cell(mem);
777        }
778    }
779    pub(crate) fn attach_compound_dictionary_chunk(self : &mut Self,
780                                            chunk: MaybeOwnedSlice<AllocU8>) -> bool {
781        let size = match chunk {
782            MaybeOwnedSlice::External(len) => len,
783            _ => chunk.slice().len(),
784        };
785        // A zero-length chunk is a no-op and not counted toward the limit.
786        if size == 0 {
787            self.free_chunk(chunk);
788            return true;
789        }
790        let addon = &mut self.compound_dictionary;
791        if addon.num_chunks == SHARED_BROTLI_MAX_COMPOUND_DICTS ||
792           size > SHARED_BROTLI_MAX_RAW_DICT_SIZE - addon.total_size {
793            self.free_chunk(chunk);
794            return false;
795        }
796        addon.chunks[addon.num_chunks] = chunk;
797        addon.num_chunks += 1;
798        addon.total_size += size;
799        addon.chunk_offsets[addon.num_chunks] = addon.total_size as u32;
800        // Invalidate the lazily-computed block map.
801        addon.block_bits = COMPOUND_DICTIONARY_BLOCK_MAP_UNINITIALIZED;
802        true
803    }
804    pub fn BrotliStateMetablockBegin(self : &mut Self) {
805        self.meta_block_remaining_len = 0;
806        self.block_type_length_state.block_length[0] = 1u32 << 24;
807        self.block_type_length_state.block_length[1] = 1u32 << 24;
808        self.block_type_length_state.block_length[2] = 1u32 << 24;
809        self.block_type_length_state.num_block_types[0] = 1;
810        self.block_type_length_state.num_block_types[1] = 1;
811        self.block_type_length_state.num_block_types[2] = 1;
812        self.block_type_length_state.block_type_rb[0] = 1;
813        self.block_type_length_state.block_type_rb[1] = 0;
814        self.block_type_length_state.block_type_rb[2] = 1;
815        self.block_type_length_state.block_type_rb[3] = 0;
816        self.block_type_length_state.block_type_rb[4] = 1;
817        self.block_type_length_state.block_type_rb[5] = 0;
818        self.context_map_slice_index = 0;
819        self.literal_htree_index = 0;
820        self.dist_context_map_slice_index = 0;
821        self.dist_htree_index = 0;
822        self.context_lookup = &kContextLookup[0];
823    }
824    pub fn BrotliStateCleanupAfterMetablock(self : &mut Self) {
825        self.alloc_u8.free_cell(core::mem::replace(&mut self.context_map,
826                                             AllocU8::AllocatedMemory::default()));
827        self.alloc_u8.free_cell(core::mem::replace(&mut self.context_modes,
828                                             AllocU8::AllocatedMemory::default()));
829        self.alloc_u8.free_cell(core::mem::replace(&mut self.dist_context_map,
830                                             AllocU8::AllocatedMemory::default()));
831
832
833        self.literal_hgroup.reset(&mut self.alloc_u32, &mut self.alloc_hc);
834        self.insert_copy_hgroup.reset(&mut self.alloc_u32, &mut self.alloc_hc);
835        self.distance_hgroup.reset(&mut self.alloc_u32, &mut self.alloc_hc);
836    }
837
838   fn BrotliStateCleanup(self : &mut Self) {
839      self.BrotliStateCleanupAfterMetablock();
840      self.alloc_u8.free_cell(core::mem::replace(&mut self.ringbuffer,
841                              AllocU8::AllocatedMemory::default()));
842      self.alloc_hc.free_cell(core::mem::replace(&mut self.block_type_length_state.block_type_trees,
843                              AllocHC::AllocatedMemory::default()));
844      self.alloc_hc.free_cell(core::mem::replace(&mut self.block_type_length_state.block_len_trees,
845                              AllocHC::AllocatedMemory::default()));
846      self.alloc_hc.free_cell(core::mem::replace(&mut self.context_map_table,
847                              AllocHC::AllocatedMemory::default()));
848      self.alloc_u8.free_cell(core::mem::replace(&mut self.custom_dict,
849                              AllocU8::AllocatedMemory::default()));
850      let num_chunks = self.compound_dictionary.num_chunks.min(self.compound_dictionary.chunks.len());
851      for chunk in self.compound_dictionary.chunks[..num_chunks].iter_mut() {
852        if let MaybeOwnedSlice::Owned(mem) =
853            core::mem::replace(chunk, MaybeOwnedSlice::default()) {
854          self.alloc_u8.free_cell(mem);
855        }
856      }
857      self.compound_dictionary.num_chunks = 0;
858      self.compound_dictionary.total_size = 0;
859      if let MaybeOwnedSlice::Owned(mem) =
860          core::mem::replace(&mut self.dictionary.blob, MaybeOwnedSlice::default()) {
861        self.alloc_u8.free_cell(mem);
862      }
863      self.alloc_u32.free_cell(core::mem::replace(&mut self.dictionary.meta,
864                               AllocU32::AllocatedMemory::default()));
865
866      //FIXME??  BROTLI_FREE(s, s->legacy_input_buffer);
867      //FIXME??  BROTLI_FREE(s, s->legacy_output_buffer);
868    }
869
870    pub fn BrotliStateIsStreamStart(self : &Self) -> bool {
871        match self.state {
872            BrotliRunningState::BROTLI_STATE_UNINITED =>
873                BrotliGetAvailableBits(&self.br) == 0,
874            _ => false,
875        }
876    }
877
878    pub fn BrotliStateIsStreamEnd(self : &Self) -> bool {
879        match self.state {
880            BrotliRunningState::BROTLI_STATE_DONE => true,
881            _ => false
882        }
883    }
884    pub fn BrotliHuffmanTreeGroupInit(self :&mut Self, group : WhichTreeGroup,
885                                      alphabet_size : u16, max_symbol: u16, ntrees : u16) {
886        match group {
887            WhichTreeGroup::LITERAL => self.literal_hgroup.init(&mut self.alloc_u32,
888                                                                &mut self.alloc_hc,
889                                                                alphabet_size, max_symbol, ntrees),
890            WhichTreeGroup::INSERT_COPY => self.insert_copy_hgroup.init(&mut self.alloc_u32,
891                                                                        &mut self.alloc_hc,
892                                                                        alphabet_size, max_symbol, ntrees),
893            WhichTreeGroup::DISTANCE => self.distance_hgroup.init(&mut self.alloc_u32,
894                                                                  &mut self.alloc_hc,
895                                                                  alphabet_size, max_symbol, ntrees),
896        }
897    }
898    pub fn BrotliHuffmanTreeGroupRelease(self :&mut Self, group : WhichTreeGroup) {
899        match group {
900            WhichTreeGroup::LITERAL => self.literal_hgroup.reset(&mut self.alloc_u32,
901                                                                 &mut self.alloc_hc),
902            WhichTreeGroup::INSERT_COPY => self.insert_copy_hgroup.reset(&mut self.alloc_u32,
903                                                                         &mut self.alloc_hc),
904            WhichTreeGroup::DISTANCE => self.distance_hgroup.reset(&mut self.alloc_u32,
905                                                                   &mut self.alloc_hc),
906        }
907    }
908}
909
910impl <'brotli_state,
911      AllocU8 : alloc::Allocator<u8>,
912      AllocU32 : alloc::Allocator<u32>,
913      AllocHC : alloc::Allocator<HuffmanCode> > Drop for BrotliState<AllocU8, AllocU32, AllocHC> {
914    fn drop(&mut self) {
915        self.BrotliStateCleanup();
916    }
917}
918
919
920
921pub fn BrotliDecoderErrorStr(c: BrotliDecoderErrorCode) -> &'static str {
922  match c {
923  BrotliDecoderErrorCode::BROTLI_DECODER_NO_ERROR => "NO_ERROR\0",
924  /* Same as BrotliDecoderResult values */
925  BrotliDecoderErrorCode::BROTLI_DECODER_SUCCESS => "SUCCESS\0",
926  BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_INPUT => "NEEDS_MORE_INPUT\0",
927  BrotliDecoderErrorCode::BROTLI_DECODER_NEEDS_MORE_OUTPUT => "NEEDS_MORE_OUTPUT\0",
928
929  /* Errors caused by invalid input */
930  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE => "ERROR_FORMAT_EXUBERANT_NIBBLE\0",
931  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_RESERVED => "ERROR_FORMAT_RESERVED\0",
932  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE => "ERROR_FORMAT_EXUBERANT_META_NIBBLE\0",
933  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET => "ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET\0",
934  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME => "ERROR_FORMAT_SIMPLE_HUFFMAN_SAME\0",
935  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_CL_SPACE => "ERROR_FORMAT_FL_SPACE\0",
936  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE => "ERROR_FORMAT_HUFFMAN_SPACE\0",
937  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT => "ERROR_FORMAT_CONTEXT_MAP_REPEAT\0",
938  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1 =>"ERROR_FORMAT_BLOCK_LENGTH_1\0",
939  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2 =>"ERROR_FORMAT_BLOCK_LENGTH_2\0",
940  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_TRANSFORM => "ERROR_FORMAT_TRANSFORM\0",
941  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DICTIONARY =>"ERROR_FORMAT_DICTIONARY\0",
942  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS =>"ERROR_FORMAT_WINDOW_BITS\0",
943  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_1 =>"ERROR_FORMAT_PADDING_1\0",
944  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_PADDING_2 =>"ERROR_FORMAT_PADDING_2\0",
945  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_DISTANCE =>"ERROR_FORMAT_DISTANCE\0",
946  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH =>"ERROR_FORMAT_BLOCK_SWITCH\0",
947
948  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY => "ERROR_COMPOUND_DICTIONARY\0",
949  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET => "ERROR_DICTIONARY_NOT_SET\0",
950  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_INVALID_ARGUMENTS => "ERROR_INVALID_ARGUMENTS\0",
951
952  /* Memory allocation problems */
953  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES => "ERROR_ALLOC_CONTEXT_MODES\0",
954  /* Literal => insert and distance trees together */
955  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS => "ERROR_ALLOC_TREE_GROUPS\0",
956  /* -23..-24 codes are reserved for distinct tree groups */
957  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP => "ERROR_ALLOC_CONTEXT_MAP\0",
958  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1 => "ERROR_ALLOC_RING_BUFFER_1\0",
959  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2 => "ERROR_ALLOC_RING_BUFFER_2\0",
960  /* -28..-29 codes are reserved for dynamic ring-buffer allocation */
961  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES => "ERROR_ALLOC_BLOCK_TYPE_TREES\0",
962
963  /* "Impossible" states */
964  BrotliDecoderErrorCode::BROTLI_DECODER_ERROR_UNREACHABLE => "ERROR_UNREACHABLE\0",
965  }
966}