Source file: /~heha/hsn/esptool.zip/miniz.h

/* miniz.c 2.1.0 - public domain deflate/inflate
   Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013

   * Low-level Deflate/Inflate implementation notes:

     Compression: Use the "Deflate" API. The compressor supports raw, static, and dynamic blocks, lazy or
     greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses
     approximately as well as zlib.

     Decompression: Use the "Inflate" API. The entire decompressor is implemented as a single function
     coroutine: see decompress(). It supports decompression into a 32KB (or larger power of 2)
     wrapping buffer, or into a memory block large enough to hold the entire file.

     The low-level API's do not make any use of dynamic memory allocation.
*/
#pragma once

/*** Hardcoded options for Xtensa - JD ***/
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0
#define MINIZ_LITTLE_ENDIAN 1

#include <stddef.h>


#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */
#define MINIZ_X86_OR_X64_CPU 1
#else
#define MINIZ_X86_OR_X64_CPU 0
#endif

#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */
#define MINIZ_HAS_64BIT_REGISTERS 1
#else
#define MINIZ_HAS_64BIT_REGISTERS 0
#endif

/* ------------------- zlib-style API Definitions. */

/* mz_adler32() returns 1 when called with ptr==0. */
unsigned mz_adler32(unsigned adler, const unsigned char *ptr, size_t buf_len);

/* mz_crc32() returns 0 when called with ptr==0. */
unsigned mz_crc32(unsigned crc, const unsigned char *ptr, size_t buf_len);

/* Compression strategies. */
enum
{
    MZ_DEFAULT_STRATEGY = 0,
    MZ_FILTERED = 1,
    MZ_HUFFMAN_ONLY = 2,
    MZ_RLE = 3,
    MZ_FIXED = 4
};

/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */
enum{
    MZ_NO_COMPRESSION = 0,
    MZ_BEST_SPEED = 1,
    MZ_BEST_COMPRESSION = 9,
    MZ_UBER_COMPRESSION = 10,
    MZ_DEFAULT_LEVEL = 6,
    MZ_DEFAULT_COMPRESSION = -1
 };

#include <assert.h>
#include <stdlib.h>
#include <string.h>

/* ------------------- Types and macros */
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;

/* Compression API */

class Deflate{
public:
 enum Dstatus{
  STATUS_BAD_PARAM = -2,
  STATUS_PUT_BUF_FAILED = -1,
  STATUS_OKAY = 0,
  STATUS_DONE = 1,
 };
/* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called OUT_BUF_SIZE at a time. */
 typedef bool (*cb_t)(const void *pBuf, int len, void *pUser);
/* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */
/* DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */
 enum{
  HUFFMAN_ONLY = 0,
  DEFAULT_MAX_PROBES = 128,
  MAX_PROBES_MASK = 0xFFF,
/* WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */
/* COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */
/* GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */
/* NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */
/* RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */
/* FILTER_MATCHES: Discards matches <= 5 chars if enabled. */
/* FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */
/* FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */
/* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see MAX_PROBES_MASK). */
  WRITE_ZLIB_HEADER = 0x01000,
  COMPUTE_ADLER32 = 0x02000,
  GREEDY_PARSING_FLAG = 0x04000,
  NONDETERMINISTIC_PARSING_FLAG = 0x08000,
  RLE_MATCHES = 0x10000,
  FILTER_MATCHES = 0x20000,
  FORCE_ALL_STATIC_BLOCKS = 0x40000,
  FORCE_ALL_RAW_BLOCKS = 0x80000,
 };
private:
 enum{
  MAX_HUFF_TABLES = 3,
  MAX_HUFF_SYMBOLS_0 = 288,
  MAX_HUFF_SYMBOLS_1 = 32,
  MAX_HUFF_SYMBOLS_2 = 19,
  LZ_DICT_SIZE = (8*1024),
  LZ_DICT_SIZE_MASK = LZ_DICT_SIZE - 1,
  MIN_MATCH_LEN = 3,
  MAX_MATCH_LEN = 258,

