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