  LZ_CODE_BUF_SIZE = 8 * 1024,
  OUT_BUF_SIZE = (LZ_CODE_BUF_SIZE * 13) / 10,
  MAX_HUFF_SYMBOLS = 288,
  LZ_HASH_BITS = 12,
  LEVEL1_HASH_SIZE_MASK = 4095,
  LZ_HASH_SHIFT = (LZ_HASH_BITS + 2) / 3,
  LZ_HASH_SIZE = 1 << LZ_HASH_BITS,
 };
/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */
 enum tdefl_flush{
  NO_FLUSH = 0,
  SYNC_FLUSH = 2,
  FULL_FLUSH = 3,
  FINISH = 4
 };
 cb_t m_pPut_buf_func;
 void *m_pPut_buf_user;
 mz_uint m_flags, m_max_probes[2];
 int m_greedy_parsing;
 mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
 mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
 mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
 mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;
 Dstatus m_prev_return_status;
 const void *m_pIn_buf;
 void *m_pOut_buf;
 size_t *m_pIn_buf_size, *m_pOut_buf_size;
 tdefl_flush m_flush;
 const mz_uint8 *m_pSrc;
 size_t m_src_buf_left, m_out_buf_ofs;
 mz_uint8 m_dict[LZ_DICT_SIZE + MAX_MATCH_LEN - 1];
 mz_uint16 m_huff_count[MAX_HUFF_TABLES][MAX_HUFF_SYMBOLS];
 mz_uint16 m_huff_codes[MAX_HUFF_TABLES][MAX_HUFF_SYMBOLS];
 mz_uint8 m_huff_code_sizes[MAX_HUFF_TABLES][MAX_HUFF_SYMBOLS];
 mz_uint8 m_lz_code_buf[LZ_CODE_BUF_SIZE];
 mz_uint16 m_next[LZ_DICT_SIZE];
 mz_uint16 m_hash[LZ_HASH_SIZE];
 mz_uint8 m_output_buf[OUT_BUF_SIZE];

/* Initializes the compressor.
   There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
   pBut_buf_func: If nullptr, output data will be supplied to the specified callback.
   In this case, the user should call the tdefl_compress_buffer() API for compression.
   If pBut_buf_func is nullptr the user should always call the tdefl_compress() API.
   flags: See the above enums (HUFFMAN_ONLY, WRITE_ZLIB_HEADER, etc.) */
 Deflate(cb_t, void*, int flags);
/* Compresses a block of data, consuming as much of the specified input buffer as possible,
   and writing as much compressed data to the specified output buffer as possible. */
 Dstatus compress(const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
/* compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
   compress_buffer() always consumes the entire input buffer. */
 Dstatus compress_buffer(const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
 Dstatus get_prev_return_status();
 mz_uint32 get_adler32();
 int flush_block(int flush);
 void start_dynamic_block();
 void start_static_block();
 bool compress_lz_codes();
 bool compress_block(bool static_block);
 bool compress_normal();
 Dstatus flush_output_buffer();
 void optimize_huffman_table(int table_num, int table_len, int code_size_limit, bool static_table);
 void find_match(mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len);
 void record_match(mz_uint match_len, mz_uint match_dist);
 void record_literal(mz_uint8 lit);
public:
/* Create tdefl_compress() flags given zlib-style compression parameters.
   level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
   window_bits may be -15 (raw deflate) or 15 (zlib)
   strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */
 static unsigned create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
/* tdefl_compress_mem_to_output() compresses a block to an output stream.
   The above helpers use this function internally. */
 static bool mem_to_output(const void *pBuf, size_t buf_len, cb_t cb, void*cbd, int flags);
/* High level compression functions:
   mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
   On entry:
    pSrc_buf, src_buf_len: Pointer and size of source block to compress.
    flags: The max match finder probes (default is 128) logically OR'd against the above flags.
	Higher probes are slower but improve compression.
   On return:
    Function returns a pointer to the compressed data, or NULL on failure.
    *pOut_len will be set to the compressed data's size,
	which could be larger than src_buf_len on uncompressible data.
    The caller must free() the returned block when it's no longer needed. */
 static void* mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t&Out_len, int flags);
/* mem_to_mem() compresses a block in memory to another block in memory.
   Returns 0 on failure. */
 static size_t mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
};


/* Decompression API */

class Inflate{
public:
 enum{
  PARSE_ZLIB_HEADER = 1,	// the input has a valid zlib header and ends with an adler32 checksum
  HAS_MORE_INPUT = 2,		// more input bytes available beyond the end of the supplied input buffer
  USING_NON_WRAPPING_OUTPUT_BUF = 4,	// If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB).
  COMPUTE_ADLER32 = 8,		// Force adler-32 checksum computation of the decompressed bytes
 };
/* Return status. */
 enum Status{
    /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */
    /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */
    /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */
  STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4,
    /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */
  STATUS_BAD_PARAM = -3,
    /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */
  STATUS_ADLER32_MISMATCH = -2,
    /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */
  STATUS_FAILED = -1,
    /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */

    /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */
    /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */
  STATUS_DONE = 0,
    /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */
    /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */
    /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */
  STATUS_NEEDS_MORE_INPUT = 1,
    /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */
    /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */
    /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */
    /* so I may need to add some code to address this. */
  STATUS_HAS_MORE_OUTPUT = 2
 };
private:
 enum {	// Internal/private bits follow.
  MEM_TO_MEM_FAILED = ((size_t)(-1)),
  LZ_DICT_SIZE	= 32768,		// Max size of LZ dictionary.
  USE_64BIT_BITBUF = MINIZ_HAS_64BIT_REGISTERS,
  BITBUF_SIZE	= 32 << USE_64BIT_BITBUF,
  MAX_HUFF_TABLES = 3,
  MAX_HUFF_SYMBOLS_0 = 288,
  MAX_HUFF_SYMBOLS_1 = 32,
  MAX_HUFF_SYMBOLS_2 = 19,
  FAST_LOOKUP_BITS = 10,
  FAST_LOOKUP_SIZE = 1 << FAST_LOOKUP_BITS,
 };
 struct huff_table;
 friend huff_table;	// otherwise no access to private MAX_HUFF_SYMBOLS_0
#if MINIZ_HAS_64BIT_REGISTERS
typedef uint64_t bitbuf_t;
#else
typedef mz_uint32 bitbuf_t;
#endif
 struct huff_table {
  mz_uint8 m_code_size[MAX_HUFF_SYMBOLS_0];
  mz_int16 m_look_up[FAST_LOOKUP_SIZE], m_tree[MAX_HUFF_SYMBOLS_0 * 2];
 };

 mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
	m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[MAX_HUFF_TABLES];
 bitbuf_t m_bit_buf;
 size_t m_dist_from_out_buf_start;
 huff_table m_tables[MAX_HUFF_TABLES];
 mz_uint8 m_raw_header[4], m_len_codes[MAX_HUFF_SYMBOLS_0 + MAX_HUFF_SYMBOLS_1 + 137];
 Inflate():m_state(0) {}
/* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */
/* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */
 Status decompress(const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
// Static user-callable functions
public:
/* mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
 On entry:
   pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
 On return:
   Function returns a pointer to the decompressed data, or NULL on failure.
   *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
   The caller must call free() or delete on the returned block when it's no longer needed. */
 static void* mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t&Out_len, int flags);
/* mem_to_mem() decompresses a block in memory to another block in memory. */
/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */
 static size_t mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
/* mem_to_callback() decompresses a block in memory to an internal 32KB buffer,
   and a user provided callback function will be called to flush the buffer.
   Callback must return 1 on success or 0 on failure. */
 typedef bool (*cb_t)(const void *pBuf, int len, void *pUser);
 static int mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, cb_t cb, void *cbd, int flags);
};
Detected encoding: ASCII (7 bit)2