LeventeDaradici

miniz.c

May 11th, 2023
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 225.62 KB | Source Code | 0 0
  1. /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing
  2.    See "unlicense" statement at the end of this file.
  3.    Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
  4.    Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
  5.  
  6.    Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define
  7.    MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).
  8.  
  9.    * Change History
  10.      10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!):
  11.        - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug
  12.         would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place()
  13.         (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag).
  14.        - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size
  15.        - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries.
  16.          Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice).
  17.        - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes
  18.        - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
  19.        - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6.
  20.        - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
  21.        - Merged MZ_FORCEINLINE fix from hdeanclark
  22.        - Fix <time.h> include before config #ifdef, thanks emil.brink
  23.        - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can
  24.         set it to 1 for real-time compression).
  25.        - Merged in some compiler fixes from paulharris's github repro.
  26.        - Retested this build under Windows (VS 2010, including static analysis), tcc  0.9.26, gcc v4.6 and clang v3.3.
  27.        - Added example6.c, which dumps an image of the mandelbrot set to a PNG file.
  28.        - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
  29.        - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled
  30.      - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch
  31.      5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect).
  32.      5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
  33.        - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files.
  34.        - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
  35.        - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly
  36.         "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning).
  37.        - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64.
  38.        - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test.
  39.        - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives.
  40.        - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.)
  41.        - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself).
  42.      4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's.
  43.       level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report.
  44.      5/28/11 v1.11 - Added statement from unlicense.org
  45.      5/27/11 v1.10 - Substantial compressor optimizations:
  46.       - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a
  47.       - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86).
  48.       - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types.
  49.       - Refactored the compression code for better readability and maintainability.
  50.       - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large
  51.        drop in throughput on some files).
  52.      5/15/11 v1.09 - Initial stable release.
  53.  
  54.    * Low-level Deflate/Inflate implementation notes:
  55.  
  56.      Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or
  57.      greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses
  58.      approximately as well as zlib.
  59.  
  60.      Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function
  61.      coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory
  62.      block large enough to hold the entire file.
  63.  
  64.      The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation.
  65.  
  66.    * zlib-style API notes:
  67.  
  68.      miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in
  69.      zlib replacement in many apps:
  70.         The z_stream struct, optional memory allocation callbacks
  71.         deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
  72.         inflateInit/inflateInit2/inflate/inflateEnd
  73.         compress, compress2, compressBound, uncompress
  74.         CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines.
  75.         Supports raw deflate streams or standard zlib streams with adler-32 checking.
  76.  
  77.      Limitations:
  78.       The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries.
  79.       I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but
  80.       there are no guarantees that miniz.c pulls this off perfectly.
  81.  
  82.    * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by
  83.      Alex Evans. Supports 1-4 bytes/pixel images.
  84.  
  85.    * ZIP archive API notes:
  86.  
  87.      The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to
  88.      get the job done with minimal fuss. There are simple API's to retrieve file information, read files from
  89.      existing archives, create new archives, append new files to existing archives, or clone archive data from
  90.      one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h),
  91.      or you can specify custom file read/write callbacks.
  92.  
  93.      - Archive reading: Just call this function to read a single file from a disk archive:
  94.  
  95.       void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name,
  96.         size_t *pSize, mz_uint zip_flags);
  97.  
  98.      For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central
  99.      directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files.
  100.  
  101.      - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file:
  102.  
  103.      int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
  104.  
  105.      The locate operation can optionally check file comments too, which (as one example) can be used to identify
  106.      multiple versions of the same file in an archive. This function uses a simple linear search through the central
  107.      directory, so it's not very fast.
  108.  
  109.      Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and
  110.      retrieve detailed info on each file by calling mz_zip_reader_file_stat().
  111.  
  112.      - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data
  113.      to disk and builds an exact image of the central directory in memory. The central directory image is written
  114.      all at once at the end of the archive file when the archive is finalized.
  115.  
  116.      The archive writer can optionally align each file's local header and file data to any power of 2 alignment,
  117.      which can be useful when the archive will be read from optical media. Also, the writer supports placing
  118.      arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still
  119.      readable by any ZIP tool.
  120.  
  121.      - Archive appending: The simple way to add a single file to an archive is to call this function:
  122.  
  123.       mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name,
  124.         const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
  125.  
  126.      The archive will be created if it doesn't already exist, otherwise it'll be appended to.
  127.      Note the appending is done in-place and is not an atomic operation, so if something goes wrong
  128.      during the operation it's possible the archive could be left without a central directory (although the local
  129.      file headers and file data will be fine, so the archive will be recoverable).
  130.  
  131.      For more complex archive modification scenarios:
  132.      1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to
  133.      preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the
  134.      compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and
  135.      you're done. This is safe but requires a bunch of temporary disk space or heap memory.
  136.  
  137.      2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(),
  138.      append new files as needed, then finalize the archive which will write an updated central directory to the
  139.      original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a
  140.      possibility that the archive's central directory could be lost with this method if anything goes wrong, though.
  141.  
  142.      - ZIP archive support limitations:
  143.      No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files.
  144.      Requires streams capable of seeking.
  145.  
  146.    * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the
  147.      below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.
  148.  
  149.    * Important: For best perf. be sure to customize the below macros for your target platform:
  150.      #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  151.      #define MINIZ_LITTLE_ENDIAN 1
  152.      #define MINIZ_HAS_64BIT_REGISTERS 1
  153.  
  154.    * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz
  155.      uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files
  156.      (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
  157. */
  158.  
  159. #ifndef MINIZ_HEADER_INCLUDED
  160. #define MINIZ_HEADER_INCLUDED
  161.  
  162. #include <stdlib.h>
  163.  
  164. // Defines to completely disable specific portions of miniz.c:
  165. // If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl.
  166.  
  167. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O.
  168. #define MINIZ_NO_STDIO
  169.  
  170. // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or
  171. // get/set file times, and the C run-time funcs that get/set times won't be called.
  172. // The current downside is the times written to your archives will be from 1979.
  173. #define MINIZ_NO_TIME
  174.  
  175. // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
  176. #define MINIZ_NO_ARCHIVE_APIS
  177.  
  178. // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's.
  179. #define MINIZ_NO_ARCHIVE_WRITING_APIS
  180.  
  181. // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's.
  182. #define MINIZ_NO_ZLIB_APIS
  183.  
  184. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib.
  185. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  186.  
  187. // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
  188. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc
  189. // callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user
  190. // functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
  191. //#define MINIZ_NO_MALLOC
  192.  
  193. //
  194. #define MINIZ_NO_COMPRESSION
  195.  
  196.  
  197. #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
  198.   // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux
  199.   #define MINIZ_NO_TIME
  200. #endif
  201.  
  202. #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
  203.   #include <time.h>
  204. #endif
  205.  
  206. #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
  207. // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
  208. #define MINIZ_X86_OR_X64_CPU 1
  209. #endif
  210.  
  211. #if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  212. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  213. #define MINIZ_LITTLE_ENDIAN 1
  214. #endif
  215.  
  216. #if MINIZ_X86_OR_X64_CPU
  217. // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
  218. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  219. #endif
  220.  
  221. #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
  222. // 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).
  223. #define MINIZ_HAS_64BIT_REGISTERS 1
  224. #endif
  225.  
  226. #ifdef __cplusplus
  227. extern "C" {
  228. #endif
  229.  
  230. // ------------------- zlib-style API Definitions.
  231.  
  232. // For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
  233. typedef unsigned long mz_ulong;
  234.  
  235. // mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap.
  236. void mz_free(void *p);
  237.  
  238. #define MZ_ADLER32_INIT (1)
  239. // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
  240. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
  241.  
  242. #define MZ_CRC32_INIT (0)
  243. // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
  244. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
  245.  
  246. // Compression strategies.
  247. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
  248.  
  249. // Method
  250. #define MZ_DEFLATED 8
  251.  
  252. #ifndef MINIZ_NO_ZLIB_APIS
  253.  
  254. // Heap allocation callbacks.
  255. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
  256. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
  257. typedef void (*mz_free_func)(void *opaque, void *address);
  258. typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
  259.  
  260. #define MZ_VERSION          "9.1.15"
  261. #define MZ_VERNUM           0x91F0
  262. #define MZ_VER_MAJOR        9
  263. #define MZ_VER_MINOR        1
  264. #define MZ_VER_REVISION     15
  265. #define MZ_VER_SUBREVISION  0
  266.  
  267. // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs).
  268. enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 };
  269.  
  270. // Return status codes. MZ_PARAM_ERROR is non-standard.
  271. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 };
  272.  
  273. // 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.
  274. 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 };
  275.  
  276. // Window bits
  277. #define MZ_DEFAULT_WINDOW_BITS 15
  278.  
  279. struct mz_internal_state;
  280.  
  281. // Compression/decompression stream struct.
  282. typedef struct mz_stream_s
  283. {
  284.   const unsigned char *next_in;     // pointer to next byte to read
  285.   unsigned int avail_in;            // number of bytes available at next_in
  286.   mz_ulong total_in;                // total number of bytes consumed so far
  287.  
  288.   unsigned char *next_out;          // pointer to next byte to write
  289.   unsigned int avail_out;           // number of bytes that can be written to next_out
  290.   mz_ulong total_out;               // total number of bytes produced so far
  291.  
  292.   char *msg;                        // error msg (unused)
  293.   struct mz_internal_state *state;  // internal state, allocated by zalloc/zfree
  294.  
  295.   mz_alloc_func zalloc;             // optional heap allocation function (defaults to malloc)
  296.   mz_free_func zfree;               // optional heap free function (defaults to free)
  297.   void *opaque;                     // heap alloc function user pointer
  298.  
  299.   int data_type;                    // data_type (unused)
  300.   mz_ulong adler;                   // adler32 of the source or uncompressed data
  301.   mz_ulong reserved;                // not used
  302. } mz_stream;
  303.  
  304. typedef mz_stream *mz_streamp;
  305.  
  306. // Returns the version string of miniz.c.
  307. const char *mz_version(void);
  308.  
  309. // mz_deflateInit() initializes a compressor with default options:
  310. // Parameters:
  311. //  pStream must point to an initialized mz_stream struct.
  312. //  level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
  313. //  level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
  314. //  (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
  315. // Return values:
  316. //  MZ_OK on success.
  317. //  MZ_STREAM_ERROR if the stream is bogus.
  318. //  MZ_PARAM_ERROR if the input parameters are bogus.
  319. //  MZ_MEM_ERROR on out of memory.
  320. int mz_deflateInit(mz_streamp pStream, int level);
  321.  
  322. // mz_deflateInit2() is like mz_deflate(), except with more control:
  323. // Additional parameters:
  324. //   method must be MZ_DEFLATED
  325. //   window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer)
  326. //   mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
  327. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);
  328.  
  329. // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
  330. int mz_deflateReset(mz_streamp pStream);
  331.  
  332. // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
  333. // Parameters:
  334. //   pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
  335. //   flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
  336. // Return values:
  337. //   MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full).
  338. //   MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore.
  339. //   MZ_STREAM_ERROR if the stream is bogus.
  340. //   MZ_PARAM_ERROR if one of the parameters is invalid.
  341. //   MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.)
  342. int mz_deflate(mz_streamp pStream, int flush);
  343.  
  344. // mz_deflateEnd() deinitializes a compressor:
  345. // Return values:
  346. //  MZ_OK on success.
  347. //  MZ_STREAM_ERROR if the stream is bogus.
  348. int mz_deflateEnd(mz_streamp pStream);
  349.  
  350. // mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH.
  351. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
  352.  
  353. // Single-call compression functions mz_compress() and mz_compress2():
  354. // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
  355. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
  356. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);
  357.  
  358. // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
  359. mz_ulong mz_compressBound(mz_ulong source_len);
  360.  
  361. // Initializes a decompressor.
  362. int mz_inflateInit(mz_streamp pStream);
  363.  
  364. // mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer:
  365. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
  366. int mz_inflateInit2(mz_streamp pStream, int window_bits);
  367.  
  368. // Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible.
  369. // Parameters:
  370. //   pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
  371. //   flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
  372. //   On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster).
  373. //   MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data.
  374. // Return values:
  375. //   MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full.
  376. //   MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified.
  377. //   MZ_STREAM_ERROR if the stream is bogus.
  378. //   MZ_DATA_ERROR if the deflate stream is invalid.
  379. //   MZ_PARAM_ERROR if one of the parameters is invalid.
  380. //   MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again
  381. //   with more input data, or with more room in the output buffer (except when using single call decompression, described above).
  382. int mz_inflate(mz_streamp pStream, int flush);
  383.  
  384. // Deinitializes a decompressor.
  385. int mz_inflateEnd(mz_streamp pStream);
  386.  
  387. // Single-call decompression.
  388. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
  389. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
  390.  
  391. // Returns a string description of the specified error code, or NULL if the error code is invalid.
  392. const char *mz_error(int err);
  393.  
  394. // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports.
  395. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
  396. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  397.   typedef unsigned char Byte;
  398.   typedef unsigned int uInt;
  399.   typedef mz_ulong uLong;
  400.   typedef Byte Bytef;
  401.   typedef uInt uIntf;
  402.   typedef char charf;
  403.   typedef int intf;
  404.   typedef void *voidpf;
  405.   typedef uLong uLongf;
  406.   typedef void *voidp;
  407.   typedef void *const voidpc;
  408.   #define Z_NULL                0
  409.   #define Z_NO_FLUSH            MZ_NO_FLUSH
  410.   #define Z_PARTIAL_FLUSH       MZ_PARTIAL_FLUSH
  411.   #define Z_SYNC_FLUSH          MZ_SYNC_FLUSH
  412.   #define Z_FULL_FLUSH          MZ_FULL_FLUSH
  413.   #define Z_FINISH              MZ_FINISH
  414.   #define Z_BLOCK               MZ_BLOCK
  415.   #define Z_OK                  MZ_OK
  416.   #define Z_STREAM_END          MZ_STREAM_END
  417.   #define Z_NEED_DICT           MZ_NEED_DICT
  418.   #define Z_ERRNO               MZ_ERRNO
  419.   #define Z_STREAM_ERROR        MZ_STREAM_ERROR
  420.   #define Z_DATA_ERROR          MZ_DATA_ERROR
  421.   #define Z_MEM_ERROR           MZ_MEM_ERROR
  422.   #define Z_BUF_ERROR           MZ_BUF_ERROR
  423.   #define Z_VERSION_ERROR       MZ_VERSION_ERROR
  424.   #define Z_PARAM_ERROR         MZ_PARAM_ERROR
  425.   #define Z_NO_COMPRESSION      MZ_NO_COMPRESSION
  426.   #define Z_BEST_SPEED          MZ_BEST_SPEED
  427.   #define Z_BEST_COMPRESSION    MZ_BEST_COMPRESSION
  428.   #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
  429.   #define Z_DEFAULT_STRATEGY    MZ_DEFAULT_STRATEGY
  430.   #define Z_FILTERED            MZ_FILTERED
  431.   #define Z_HUFFMAN_ONLY        MZ_HUFFMAN_ONLY
  432.   #define Z_RLE                 MZ_RLE
  433.   #define Z_FIXED               MZ_FIXED
  434.   #define Z_DEFLATED            MZ_DEFLATED
  435.   #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
  436.   #define alloc_func            mz_alloc_func
  437.   #define free_func             mz_free_func
  438.   #define internal_state        mz_internal_state
  439.   #define z_stream              mz_stream
  440.   #define deflateInit           mz_deflateInit
  441.   #define deflateInit2          mz_deflateInit2
  442.   #define deflateReset          mz_deflateReset
  443.   #define deflate               mz_deflate
  444.   #define deflateEnd            mz_deflateEnd
  445.   #define deflateBound          mz_deflateBound
  446.   #define compress              mz_compress
  447.   #define compress2             mz_compress2
  448.   #define compressBound         mz_compressBound
  449.   #define inflateInit           mz_inflateInit
  450.   #define inflateInit2          mz_inflateInit2
  451.   #define inflate               mz_inflate
  452.   #define inflateEnd            mz_inflateEnd
  453.   #define uncompress            mz_uncompress
  454.   #define crc32                 mz_crc32
  455.   #define adler32               mz_adler32
  456.   #define MAX_WBITS             15
  457.   #define MAX_MEM_LEVEL         9
  458.   #define zError                mz_error
  459.   #define ZLIB_VERSION          MZ_VERSION
  460.   #define ZLIB_VERNUM           MZ_VERNUM
  461.   #define ZLIB_VER_MAJOR        MZ_VER_MAJOR
  462.   #define ZLIB_VER_MINOR        MZ_VER_MINOR
  463.   #define ZLIB_VER_REVISION     MZ_VER_REVISION
  464.   #define ZLIB_VER_SUBREVISION  MZ_VER_SUBREVISION
  465.   #define zlibVersion           mz_version
  466.   #define zlib_version          mz_version()
  467. #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  468.  
  469. #endif // MINIZ_NO_ZLIB_APIS
  470.  
  471. // ------------------- Types and macros
  472.  
  473. typedef unsigned char mz_uint8;
  474. typedef signed short mz_int16;
  475. typedef unsigned short mz_uint16;
  476. typedef unsigned int mz_uint32;
  477. typedef unsigned int mz_uint;
  478. typedef long long mz_int64;
  479. typedef unsigned long long mz_uint64;
  480. typedef int mz_bool;
  481.  
  482. #define MZ_FALSE (0)
  483. #define MZ_TRUE (1)
  484.  
  485. // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message.
  486. #ifdef _MSC_VER
  487.    #define MZ_MACRO_END while (0, 0)
  488. #else
  489.    #define MZ_MACRO_END while (0)
  490. #endif
  491.  
  492. // ------------------- ZIP archive reading/writing
  493.  
  494. #ifndef MINIZ_NO_ARCHIVE_APIS
  495.  
  496. enum
  497. {
  498.   MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024,
  499.   MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
  500.   MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
  501. };
  502.  
  503. typedef struct
  504. {
  505.   mz_uint32 m_file_index;
  506.   mz_uint32 m_central_dir_ofs;
  507.   mz_uint16 m_version_made_by;
  508.   mz_uint16 m_version_needed;
  509.   mz_uint16 m_bit_flag;
  510.   mz_uint16 m_method;
  511. #ifndef MINIZ_NO_TIME
  512.   time_t m_time;
  513. #endif
  514.   mz_uint32 m_crc32;
  515.   mz_uint64 m_comp_size;
  516.   mz_uint64 m_uncomp_size;
  517.   mz_uint16 m_internal_attr;
  518.   mz_uint32 m_external_attr;
  519.   mz_uint64 m_local_header_ofs;
  520.   mz_uint32 m_comment_size;
  521.   char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
  522.   char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
  523. } mz_zip_archive_file_stat;
  524.  
  525. typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n);
  526. typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n);
  527.  
  528. struct mz_zip_internal_state_tag;
  529. typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
  530.  
  531. typedef enum
  532. {
  533.   MZ_ZIP_MODE_INVALID = 0,
  534.   MZ_ZIP_MODE_READING = 1,
  535.   MZ_ZIP_MODE_WRITING = 2,
  536.   MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
  537. } mz_zip_mode;
  538.  
  539. typedef struct mz_zip_archive_tag
  540. {
  541.   mz_uint64 m_archive_size;
  542.   mz_uint64 m_central_directory_file_ofs;
  543.   mz_uint m_total_files;
  544.   mz_zip_mode m_zip_mode;
  545.  
  546.   mz_uint m_file_offset_alignment;
  547.  
  548.   mz_alloc_func m_pAlloc;
  549.   mz_free_func m_pFree;
  550.   mz_realloc_func m_pRealloc;
  551.   void *m_pAlloc_opaque;
  552.  
  553.   mz_file_read_func m_pRead;
  554.   mz_file_write_func m_pWrite;
  555.   void *m_pIO_opaque;
  556.  
  557.   mz_zip_internal_state *m_pState;
  558.  
  559. } mz_zip_archive;
  560.  
  561. typedef enum
  562. {
  563.   MZ_ZIP_FLAG_CASE_SENSITIVE                = 0x0100,
  564.   MZ_ZIP_FLAG_IGNORE_PATH                   = 0x0200,
  565.   MZ_ZIP_FLAG_COMPRESSED_DATA               = 0x0400,
  566.   MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
  567. } mz_zip_flags;
  568.  
  569. // ZIP archive reading
  570.  
  571. // Inits a ZIP archive reader.
  572. // These functions read and validate the archive's central directory.
  573. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags);
  574. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags);
  575.  
  576. #ifndef MINIZ_NO_STDIO
  577. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags);
  578. #endif
  579.  
  580. // Returns the total number of files in the archive.
  581. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
  582.  
  583. // Returns detailed information about an archive file entry.
  584. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat);
  585.  
  586. // Determines if an archive file entry is a directory entry.
  587. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index);
  588. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index);
  589.  
  590. // Retrieves the filename of an archive file entry.
  591. // Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename.
  592. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size);
  593.  
  594. // Attempts to locates a file in the archive's central directory.
  595. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
  596. // Returns -1 if the file cannot be found.
  597. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
  598.  
  599. // Extracts a archive file to a memory buffer using no memory allocation.
  600. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  601. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  602.  
  603. // Extracts a archive file to a memory buffer.
  604. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags);
  605. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags);
  606.  
  607. // Extracts a archive file to a dynamically allocated heap buffer.
  608. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags);
  609. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags);
  610.  
  611. // Extracts a archive file using a callback function to output the file's data.
  612. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
  613. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
  614.  
  615. #ifndef MINIZ_NO_STDIO
  616. // Extracts a archive file to a disk file and sets its last accessed and modified times.
  617. // This function only extracts files, not archive directory records.
  618. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags);
  619. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags);
  620. #endif
  621.  
  622. // Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used.
  623. mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
  624.  
  625. // ZIP archive writing
  626.  
  627. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  628.  
  629. // Inits a ZIP archive writer.
  630. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
  631. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size);
  632.  
  633. #ifndef MINIZ_NO_STDIO
  634. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning);
  635. #endif
  636.  
  637. // Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive.
  638. // For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called.
  639. // For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it).
  640. // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL.
  641. // Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before
  642. // the archive is finalized the file's central directory will be hosed.
  643. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename);
  644.  
  645. // Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive.
  646. // To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer.
  647. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
  648. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags);
  649. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32);
  650.  
  651. #ifndef MINIZ_NO_STDIO
  652. // Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive.
  653. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
  654. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
  655. #endif
  656.  
  657. // Adds a file to an archive by fully cloning the data from another archive.
  658. // This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields.
  659. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index);
  660.  
  661. // Finalizes the archive by writing the central directory records followed by the end of central directory record.
  662. // After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end().
  663. // An archive must be manually finalized by calling this function for it to be valid.
  664. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
  665. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize);
  666.  
  667. // Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used.
  668. // Note for the archive to be valid, it must have been finalized before ending.
  669. mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
  670.  
  671. // Misc. high-level helper functions:
  672.  
  673. // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive.
  674. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
  675. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
  676.  
  677. // Reads a single file from an archive into a heap block.
  678. // Returns NULL on failure.
  679. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags);
  680.  
  681. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  682.  
  683. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  684.  
  685. // ------------------- Low-level Decompression API Definitions
  686.  
  687. // Decompression flags used by tinfl_decompress().
  688. // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream.
  689. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input.
  690. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: 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).
  691. // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
  692. enum
  693. {
  694.   TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
  695.   TINFL_FLAG_HAS_MORE_INPUT = 2,
  696.   TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
  697.   TINFL_FLAG_COMPUTE_ADLER32 = 8
  698. };
  699.  
  700. // High level decompression functions:
  701. // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
  702. // On entry:
  703. //  pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
  704. // On return:
  705. //  Function returns a pointer to the decompressed data, or NULL on failure.
  706. //  *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
  707. //  The caller must call mz_free() on the returned block when it's no longer needed.
  708. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
  709.  
  710. // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
  711. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
  712. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
  713. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
  714.  
  715. // tinfl_decompress_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.
  716. // Returns 1 on success or 0 on failure.
  717. typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
  718. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  719.  
  720. struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
  721.  
  722. // Max size of LZ dictionary.
  723. #define TINFL_LZ_DICT_SIZE 32768
  724.  
  725. // Return status.
  726. typedef enum
  727. {
  728.   TINFL_STATUS_BAD_PARAM = -3,
  729.   TINFL_STATUS_ADLER32_MISMATCH = -2,
  730.   TINFL_STATUS_FAILED = -1,
  731.   TINFL_STATUS_DONE = 0,
  732.   TINFL_STATUS_NEEDS_MORE_INPUT = 1,
  733.   TINFL_STATUS_HAS_MORE_OUTPUT = 2
  734. } tinfl_status;
  735.  
  736. // Initializes the decompressor to its initial state.
  737. #define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
  738. #define tinfl_get_adler32(r) (r)->m_check_adler32
  739.  
  740. // 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.
  741. // 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.
  742. tinfl_status tinfl_decompress(tinfl_decompressor *r, 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);
  743.  
  744. // Internal/private bits follow.
  745. enum
  746. {
  747.   TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
  748.   TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
  749. };
  750.  
  751. typedef struct
  752. {
  753.   mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
  754.   mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
  755. } tinfl_huff_table;
  756.  
  757. #if MINIZ_HAS_64BIT_REGISTERS
  758.   #define TINFL_USE_64BIT_BITBUF 1
  759. #endif
  760.  
  761. #if TINFL_USE_64BIT_BITBUF
  762.   typedef mz_uint64 tinfl_bit_buf_t;
  763.   #define TINFL_BITBUF_SIZE (64)
  764. #else
  765.   typedef mz_uint32 tinfl_bit_buf_t;
  766.   #define TINFL_BITBUF_SIZE (32)
  767. #endif
  768.  
  769. struct tinfl_decompressor_tag
  770. {
  771.   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[TINFL_MAX_HUFF_TABLES];
  772.   tinfl_bit_buf_t m_bit_buf;
  773.   size_t m_dist_from_out_buf_start;
  774.   tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
  775.   mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
  776. };
  777.  
  778.  
  779. #ifndef MINIZ_NO_COMPRESSION
  780. // ------------------- Low-level Compression API Definitions
  781.  
  782. // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
  783. #define TDEFL_LESS_MEMORY 0
  784.  
  785. // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
  786. // TDEFL_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).
  787. enum
  788. {
  789.   TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF
  790. };
  791.  
  792. // TDEFL_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.
  793. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
  794. // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
  795. // TDEFL_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).
  796. // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
  797. // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
  798. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
  799. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
  800. // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
  801. enum
  802. {
  803.   TDEFL_WRITE_ZLIB_HEADER             = 0x01000,
  804.   TDEFL_COMPUTE_ADLER32               = 0x02000,
  805.   TDEFL_GREEDY_PARSING_FLAG           = 0x04000,
  806.   TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
  807.   TDEFL_RLE_MATCHES                   = 0x10000,
  808.   TDEFL_FILTER_MATCHES                = 0x20000,
  809.   TDEFL_FORCE_ALL_STATIC_BLOCKS       = 0x40000,
  810.   TDEFL_FORCE_ALL_RAW_BLOCKS          = 0x80000
  811. };
  812.  
  813. // High level compression functions:
  814. // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
  815. // On entry:
  816. //  pSrc_buf, src_buf_len: Pointer and size of source block to compress.
  817. //  flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
  818. // On return:
  819. //  Function returns a pointer to the compressed data, or NULL on failure.
  820. //  *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
  821. //  The caller must free() the returned block when it's no longer needed.
  822. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
  823.  
  824. // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
  825. // Returns 0 on failure.
  826. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
  827.  
  828. // Compresses an image to a compressed PNG file in memory.
  829. // On entry:
  830. //  pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
  831. //  The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
  832. //  level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
  833. //  If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
  834. // On return:
  835. //  Function returns a pointer to the compressed data, or NULL on failure.
  836. //  *pLen_out will be set to the size of the PNG image file.
  837. //  The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
  838. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip);
  839. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out);
  840.  
  841. // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
  842. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
  843.  
  844. // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
  845. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  846.  
  847. enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 };
  848.  
  849. // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
  850. #if TDEFL_LESS_MEMORY
  851. enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
  852. #else
  853. enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
  854. #endif
  855.  
  856. // The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions.
  857. typedef enum
  858. {
  859.   TDEFL_STATUS_BAD_PARAM = -2,
  860.   TDEFL_STATUS_PUT_BUF_FAILED = -1,
  861.   TDEFL_STATUS_OKAY = 0,
  862.   TDEFL_STATUS_DONE = 1,
  863. } tdefl_status;
  864.  
  865. // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
  866. typedef enum
  867. {
  868.   TDEFL_NO_FLUSH = 0,
  869.   TDEFL_SYNC_FLUSH = 2,
  870.   TDEFL_FULL_FLUSH = 3,
  871.   TDEFL_FINISH = 4
  872. } tdefl_flush;
  873.  
  874. // tdefl's compression state structure.
  875. typedef struct
  876. {
  877.   tdefl_put_buf_func_ptr m_pPut_buf_func;
  878.   void *m_pPut_buf_user;
  879.   mz_uint m_flags, m_max_probes[2];
  880.   int m_greedy_parsing;
  881.   mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
  882.   mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
  883.   mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
  884.   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;
  885.   tdefl_status m_prev_return_status;
  886.   const void *m_pIn_buf;
  887.   void *m_pOut_buf;
  888.   size_t *m_pIn_buf_size, *m_pOut_buf_size;
  889.   tdefl_flush m_flush;
  890.   const mz_uint8 *m_pSrc;
  891.   size_t m_src_buf_left, m_out_buf_ofs;
  892.   mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
  893.   mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  894.   mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  895.   mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  896.   mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
  897.   mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
  898.   mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
  899.   mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
  900. } tdefl_compressor;
  901.  
  902. // Initializes the compressor.
  903. // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
  904. // pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression.
  905. // If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
  906. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
  907. tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  908.  
  909. // 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.
  910. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
  911.  
  912. // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
  913. // tdefl_compress_buffer() always consumes the entire input buffer.
  914. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
  915.  
  916. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
  917. mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
  918.  
  919. // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros.
  920. #ifndef MINIZ_NO_ZLIB_APIS
  921. // Create tdefl_compress() flags given zlib-style compression parameters.
  922. // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
  923. // window_bits may be -15 (raw deflate) or 15 (zlib)
  924. // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
  925. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
  926. #endif // #ifndef MINIZ_NO_ZLIB_APIS
  927.  
  928. #endif // MINIZ_NO_COMPRESSION
  929.  
  930. #ifdef __cplusplus
  931. }
  932. #endif
  933.  
  934. #endif // MINIZ_HEADER_INCLUDED
  935.  
  936. // ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.)
  937.  
  938. #ifndef MINIZ_HEADER_FILE_ONLY
  939.  
  940. typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1];
  941. typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1];
  942. typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1];
  943.  
  944. #include <string.h>
  945. #include <assert.h>
  946.  
  947. #define MZ_ASSERT(x) assert(x)
  948.  
  949. #ifdef MINIZ_NO_MALLOC
  950.   #define MZ_MALLOC(x) NULL
  951.   #define MZ_FREE(x) (void)x, ((void)0)
  952.   #define MZ_REALLOC(p, x) NULL
  953. #else
  954.   #define MZ_MALLOC(x) malloc(x)
  955.   #define MZ_FREE(x) free(x)
  956.   #define MZ_REALLOC(p, x) realloc(p, x)
  957. #endif
  958.  
  959. #define MZ_MAX(a,b) (((a)>(b))?(a):(b))
  960. #define MZ_MIN(a,b) (((a)<(b))?(a):(b))
  961. #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
  962.  
  963. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  964.   #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
  965.   #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
  966. #else
  967.   #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
  968.   #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
  969. #endif
  970.  
  971. #ifdef _MSC_VER
  972.   #define MZ_FORCEINLINE __forceinline
  973. #elif defined(__GNUC__)
  974.   #define MZ_FORCEINLINE inline __attribute__((__always_inline__))
  975. #else
  976.   #define MZ_FORCEINLINE inline
  977. #endif
  978.  
  979. #ifdef __cplusplus
  980.   extern "C" {
  981. #endif
  982.  
  983. // ------------------- zlib-style API's
  984.  
  985. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len)
  986. {
  987.   mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552;
  988.   if (!ptr) return MZ_ADLER32_INIT;
  989.   while (buf_len) {
  990.     for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  991.       s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
  992.       s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
  993.     }
  994.     for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  995.     s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
  996.   }
  997.   return (s2 << 16) + s1;
  998. }
  999.  
  1000. // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/
  1001. mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)
  1002. {
  1003.   static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
  1004.     0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
  1005.   mz_uint32 crcu32 = (mz_uint32)crc;
  1006.   if (!ptr) return MZ_CRC32_INIT;
  1007.   crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; }
  1008.   return ~crcu32;
  1009. }
  1010.  
  1011. void mz_free(void *p)
  1012. {
  1013.   MZ_FREE(p);
  1014. }
  1015.  
  1016. #ifndef MINIZ_NO_ZLIB_APIS
  1017.  
  1018. static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); }
  1019. static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); }
  1020. static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); }
  1021.  
  1022. const char *mz_version(void)
  1023. {
  1024.   return MZ_VERSION;
  1025. }
  1026.  
  1027. #ifndef MINIZ_NO_COMPRESSION
  1028.  
  1029. int mz_deflateInit(mz_streamp pStream, int level)
  1030. {
  1031.   return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY);
  1032. }
  1033.  
  1034. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy)
  1035. {
  1036.   tdefl_compressor *pComp;
  1037.   mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
  1038.  
  1039.   if (!pStream) return MZ_STREAM_ERROR;
  1040.   if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR;
  1041.  
  1042.   pStream->data_type = 0;
  1043.   pStream->adler = MZ_ADLER32_INIT;
  1044.   pStream->msg = NULL;
  1045.   pStream->reserved = 0;
  1046.   pStream->total_in = 0;
  1047.   pStream->total_out = 0;
  1048.   if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  1049.   if (!pStream->zfree) pStream->zfree = def_free_func;
  1050.  
  1051.   pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor));
  1052.   if (!pComp)
  1053.     return MZ_MEM_ERROR;
  1054.  
  1055.   pStream->state = (struct mz_internal_state *)pComp;
  1056.  
  1057.   if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY)
  1058.   {
  1059.     mz_deflateEnd(pStream);
  1060.     return MZ_PARAM_ERROR;
  1061.   }
  1062.  
  1063.   return MZ_OK;
  1064. }
  1065.  
  1066. int mz_deflateReset(mz_streamp pStream)
  1067. {
  1068.   if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR;
  1069.   pStream->total_in = pStream->total_out = 0;
  1070.   tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags);
  1071.   return MZ_OK;
  1072. }
  1073.  
  1074. int mz_deflate(mz_streamp pStream, int flush)
  1075. {
  1076.   size_t in_bytes, out_bytes;
  1077.   mz_ulong orig_total_in, orig_total_out;
  1078.   int mz_status = MZ_OK;
  1079.  
  1080.   if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR;
  1081.   if (!pStream->avail_out) return MZ_BUF_ERROR;
  1082.  
  1083.   if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1084.  
  1085.   if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE)
  1086.     return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
  1087.  
  1088.   orig_total_in = pStream->total_in; orig_total_out = pStream->total_out;
  1089.   for ( ; ; )
  1090.   {
  1091.     tdefl_status defl_status;
  1092.     in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
  1093.  
  1094.     defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush);
  1095.     pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
  1096.     pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state);
  1097.  
  1098.     pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes;
  1099.     pStream->total_out += (mz_uint)out_bytes;
  1100.  
  1101.     if (defl_status < 0)
  1102.     {
  1103.       mz_status = MZ_STREAM_ERROR;
  1104.       break;
  1105.     }
  1106.     else if (defl_status == TDEFL_STATUS_DONE)
  1107.     {
  1108.       mz_status = MZ_STREAM_END;
  1109.       break;
  1110.     }
  1111.     else if (!pStream->avail_out)
  1112.       break;
  1113.     else if ((!pStream->avail_in) && (flush != MZ_FINISH))
  1114.     {
  1115.       if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out))
  1116.         break;
  1117.       return MZ_BUF_ERROR; // Can't make forward progress without some input.
  1118.     }
  1119.   }
  1120.   return mz_status;
  1121. }
  1122.  
  1123. int mz_deflateEnd(mz_streamp pStream)
  1124. {
  1125.   if (!pStream) return MZ_STREAM_ERROR;
  1126.   if (pStream->state)
  1127.   {
  1128.     pStream->zfree(pStream->opaque, pStream->state);
  1129.     pStream->state = NULL;
  1130.   }
  1131.   return MZ_OK;
  1132. }
  1133.  
  1134. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len)
  1135. {
  1136.   (void)pStream;
  1137.   // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.)
  1138.   return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
  1139. }
  1140.  
  1141. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level)
  1142. {
  1143.   int status;
  1144.   mz_stream stream;
  1145.   memset(&stream, 0, sizeof(stream));
  1146.  
  1147.   // In case mz_ulong is 64-bits (argh I hate longs).
  1148.   if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  1149.  
  1150.   stream.next_in = pSource;
  1151.   stream.avail_in = (mz_uint32)source_len;
  1152.   stream.next_out = pDest;
  1153.   stream.avail_out = (mz_uint32)*pDest_len;
  1154.  
  1155.   status = mz_deflateInit(&stream, level);
  1156.   if (status != MZ_OK) return status;
  1157.  
  1158.   status = mz_deflate(&stream, MZ_FINISH);
  1159.   if (status != MZ_STREAM_END)
  1160.   {
  1161.     mz_deflateEnd(&stream);
  1162.     return (status == MZ_OK) ? MZ_BUF_ERROR : status;
  1163.   }
  1164.  
  1165.   *pDest_len = stream.total_out;
  1166.   return mz_deflateEnd(&stream);
  1167. }
  1168.  
  1169. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
  1170. {
  1171.   return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION);
  1172. }
  1173.  
  1174. mz_ulong mz_compressBound(mz_ulong source_len)
  1175. {
  1176.   return mz_deflateBound(NULL, source_len);
  1177. }
  1178.  
  1179. #endif // MINIZ_NO_COMPRESSION
  1180.  
  1181. typedef struct
  1182. {
  1183.   tinfl_decompressor m_decomp;
  1184.   mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits;
  1185.   mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
  1186.   tinfl_status m_last_status;
  1187. } inflate_state;
  1188.  
  1189. int mz_inflateInit2(mz_streamp pStream, int window_bits)
  1190. {
  1191.   inflate_state *pDecomp;
  1192.   if (!pStream) return MZ_STREAM_ERROR;
  1193.   if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR;
  1194.  
  1195.   pStream->data_type = 0;
  1196.   pStream->adler = 0;
  1197.   pStream->msg = NULL;
  1198.   pStream->total_in = 0;
  1199.   pStream->total_out = 0;
  1200.   pStream->reserved = 0;
  1201.   if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  1202.   if (!pStream->zfree) pStream->zfree = def_free_func;
  1203.  
  1204.   pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state));
  1205.   if (!pDecomp) return MZ_MEM_ERROR;
  1206.  
  1207.   pStream->state = (struct mz_internal_state *)pDecomp;
  1208.  
  1209.   tinfl_init(&pDecomp->m_decomp);
  1210.   pDecomp->m_dict_ofs = 0;
  1211.   pDecomp->m_dict_avail = 0;
  1212.   pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
  1213.   pDecomp->m_first_call = 1;
  1214.   pDecomp->m_has_flushed = 0;
  1215.   pDecomp->m_window_bits = window_bits;
  1216.  
  1217.   return MZ_OK;
  1218. }
  1219.  
  1220. int mz_inflateInit(mz_streamp pStream)
  1221. {
  1222.    return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
  1223. }
  1224.  
  1225. int mz_inflate(mz_streamp pStream, int flush)
  1226. {
  1227.   inflate_state* pState;
  1228.   mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
  1229.   size_t in_bytes, out_bytes, orig_avail_in;
  1230.   tinfl_status status;
  1231.  
  1232.   if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR;
  1233.   if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1234.   if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  1235.  
  1236.   pState = (inflate_state*)pStream->state;
  1237.   if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
  1238.   orig_avail_in = pStream->avail_in;
  1239.  
  1240.   first_call = pState->m_first_call; pState->m_first_call = 0;
  1241.   if (pState->m_last_status < 0) return MZ_DATA_ERROR;
  1242.  
  1243.   if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  1244.   pState->m_has_flushed |= (flush == MZ_FINISH);
  1245.  
  1246.   if ((flush == MZ_FINISH) && (first_call))
  1247.   {
  1248.     // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file.
  1249.     decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
  1250.     in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
  1251.     status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags);
  1252.     pState->m_last_status = status;
  1253.     pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes;
  1254.     pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1255.     pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes;
  1256.  
  1257.     if (status < 0)
  1258.       return MZ_DATA_ERROR;
  1259.     else if (status != TINFL_STATUS_DONE)
  1260.     {
  1261.       pState->m_last_status = TINFL_STATUS_FAILED;
  1262.       return MZ_BUF_ERROR;
  1263.     }
  1264.     return MZ_STREAM_END;
  1265.   }
  1266.   // flush != MZ_FINISH then we must assume there's more input.
  1267.   if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
  1268.  
  1269.   if (pState->m_dict_avail)
  1270.   {
  1271.     n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1272.     memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1273.     pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
  1274.     pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1275.     return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
  1276.   }
  1277.  
  1278.   for ( ; ; )
  1279.   {
  1280.     in_bytes = pStream->avail_in;
  1281.     out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
  1282.  
  1283.     status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
  1284.     pState->m_last_status = status;
  1285.  
  1286.     pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
  1287.     pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1288.  
  1289.     pState->m_dict_avail = (mz_uint)out_bytes;
  1290.  
  1291.     n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1292.     memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1293.     pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
  1294.     pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1295.  
  1296.     if (status < 0)
  1297.        return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well).
  1298.     else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
  1299.       return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH.
  1300.     else if (flush == MZ_FINISH)
  1301.     {
  1302.        // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH.
  1303.        if (status == TINFL_STATUS_DONE)
  1304.           return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
  1305.        // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong.
  1306.        else if (!pStream->avail_out)
  1307.           return MZ_BUF_ERROR;
  1308.     }
  1309.     else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail))
  1310.       break;
  1311.   }
  1312.  
  1313.   return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
  1314. }
  1315.  
  1316. int mz_inflateEnd(mz_streamp pStream)
  1317. {
  1318.   if (!pStream)
  1319.     return MZ_STREAM_ERROR;
  1320.   if (pStream->state)
  1321.   {
  1322.     pStream->zfree(pStream->opaque, pStream->state);
  1323.     pStream->state = NULL;
  1324.   }
  1325.   return MZ_OK;
  1326. }
  1327.  
  1328. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
  1329. {
  1330.   mz_stream stream;
  1331.   int status;
  1332.   memset(&stream, 0, sizeof(stream));
  1333.  
  1334.   // In case mz_ulong is 64-bits (argh I hate longs).
  1335.   if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  1336.  
  1337.   stream.next_in = pSource;
  1338.   stream.avail_in = (mz_uint32)source_len;
  1339.   stream.next_out = pDest;
  1340.   stream.avail_out = (mz_uint32)*pDest_len;
  1341.  
  1342.   status = mz_inflateInit(&stream);
  1343.   if (status != MZ_OK)
  1344.     return status;
  1345.  
  1346.   status = mz_inflate(&stream, MZ_FINISH);
  1347.   if (status != MZ_STREAM_END)
  1348.   {
  1349.     mz_inflateEnd(&stream);
  1350.     return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status;
  1351.   }
  1352.   *pDest_len = stream.total_out;
  1353.  
  1354.   return mz_inflateEnd(&stream);
  1355. }
  1356.  
  1357. const char *mz_error(int err)
  1358. {
  1359.   static struct { int m_err; const char *m_pDesc; } s_error_descs[] =
  1360.   {
  1361.     { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" },
  1362.     { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" }
  1363.   };
  1364.   mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc;
  1365.   return NULL;
  1366. }
  1367.  
  1368. #endif //MINIZ_NO_ZLIB_APIS
  1369.  
  1370. // ------------------- Low-level Decompression (completely independent from all compression API's)
  1371.  
  1372. #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
  1373. #define TINFL_MEMSET(p, c, l) memset(p, c, l)
  1374.  
  1375. #define TINFL_CR_BEGIN switch(r->m_state) { case 0:
  1376. #define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END
  1377. #define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END
  1378. #define TINFL_CR_FINISH }
  1379.  
  1380. // TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never
  1381. // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.
  1382. #define TINFL_GET_BYTE(state_index, c) do { \
  1383.   if (pIn_buf_cur >= pIn_buf_end) { \
  1384.     for ( ; ; ) { \
  1385.       if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
  1386.         TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
  1387.         if (pIn_buf_cur < pIn_buf_end) { \
  1388.           c = *pIn_buf_cur++; \
  1389.           break; \
  1390.         } \
  1391.       } else { \
  1392.         c = 0; \
  1393.         break; \
  1394.       } \
  1395.     } \
  1396.   } else c = *pIn_buf_cur++; } MZ_MACRO_END
  1397.  
  1398. #define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n))
  1399. #define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
  1400. #define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
  1401.  
  1402. // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.
  1403. // It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a
  1404. // Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the
  1405. // bit buffer contains >=15 bits (deflate's max. Huffman code size).
  1406. #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
  1407.   do { \
  1408.     temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
  1409.     if (temp >= 0) { \
  1410.       code_len = temp >> 9; \
  1411.       if ((code_len) && (num_bits >= code_len)) \
  1412.       break; \
  1413.     } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
  1414.        code_len = TINFL_FAST_LOOKUP_BITS; \
  1415.        do { \
  1416.           temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  1417.        } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \
  1418.     } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \
  1419.   } while (num_bits < 15);
  1420.  
  1421. // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read
  1422. // beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully
  1423. // decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32.
  1424. // The slow path is only executed at the very end of the input buffer.
  1425. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \
  1426.   int temp; mz_uint code_len, c; \
  1427.   if (num_bits < 15) { \
  1428.     if ((pIn_buf_end - pIn_buf_cur) < 2) { \
  1429.        TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
  1430.     } else { \
  1431.        bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \
  1432.     } \
  1433.   } \
  1434.   if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
  1435.     code_len = temp >> 9, temp &= 511; \
  1436.   else { \
  1437.     code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \
  1438.   } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END
  1439.  
  1440. tinfl_status tinfl_decompress(tinfl_decompressor *r, 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)
  1441. {
  1442.   static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 };
  1443.   static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
  1444.   static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
  1445.   static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  1446.   static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
  1447.   static const int s_min_table_sizes[3] = { 257, 1, 4 };
  1448.  
  1449.   tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf;
  1450.   const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
  1451.   mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
  1452.   size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start;
  1453.  
  1454.   // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter).
  1455.   if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; }
  1456.  
  1457.   num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start;
  1458.   TINFL_CR_BEGIN
  1459.  
  1460.   bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1;
  1461.   if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
  1462.   {
  1463.     TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1);
  1464.     counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
  1465.     if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
  1466.     if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); }
  1467.   }
  1468.  
  1469.   do
  1470.   {
  1471.     TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1;
  1472.     if (r->m_type == 0)
  1473.     {
  1474.       TINFL_SKIP_BITS(5, num_bits & 7);
  1475.       for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); }
  1476.       if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); }
  1477.       while ((counter) && (num_bits))
  1478.       {
  1479.         TINFL_GET_BITS(51, dist, 8);
  1480.         while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1481.         *pOut_buf_cur++ = (mz_uint8)dist;
  1482.         counter--;
  1483.       }
  1484.       while (counter)
  1485.       {
  1486.         size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1487.         while (pIn_buf_cur >= pIn_buf_end)
  1488.         {
  1489.           if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT)
  1490.           {
  1491.             TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
  1492.           }
  1493.           else
  1494.           {
  1495.             TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
  1496.           }
  1497.         }
  1498.         n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);
  1499.         TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n;
  1500.       }
  1501.     }
  1502.     else if (r->m_type == 3)
  1503.     {
  1504.       TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
  1505.     }
  1506.     else
  1507.     {
  1508.       if (r->m_type == 1)
  1509.       {
  1510.         mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i;
  1511.         r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
  1512.         for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8;
  1513.       }
  1514.       else
  1515.       {
  1516.         for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; }
  1517.         MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; }
  1518.         r->m_table_sizes[2] = 19;
  1519.       }
  1520.       for ( ; (int)r->m_type >= 0; r->m_type--)
  1521.       {
  1522.         int tree_next, tree_cur; tinfl_huff_table *pTable;
  1523.         mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree);
  1524.         for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++;
  1525.         used_syms = 0, total = 0; next_code[0] = next_code[1] = 0;
  1526.         for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); }
  1527.         if ((65536 != total) && (used_syms > 1))
  1528.         {
  1529.           TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
  1530.         }
  1531.         for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)
  1532.         {
  1533.           mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue;
  1534.           cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1);
  1535.           if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; }
  1536.           if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; }
  1537.           rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
  1538.           for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)
  1539.           {
  1540.             tree_cur -= ((rev_code >>= 1) & 1);
  1541.             if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1];
  1542.           }
  1543.           tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
  1544.         }
  1545.         if (r->m_type == 2)
  1546.         {
  1547.           for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); )
  1548.           {
  1549.             mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; }
  1550.             if ((dist == 16) && (!counter))
  1551.             {
  1552.               TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
  1553.             }
  1554.             num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16];
  1555.             TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s;
  1556.           }
  1557.           if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)
  1558.           {
  1559.             TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
  1560.           }
  1561.           TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);
  1562.         }
  1563.       }
  1564.       for ( ; ; )
  1565.       {
  1566.         mz_uint8 *pSrc;
  1567.         for ( ; ; )
  1568.         {
  1569.           if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))
  1570.           {
  1571.             TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
  1572.             if (counter >= 256)
  1573.               break;
  1574.             while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1575.             *pOut_buf_cur++ = (mz_uint8)counter;
  1576.           }
  1577.           else
  1578.           {
  1579.             int sym2; mz_uint code_len;
  1580. #if TINFL_USE_64BIT_BITBUF
  1581.             if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; }
  1582. #else
  1583.             if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }
  1584. #endif
  1585.             if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
  1586.               code_len = sym2 >> 9;
  1587.             else
  1588.             {
  1589.               code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
  1590.             }
  1591.             counter = sym2; bit_buf >>= code_len; num_bits -= code_len;
  1592.             if (counter & 256)
  1593.               break;
  1594.  
  1595. #if !TINFL_USE_64BIT_BITBUF
  1596.             if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }
  1597. #endif
  1598.             if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
  1599.               code_len = sym2 >> 9;
  1600.             else
  1601.             {
  1602.               code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
  1603.             }
  1604.             bit_buf >>= code_len; num_bits -= code_len;
  1605.  
  1606.             pOut_buf_cur[0] = (mz_uint8)counter;
  1607.             if (sym2 & 256)
  1608.             {
  1609.               pOut_buf_cur++;
  1610.               counter = sym2;
  1611.               break;
  1612.             }
  1613.             pOut_buf_cur[1] = (mz_uint8)sym2;
  1614.             pOut_buf_cur += 2;
  1615.           }
  1616.         }
  1617.         if ((counter &= 511) == 256) break;
  1618.  
  1619.         num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257];
  1620.         if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; }
  1621.  
  1622.         TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
  1623.         num_extra = s_dist_extra[dist]; dist = s_dist_base[dist];
  1624.         if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; }
  1625.  
  1626.         dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
  1627.         if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
  1628.         {
  1629.           TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
  1630.         }
  1631.  
  1632.         pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);
  1633.  
  1634.         if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)
  1635.         {
  1636.           while (counter--)
  1637.           {
  1638.             while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1639.             *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];
  1640.           }
  1641.           continue;
  1642.         }
  1643. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  1644.         else if ((counter >= 9) && (counter <= dist))
  1645.         {
  1646.           const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
  1647.           do
  1648.           {
  1649.             ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
  1650.             ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
  1651.             pOut_buf_cur += 8;
  1652.           } while ((pSrc += 8) < pSrc_end);
  1653.           if ((counter &= 7) < 3)
  1654.           {
  1655.             if (counter)
  1656.             {
  1657.               pOut_buf_cur[0] = pSrc[0];
  1658.               if (counter > 1)
  1659.                 pOut_buf_cur[1] = pSrc[1];
  1660.               pOut_buf_cur += counter;
  1661.             }
  1662.             continue;
  1663.           }
  1664.         }
  1665. #endif
  1666.         do
  1667.         {
  1668.           pOut_buf_cur[0] = pSrc[0];
  1669.           pOut_buf_cur[1] = pSrc[1];
  1670.           pOut_buf_cur[2] = pSrc[2];
  1671.           pOut_buf_cur += 3; pSrc += 3;
  1672.         } while ((int)(counter -= 3) > 2);
  1673.         if ((int)counter > 0)
  1674.         {
  1675.           pOut_buf_cur[0] = pSrc[0];
  1676.           if ((int)counter > 1)
  1677.             pOut_buf_cur[1] = pSrc[1];
  1678.           pOut_buf_cur += counter;
  1679.         }
  1680.       }
  1681.     }
  1682.   } while (!(r->m_final & 1));
  1683.   if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
  1684.   {
  1685.     TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; }
  1686.   }
  1687.   TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
  1688.   TINFL_CR_FINISH
  1689.  
  1690. common_exit:
  1691.   r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start;
  1692.   *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
  1693.   if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))
  1694.   {
  1695.     const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size;
  1696.     mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552;
  1697.     while (buf_len)
  1698.     {
  1699.       for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
  1700.       {
  1701.         s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
  1702.         s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
  1703.       }
  1704.       for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  1705.       s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
  1706.     }
  1707.     r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH;
  1708.   }
  1709.   return status;
  1710. }
  1711.  
  1712. // Higher level helper functions.
  1713. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
  1714. {
  1715.   tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0;
  1716.   *pOut_len = 0;
  1717.   tinfl_init(&decomp);
  1718.   for ( ; ; )
  1719.   {
  1720.     size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
  1721.     tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size,
  1722.       (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  1723.     if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT))
  1724.     {
  1725.       MZ_FREE(pBuf); *pOut_len = 0; return NULL;
  1726.     }
  1727.     src_buf_ofs += src_buf_size;
  1728.     *pOut_len += dst_buf_size;
  1729.     if (status == TINFL_STATUS_DONE) break;
  1730.     new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;
  1731.     pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
  1732.     if (!pNew_buf)
  1733.     {
  1734.       MZ_FREE(pBuf); *pOut_len = 0; return NULL;
  1735.     }
  1736.     pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity;
  1737.   }
  1738.   return pBuf;
  1739. }
  1740.  
  1741. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
  1742. {
  1743.   tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp);
  1744.   status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  1745.   return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
  1746. }
  1747.  
  1748. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  1749. {
  1750.   int result = 0;
  1751.   tinfl_decompressor decomp;
  1752.   mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0;
  1753.   if (!pDict)
  1754.     return TINFL_STATUS_FAILED;
  1755.   tinfl_init(&decomp);
  1756.   for ( ; ; )
  1757.   {
  1758.     size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
  1759.     tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
  1760.       (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
  1761.     in_buf_ofs += in_buf_size;
  1762.     if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
  1763.       break;
  1764.     if (status != TINFL_STATUS_HAS_MORE_OUTPUT)
  1765.     {
  1766.       result = (status == TINFL_STATUS_DONE);
  1767.       break;
  1768.     }
  1769.     dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
  1770.   }
  1771.   MZ_FREE(pDict);
  1772.   *pIn_buf_size = in_buf_ofs;
  1773.   return result;
  1774. }
  1775.  
  1776. #ifndef MINIZ_NO_COMPRESSION
  1777. // ------------------- Low-level Compression (independent from all decompression API's)
  1778.  
  1779. // Purposely making these tables static for faster init and thread safety.
  1780. static const mz_uint16 s_tdefl_len_sym[256] = {
  1781.   257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272,
  1782.   273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276,
  1783.   277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,
  1784.   279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,
  1785.   281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,
  1786.   282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,
  1787.   283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,
  1788.   284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 };
  1789.  
  1790. static const mz_uint8 s_tdefl_len_extra[256] = {
  1791.   0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
  1792.   4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
  1793.   5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
  1794.   5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 };
  1795.  
  1796. static const mz_uint8 s_tdefl_small_dist_sym[512] = {
  1797.   0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  1798.   11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
  1799.   13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,
  1800.   14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  1801.   14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  1802.   15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,
  1803.   16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  1804.   16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  1805.   16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  1806.   17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  1807.   17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  1808.   17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 };
  1809.  
  1810. static const mz_uint8 s_tdefl_small_dist_extra[512] = {
  1811.   0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,
  1812.   5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  1813.   6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  1814.   6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1815.   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1816.   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1817.   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1818.   7,7,7,7,7,7,7,7 };
  1819.  
  1820. static const mz_uint8 s_tdefl_large_dist_sym[128] = {
  1821.   0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,
  1822.   26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,
  1823.   28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 };
  1824.  
  1825. static const mz_uint8 s_tdefl_large_dist_extra[128] = {
  1826.   0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  1827.   12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  1828.   13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 };
  1829.  
  1830. // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values.
  1831. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
  1832. static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1)
  1833. {
  1834.   mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist);
  1835.   for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; }
  1836.   while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;
  1837.   for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
  1838.   {
  1839.     const mz_uint32* pHist = &hist[pass << 8];
  1840.     mz_uint offsets[256], cur_ofs = 0;
  1841.     for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }
  1842.     for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
  1843.     { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; }
  1844.   }
  1845.   return pCur_syms;
  1846. }
  1847.  
  1848. // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
  1849. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n)
  1850. {
  1851.   int root, leaf, next, avbl, used, dpth;
  1852.   if (n==0) return; else if (n==1) { A[0].m_key = 1; return; }
  1853.   A[0].m_key += A[1].m_key; root = 0; leaf = 2;
  1854.   for (next=1; next < n-1; next++)
  1855.   {
  1856.     if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key;
  1857.     if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
  1858.   }
  1859.   A[n-2].m_key = 0; for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1;
  1860.   avbl = 1; used = dpth = 0; root = n-2; next = n-1;
  1861.   while (avbl>0)
  1862.   {
  1863.     while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; }
  1864.     while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; }
  1865.     avbl = 2*used; dpth++; used = 0;
  1866.   }
  1867. }
  1868.  
  1869. // Limits canonical Huffman code table's max code size.
  1870. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
  1871. static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
  1872. {
  1873.   int i; mz_uint32 total = 0; if (code_list_len <= 1) return;
  1874.   for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];
  1875.   for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
  1876.   while (total != (1UL << max_code_size))
  1877.   {
  1878.     pNum_codes[max_code_size]--;
  1879.     for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }
  1880.     total--;
  1881.   }
  1882. }
  1883.  
  1884. static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table)
  1885. {
  1886.   int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes);
  1887.   if (static_table)
  1888.   {
  1889.     for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++;
  1890.   }
  1891.   else
  1892.   {
  1893.     tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;
  1894.     int num_used_syms = 0;
  1895.     const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
  1896.     for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; }
  1897.  
  1898.     pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
  1899.  
  1900.     for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
  1901.  
  1902.     tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit);
  1903.  
  1904.     MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
  1905.     for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
  1906.       for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
  1907.   }
  1908.  
  1909.   next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  1910.  
  1911.   for (i = 0; i < table_len; i++)
  1912.   {
  1913.     mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
  1914.     code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1);
  1915.     d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
  1916.   }
  1917. }
  1918.  
  1919. #define TDEFL_PUT_BITS(b, l) do { \
  1920.   mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \
  1921.   d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \
  1922.   while (d->m_bits_in >= 8) { \
  1923.     if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
  1924.       *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
  1925.       d->m_bit_buffer >>= 8; \
  1926.       d->m_bits_in -= 8; \
  1927.   } \
  1928. } MZ_MACRO_END
  1929.  
  1930. #define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \
  1931.   if (rle_repeat_count < 3) { \
  1932.     d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
  1933.     while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
  1934.   } else { \
  1935.     d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \
  1936. } rle_repeat_count = 0; } }
  1937.  
  1938. #define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \
  1939.   if (rle_z_count < 3) { \
  1940.     d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
  1941.   } else if (rle_z_count <= 10) { \
  1942.     d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \
  1943.   } else { \
  1944.     d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \
  1945. } rle_z_count = 0; } }
  1946.  
  1947. static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
  1948.  
  1949. static void tdefl_start_dynamic_block(tdefl_compressor *d)
  1950. {
  1951.   int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index;
  1952.   mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF;
  1953.  
  1954.   d->m_huff_count[0][256] = 1;
  1955.  
  1956.   tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
  1957.   tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
  1958.  
  1959.   for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
  1960.   for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
  1961.  
  1962.   memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
  1963.   memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes);
  1964.   total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0;
  1965.  
  1966.   memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
  1967.   for (i = 0; i < total_code_sizes_to_pack; i++)
  1968.   {
  1969.     mz_uint8 code_size = code_sizes_to_pack[i];
  1970.     if (!code_size)
  1971.     {
  1972.       TDEFL_RLE_PREV_CODE_SIZE();
  1973.       if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); }
  1974.     }
  1975.     else
  1976.     {
  1977.       TDEFL_RLE_ZERO_CODE_SIZE();
  1978.       if (code_size != prev_code_size)
  1979.       {
  1980.         TDEFL_RLE_PREV_CODE_SIZE();
  1981.         d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size;
  1982.       }
  1983.       else if (++rle_repeat_count == 6)
  1984.       {
  1985.         TDEFL_RLE_PREV_CODE_SIZE();
  1986.       }
  1987.     }
  1988.     prev_code_size = code_size;
  1989.   }
  1990.   if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); }
  1991.  
  1992.   tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
  1993.  
  1994.   TDEFL_PUT_BITS(2, 2);
  1995.  
  1996.   TDEFL_PUT_BITS(num_lit_codes - 257, 5);
  1997.   TDEFL_PUT_BITS(num_dist_codes - 1, 5);
  1998.  
  1999.   for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break;
  2000.   num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
  2001.   for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
  2002.  
  2003.   for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; )
  2004.   {
  2005.     mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
  2006.     TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
  2007.     if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]);
  2008.   }
  2009. }
  2010.  
  2011. static void tdefl_start_static_block(tdefl_compressor *d)
  2012. {
  2013.   mz_uint i;
  2014.   mz_uint8 *p = &d->m_huff_code_sizes[0][0];
  2015.  
  2016.   for (i = 0; i <= 143; ++i) *p++ = 8;
  2017.   for ( ; i <= 255; ++i) *p++ = 9;
  2018.   for ( ; i <= 279; ++i) *p++ = 7;
  2019.   for ( ; i <= 287; ++i) *p++ = 8;
  2020.  
  2021.   memset(d->m_huff_code_sizes[1], 5, 32);
  2022.  
  2023.   tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
  2024.   tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
  2025.  
  2026.   TDEFL_PUT_BITS(1, 2);
  2027. }
  2028.  
  2029. static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
  2030.  
  2031. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
  2032. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
  2033. {
  2034.   mz_uint flags;
  2035.   mz_uint8 *pLZ_codes;
  2036.   mz_uint8 *pOutput_buf = d->m_pOutput_buf;
  2037.   mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
  2038.   mz_uint64 bit_buffer = d->m_bit_buffer;
  2039.   mz_uint bits_in = d->m_bits_in;
  2040.  
  2041. #define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); }
  2042.  
  2043.   flags = 1;
  2044.   for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1)
  2045.   {
  2046.     if (flags == 1)
  2047.       flags = *pLZ_codes++ | 0x100;
  2048.  
  2049.     if (flags & 1)
  2050.     {
  2051.       mz_uint s0, s1, n0, n1, sym, num_extra_bits;
  2052.       mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3;
  2053.  
  2054.       MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  2055.       TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  2056.       TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
  2057.  
  2058.       // This sequence coaxes MSVC into using cmov's vs. jmp's.
  2059.       s0 = s_tdefl_small_dist_sym[match_dist & 511];
  2060.       n0 = s_tdefl_small_dist_extra[match_dist & 511];
  2061.       s1 = s_tdefl_large_dist_sym[match_dist >> 8];
  2062.       n1 = s_tdefl_large_dist_extra[match_dist >> 8];
  2063.       sym = (match_dist < 512) ? s0 : s1;
  2064.       num_extra_bits = (match_dist < 512) ? n0 : n1;
  2065.  
  2066.       MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  2067.       TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  2068.       TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  2069.     }
  2070.     else
  2071.     {
  2072.       mz_uint lit = *pLZ_codes++;
  2073.       MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  2074.       TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  2075.  
  2076.       if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))
  2077.       {
  2078.         flags >>= 1;
  2079.         lit = *pLZ_codes++;
  2080.         MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  2081.         TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  2082.  
  2083.         if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))
  2084.         {
  2085.           flags >>= 1;
  2086.           lit = *pLZ_codes++;
  2087.           MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  2088.           TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  2089.         }
  2090.       }
  2091.     }
  2092.  
  2093.     if (pOutput_buf >= d->m_pOutput_buf_end)
  2094.       return MZ_FALSE;
  2095.  
  2096.     *(mz_uint64*)pOutput_buf = bit_buffer;
  2097.     pOutput_buf += (bits_in >> 3);
  2098.     bit_buffer >>= (bits_in & ~7);
  2099.     bits_in &= 7;
  2100.   }
  2101.  
  2102. #undef TDEFL_PUT_BITS_FAST
  2103.  
  2104.   d->m_pOutput_buf = pOutput_buf;
  2105.   d->m_bits_in = 0;
  2106.   d->m_bit_buffer = 0;
  2107.  
  2108.   while (bits_in)
  2109.   {
  2110.     mz_uint32 n = MZ_MIN(bits_in, 16);
  2111.     TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
  2112.     bit_buffer >>= n;
  2113.     bits_in -= n;
  2114.   }
  2115.  
  2116.   TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  2117.  
  2118.   return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  2119. }
  2120. #else
  2121. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
  2122. {
  2123.   mz_uint flags;
  2124.   mz_uint8 *pLZ_codes;
  2125.  
  2126.   flags = 1;
  2127.   for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1)
  2128.   {
  2129.     if (flags == 1)
  2130.       flags = *pLZ_codes++ | 0x100;
  2131.     if (flags & 1)
  2132.     {
  2133.       mz_uint sym, num_extra_bits;
  2134.       mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3;
  2135.  
  2136.       MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  2137.       TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  2138.       TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
  2139.  
  2140.       if (match_dist < 512)
  2141.       {
  2142.         sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist];
  2143.       }
  2144.       else
  2145.       {
  2146.         sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
  2147.       }
  2148.       MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  2149.       TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  2150.       TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  2151.     }
  2152.     else
  2153.     {
  2154.       mz_uint lit = *pLZ_codes++;
  2155.       MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  2156.       TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  2157.     }
  2158.   }
  2159.  
  2160.   TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  2161.  
  2162.   return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  2163. }
  2164. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
  2165.  
  2166. static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block)
  2167. {
  2168.   if (static_block)
  2169.     tdefl_start_static_block(d);
  2170.   else
  2171.     tdefl_start_dynamic_block(d);
  2172.   return tdefl_compress_lz_codes(d);
  2173. }
  2174.  
  2175. static int tdefl_flush_block(tdefl_compressor *d, int flush)
  2176. {
  2177.   mz_uint saved_bit_buf, saved_bits_in;
  2178.   mz_uint8 *pSaved_output_buf;
  2179.   mz_bool comp_block_succeeded = MZ_FALSE;
  2180.   int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
  2181.   mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf;
  2182.  
  2183.   d->m_pOutput_buf = pOutput_buf_start;
  2184.   d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
  2185.  
  2186.   MZ_ASSERT(!d->m_output_flush_remaining);
  2187.   d->m_output_flush_ofs = 0;
  2188.   d->m_output_flush_remaining = 0;
  2189.  
  2190.   *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
  2191.   d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
  2192.  
  2193.   if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index))
  2194.   {
  2195.     TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8);
  2196.   }
  2197.  
  2198.   TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
  2199.  
  2200.   pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in;
  2201.  
  2202.   if (!use_raw_block)
  2203.     comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48));
  2204.  
  2205.   // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead.
  2206.   if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) &&
  2207.        ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) )
  2208.   {
  2209.     mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  2210.     TDEFL_PUT_BITS(0, 2);
  2211.     if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }
  2212.     for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF)
  2213.     {
  2214.       TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
  2215.     }
  2216.     for (i = 0; i < d->m_total_lz_bytes; ++i)
  2217.     {
  2218.       TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8);
  2219.     }
  2220.   }
  2221.   // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes.
  2222.   else if (!comp_block_succeeded)
  2223.   {
  2224.     d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  2225.     tdefl_compress_block(d, MZ_TRUE);
  2226.   }
  2227.  
  2228.   if (flush)
  2229.   {
  2230.     if (flush == TDEFL_FINISH)
  2231.     {
  2232.       if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }
  2233.       if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } }
  2234.     }
  2235.     else
  2236.     {
  2237.       mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); }
  2238.     }
  2239.   }
  2240.  
  2241.   MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
  2242.  
  2243.   memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  2244.   memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  2245.  
  2246.   d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++;
  2247.  
  2248.   if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0)
  2249.   {
  2250.     if (d->m_pPut_buf_func)
  2251.     {
  2252.       *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  2253.       if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
  2254.         return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
  2255.     }
  2256.     else if (pOutput_buf_start == d->m_output_buf)
  2257.     {
  2258.       int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
  2259.       memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy);
  2260.       d->m_out_buf_ofs += bytes_to_copy;
  2261.       if ((n -= bytes_to_copy) != 0)
  2262.       {
  2263.         d->m_output_flush_ofs = bytes_to_copy;
  2264.         d->m_output_flush_remaining = n;
  2265.       }
  2266.     }
  2267.     else
  2268.     {
  2269.       d->m_out_buf_ofs += n;
  2270.     }
  2271.   }
  2272.  
  2273.   return d->m_output_flush_remaining;
  2274. }
  2275.  
  2276. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  2277. #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p)
  2278. static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)
  2279. {
  2280.   mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
  2281.   mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  2282.   const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q;
  2283.   mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s);
  2284.   MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;
  2285.   for ( ; ; )
  2286.   {
  2287.     for ( ; ; )
  2288.     {
  2289.       if (--num_probes_left == 0) return;
  2290.       #define TDEFL_PROBE \
  2291.         next_probe_pos = d->m_next[probe_pos]; \
  2292.         if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
  2293.         probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  2294.         if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break;
  2295.       TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
  2296.     }
  2297.     if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32;
  2298.     do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  2299.                    (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );
  2300.     if (!probe_len)
  2301.     {
  2302.       *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break;
  2303.     }
  2304.     else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len)
  2305.     {
  2306.       *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break;
  2307.       c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
  2308.     }
  2309.   }
  2310. }
  2311. #else
  2312. static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)
  2313. {
  2314.   mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
  2315.   mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  2316.   const mz_uint8 *s = d->m_dict + pos, *p, *q;
  2317.   mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
  2318.   MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;
  2319.   for ( ; ; )
  2320.   {
  2321.     for ( ; ; )
  2322.     {
  2323.       if (--num_probes_left == 0) return;
  2324.       #define TDEFL_PROBE \
  2325.         next_probe_pos = d->m_next[probe_pos]; \
  2326.         if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
  2327.         probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  2328.         if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break;
  2329.       TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
  2330.     }
  2331.     if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break;
  2332.     if (probe_len > match_len)
  2333.     {
  2334.       *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
  2335.       c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1];
  2336.     }
  2337.   }
  2338. }
  2339. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  2340.  
  2341. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2342. static mz_bool tdefl_compress_fast(tdefl_compressor *d)
  2343. {
  2344.   // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio.
  2345.   mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left;
  2346.   mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
  2347.   mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  2348.  
  2349.   while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size)))
  2350.   {
  2351.     const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
  2352.     mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  2353.     mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
  2354.     d->m_src_buf_left -= num_bytes_to_process;
  2355.     lookahead_size += num_bytes_to_process;
  2356.  
  2357.     while (num_bytes_to_process)
  2358.     {
  2359.       mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
  2360.       memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
  2361.       if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  2362.         memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
  2363.       d->m_pSrc += n;
  2364.       dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
  2365.       num_bytes_to_process -= n;
  2366.     }
  2367.  
  2368.     dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
  2369.     if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break;
  2370.  
  2371.     while (lookahead_size >= 4)
  2372.     {
  2373.       mz_uint cur_match_dist, cur_match_len = 1;
  2374.       mz_uint8 *pCur_dict = d->m_dict + cur_pos;
  2375.       mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
  2376.       mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK;
  2377.       mz_uint probe_pos = d->m_hash[hash];
  2378.       d->m_hash[hash] = (mz_uint16)lookahead_pos;
  2379.  
  2380.       if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram))
  2381.       {
  2382.         const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
  2383.         const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
  2384.         mz_uint32 probe_len = 32;
  2385.         do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  2386.           (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );
  2387.         cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
  2388.         if (!probe_len)
  2389.           cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
  2390.  
  2391.         if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)))
  2392.         {
  2393.           cur_match_len = 1;
  2394.           *pLZ_code_buf++ = (mz_uint8)first_trigram;
  2395.           *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  2396.           d->m_huff_count[0][(mz_uint8)first_trigram]++;
  2397.         }
  2398.         else
  2399.         {
  2400.           mz_uint32 s0, s1;
  2401.           cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
  2402.  
  2403.           MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE));
  2404.  
  2405.           cur_match_dist--;
  2406.  
  2407.           pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
  2408.           *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
  2409.           pLZ_code_buf += 3;
  2410.           *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
  2411.  
  2412.           s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
  2413.           s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
  2414.           d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
  2415.  
  2416.           d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++;
  2417.         }
  2418.       }
  2419.       else
  2420.       {
  2421.         *pLZ_code_buf++ = (mz_uint8)first_trigram;
  2422.         *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  2423.         d->m_huff_count[0][(mz_uint8)first_trigram]++;
  2424.       }
  2425.  
  2426.       if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
  2427.  
  2428.       total_lz_bytes += cur_match_len;
  2429.       lookahead_pos += cur_match_len;
  2430.       dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
  2431.       cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
  2432.       MZ_ASSERT(lookahead_size >= cur_match_len);
  2433.       lookahead_size -= cur_match_len;
  2434.  
  2435.       if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])
  2436.       {
  2437.         int n;
  2438.         d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  2439.         d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
  2440.         if ((n = tdefl_flush_block(d, 0)) != 0)
  2441.           return (n < 0) ? MZ_FALSE : MZ_TRUE;
  2442.         total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
  2443.       }
  2444.     }
  2445.  
  2446.     while (lookahead_size)
  2447.     {
  2448.       mz_uint8 lit = d->m_dict[cur_pos];
  2449.  
  2450.       total_lz_bytes++;
  2451.       *pLZ_code_buf++ = lit;
  2452.       *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  2453.       if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
  2454.  
  2455.       d->m_huff_count[0][lit]++;
  2456.  
  2457.       lookahead_pos++;
  2458.       dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
  2459.       cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  2460.       lookahead_size--;
  2461.  
  2462.       if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])
  2463.       {
  2464.         int n;
  2465.         d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  2466.         d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
  2467.         if ((n = tdefl_flush_block(d, 0)) != 0)
  2468.           return (n < 0) ? MZ_FALSE : MZ_TRUE;
  2469.         total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
  2470.       }
  2471.     }
  2472.   }
  2473.  
  2474.   d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  2475.   d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
  2476.   return MZ_TRUE;
  2477. }
  2478. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2479.  
  2480. static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit)
  2481. {
  2482.   d->m_total_lz_bytes++;
  2483.   *d->m_pLZ_code_buf++ = lit;
  2484.   *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
  2485.   d->m_huff_count[0][lit]++;
  2486. }
  2487.  
  2488. static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist)
  2489. {
  2490.   mz_uint32 s0, s1;
  2491.  
  2492.   MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE));
  2493.  
  2494.   d->m_total_lz_bytes += match_len;
  2495.  
  2496.   d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
  2497.  
  2498.   match_dist -= 1;
  2499.   d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
  2500.   d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3;
  2501.  
  2502.   *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
  2503.  
  2504.   s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
  2505.   d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
  2506.  
  2507.   if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
  2508. }
  2509.  
  2510. static mz_bool tdefl_compress_normal(tdefl_compressor *d)
  2511. {
  2512.   const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left;
  2513.   tdefl_flush flush = d->m_flush;
  2514.  
  2515.   while ((src_buf_left) || ((flush) && (d->m_lookahead_size)))
  2516.   {
  2517.     mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
  2518.     // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN.
  2519.     if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1))
  2520.     {
  2521.       mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
  2522.       mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
  2523.       mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
  2524.       const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
  2525.       src_buf_left -= num_bytes_to_process;
  2526.       d->m_lookahead_size += num_bytes_to_process;
  2527.       while (pSrc != pSrc_end)
  2528.       {
  2529.         mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  2530.         hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  2531.         d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);
  2532.         dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++;
  2533.       }
  2534.     }
  2535.     else
  2536.     {
  2537.       while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
  2538.       {
  2539.         mz_uint8 c = *pSrc++;
  2540.         mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  2541.         src_buf_left--;
  2542.         d->m_dict[dst_pos] = c;
  2543.         if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  2544.           d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  2545.         if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN)
  2546.         {
  2547.           mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
  2548.           mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  2549.           d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);
  2550.         }
  2551.       }
  2552.     }
  2553.     d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
  2554.     if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
  2555.       break;
  2556.  
  2557.     // Simple lazy/greedy parsing state machine.
  2558.     len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  2559.     if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS))
  2560.     {
  2561.       if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))
  2562.       {
  2563.         mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
  2564.         cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; }
  2565.         if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1;
  2566.       }
  2567.     }
  2568.     else
  2569.     {
  2570.       tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len);
  2571.     }
  2572.     if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5)))
  2573.     {
  2574.       cur_match_dist = cur_match_len = 0;
  2575.     }
  2576.     if (d->m_saved_match_len)
  2577.     {
  2578.       if (cur_match_len > d->m_saved_match_len)
  2579.       {
  2580.         tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
  2581.         if (cur_match_len >= 128)
  2582.         {
  2583.           tdefl_record_match(d, cur_match_len, cur_match_dist);
  2584.           d->m_saved_match_len = 0; len_to_move = cur_match_len;
  2585.         }
  2586.         else
  2587.         {
  2588.           d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
  2589.         }
  2590.       }
  2591.       else
  2592.       {
  2593.         tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
  2594.         len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0;
  2595.       }
  2596.     }
  2597.     else if (!cur_match_dist)
  2598.       tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
  2599.     else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128))
  2600.     {
  2601.       tdefl_record_match(d, cur_match_len, cur_match_dist);
  2602.       len_to_move = cur_match_len;
  2603.     }
  2604.     else
  2605.     {
  2606.       d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
  2607.     }
  2608.     // Move the lookahead forward by len_to_move bytes.
  2609.     d->m_lookahead_pos += len_to_move;
  2610.     MZ_ASSERT(d->m_lookahead_size >= len_to_move);
  2611.     d->m_lookahead_size -= len_to_move;
  2612.     d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE);
  2613.     // Check if it's time to flush the current LZ codes to the internal output buffer.
  2614.     if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
  2615.          ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) )
  2616.     {
  2617.       int n;
  2618.       d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
  2619.       if ((n = tdefl_flush_block(d, 0)) != 0)
  2620.         return (n < 0) ? MZ_FALSE : MZ_TRUE;
  2621.     }
  2622.   }
  2623.  
  2624.   d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
  2625.   return MZ_TRUE;
  2626. }
  2627.  
  2628. static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d)
  2629. {
  2630.   if (d->m_pIn_buf_size)
  2631.   {
  2632.     *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  2633.   }
  2634.  
  2635.   if (d->m_pOut_buf_size)
  2636.   {
  2637.     size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining);
  2638.     memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n);
  2639.     d->m_output_flush_ofs += (mz_uint)n;
  2640.     d->m_output_flush_remaining -= (mz_uint)n;
  2641.     d->m_out_buf_ofs += n;
  2642.  
  2643.     *d->m_pOut_buf_size = d->m_out_buf_ofs;
  2644.   }
  2645.  
  2646.   return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;
  2647. }
  2648.  
  2649. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush)
  2650. {
  2651.   if (!d)
  2652.   {
  2653.     if (pIn_buf_size) *pIn_buf_size = 0;
  2654.     if (pOut_buf_size) *pOut_buf_size = 0;
  2655.     return TDEFL_STATUS_BAD_PARAM;
  2656.   }
  2657.  
  2658.   d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size;
  2659.   d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size;
  2660.   d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
  2661.   d->m_out_buf_ofs = 0;
  2662.   d->m_flush = flush;
  2663.  
  2664.   if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
  2665.         (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) )
  2666.   {
  2667.     if (pIn_buf_size) *pIn_buf_size = 0;
  2668.     if (pOut_buf_size) *pOut_buf_size = 0;
  2669.     return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
  2670.   }
  2671.   d->m_wants_to_finish |= (flush == TDEFL_FINISH);
  2672.  
  2673.   if ((d->m_output_flush_remaining) || (d->m_finished))
  2674.     return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  2675.  
  2676. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2677.   if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
  2678.       ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
  2679.       ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0))
  2680.   {
  2681.     if (!tdefl_compress_fast(d))
  2682.       return d->m_prev_return_status;
  2683.   }
  2684.   else
  2685. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2686.   {
  2687.     if (!tdefl_compress_normal(d))
  2688.       return d->m_prev_return_status;
  2689.   }
  2690.  
  2691.   if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf))
  2692.     d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf);
  2693.  
  2694.   if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining))
  2695.   {
  2696.     if (tdefl_flush_block(d, flush) < 0)
  2697.       return d->m_prev_return_status;
  2698.     d->m_finished = (flush == TDEFL_FINISH);
  2699.     if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; }
  2700.   }
  2701.  
  2702.   return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  2703. }
  2704.  
  2705. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush)
  2706. {
  2707.   MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
  2708. }
  2709.  
  2710. tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  2711. {
  2712.   d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user;
  2713.   d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
  2714.   d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
  2715.   if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);
  2716.   d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
  2717.   d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
  2718.   d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8;
  2719.   d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY;
  2720.   d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1;
  2721.   d->m_pIn_buf = NULL; d->m_pOut_buf = NULL;
  2722.   d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL;
  2723.   d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0;
  2724.   memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  2725.   memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  2726.   return TDEFL_STATUS_OKAY;
  2727. }
  2728.  
  2729. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d)
  2730. {
  2731.   return d->m_prev_return_status;
  2732. }
  2733.  
  2734. mz_uint32 tdefl_get_adler32(tdefl_compressor *d)
  2735. {
  2736.   return d->m_adler32;
  2737. }
  2738.  
  2739. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  2740. {
  2741.   tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
  2742.   pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE;
  2743.   succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY);
  2744.   succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE);
  2745.   MZ_FREE(pComp); return succeeded;
  2746. }
  2747.  
  2748. typedef struct
  2749. {
  2750.   size_t m_size, m_capacity;
  2751.   mz_uint8 *m_pBuf;
  2752.   mz_bool m_expandable;
  2753. } tdefl_output_buffer;
  2754.  
  2755. static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser)
  2756. {
  2757.   tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
  2758.   size_t new_size = p->m_size + len;
  2759.   if (new_size > p->m_capacity)
  2760.   {
  2761.     size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE;
  2762.     do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity);
  2763.     pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE;
  2764.     p->m_pBuf = pNew_buf; p->m_capacity = new_capacity;
  2765.   }
  2766.   memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size;
  2767.   return MZ_TRUE;
  2768. }
  2769.  
  2770. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
  2771. {
  2772.   tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);
  2773.   if (!pOut_len) return MZ_FALSE; else *pOut_len = 0;
  2774.   out_buf.m_expandable = MZ_TRUE;
  2775.   if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL;
  2776.   *pOut_len = out_buf.m_size; return out_buf.m_pBuf;
  2777. }
  2778.  
  2779. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
  2780. {
  2781.   tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);
  2782.   if (!pOut_buf) return 0;
  2783.   out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len;
  2784.   if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0;
  2785.   return out_buf.m_size;
  2786. }
  2787.  
  2788. #ifndef MINIZ_NO_ZLIB_APIS
  2789. static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32,  16, 32, 128, 256,  512, 768, 1500 };
  2790.  
  2791. // level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files).
  2792. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy)
  2793. {
  2794.   mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
  2795.   if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
  2796.  
  2797.   if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
  2798.   else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES;
  2799.   else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK;
  2800.   else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
  2801.   else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES;
  2802.  
  2803.   return comp_flags;
  2804. }
  2805. #endif //MINIZ_NO_ZLIB_APIS
  2806.  
  2807. #ifdef _MSC_VER
  2808. #pragma warning (push)
  2809. #pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal)
  2810. #endif
  2811.  
  2812. // Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at
  2813. // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
  2814. // This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck.
  2815. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip)
  2816. {
  2817.   // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined.
  2818.   static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32,  16, 32, 128, 256,  512, 768, 1500 };
  2819.   tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0;
  2820.   if (!pComp) return NULL;
  2821.   MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; }
  2822.   // write dummy header
  2823.   for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf);
  2824.   // compress image data
  2825.   tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER);
  2826.   for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); }
  2827.   if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2828.   // write real header
  2829.   *pLen_out = out_buf.m_size-41;
  2830.   {
  2831.     static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
  2832.     mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,
  2833.       0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,chans[num_chans],0,0,0,0,0,0,0,
  2834.       (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54};
  2835.     c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24);
  2836.     memcpy(out_buf.m_pBuf, pnghdr, 41);
  2837.   }
  2838.   // write footer (IDAT CRC-32, followed by IEND chunk)
  2839.   if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2840.   c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24);
  2841.   // compute final size of file, grab compressed data buffer and return
  2842.   *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf;
  2843. }
  2844. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out)
  2845. {
  2846.   // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out)
  2847.   return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE);
  2848. }
  2849.  
  2850. #endif // MINIZ_NO_COMPRESSION
  2851.  
  2852. #ifdef _MSC_VER
  2853. #pragma warning (pop)
  2854. #endif
  2855.  
  2856. // ------------------- .ZIP archive reading
  2857.  
  2858. #ifndef MINIZ_NO_ARCHIVE_APIS
  2859.  
  2860. #ifdef MINIZ_NO_STDIO
  2861.   #define MZ_FILE void *
  2862. #else
  2863.   #include <stdio.h>
  2864.   #include <sys/stat.h>
  2865.  
  2866.   #if defined(_MSC_VER) || defined(__MINGW64__)
  2867.     static FILE *mz_fopen(const char *pFilename, const char *pMode)
  2868.     {
  2869.       FILE* pFile = NULL;
  2870.       fopen_s(&pFile, pFilename, pMode);
  2871.       return pFile;
  2872.     }
  2873.     static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream)
  2874.     {
  2875.       FILE* pFile = NULL;
  2876.       if (freopen_s(&pFile, pPath, pMode, pStream))
  2877.         return NULL;
  2878.       return pFile;
  2879.     }
  2880.     #ifndef MINIZ_NO_TIME
  2881.       #include <sys/utime.h>
  2882.     #endif
  2883.     #define MZ_FILE FILE
  2884.     #define MZ_FOPEN mz_fopen
  2885.     #define MZ_FCLOSE fclose
  2886.     #define MZ_FREAD fread
  2887.     #define MZ_FWRITE fwrite
  2888.     #define MZ_FTELL64 _ftelli64
  2889.     #define MZ_FSEEK64 _fseeki64
  2890.     #define MZ_FILE_STAT_STRUCT _stat
  2891.     #define MZ_FILE_STAT _stat
  2892.     #define MZ_FFLUSH fflush
  2893.     #define MZ_FREOPEN mz_freopen
  2894.     #define MZ_DELETE_FILE remove
  2895.   #elif defined(__MINGW32__)
  2896.     #ifndef MINIZ_NO_TIME
  2897.       #include <sys/utime.h>
  2898.     #endif
  2899.     #define MZ_FILE FILE
  2900.     #define MZ_FOPEN(f, m) fopen(f, m)
  2901.     #define MZ_FCLOSE fclose
  2902.     #define MZ_FREAD fread
  2903.     #define MZ_FWRITE fwrite
  2904.     #define MZ_FTELL64 ftello64
  2905.     #define MZ_FSEEK64 fseeko64
  2906.     #define MZ_FILE_STAT_STRUCT _stat
  2907.     #define MZ_FILE_STAT _stat
  2908.     #define MZ_FFLUSH fflush
  2909.     #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  2910.     #define MZ_DELETE_FILE remove
  2911.   #elif defined(__TINYC__)
  2912.     #ifndef MINIZ_NO_TIME
  2913.       #include <sys/utime.h>
  2914.     #endif
  2915.     #define MZ_FILE FILE
  2916.     #define MZ_FOPEN(f, m) fopen(f, m)
  2917.     #define MZ_FCLOSE fclose
  2918.     #define MZ_FREAD fread
  2919.     #define MZ_FWRITE fwrite
  2920.     #define MZ_FTELL64 ftell
  2921.     #define MZ_FSEEK64 fseek
  2922.     #define MZ_FILE_STAT_STRUCT stat
  2923.     #define MZ_FILE_STAT stat
  2924.     #define MZ_FFLUSH fflush
  2925.     #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  2926.     #define MZ_DELETE_FILE remove
  2927.   #elif defined(__GNUC__) && _LARGEFILE64_SOURCE
  2928.     #ifndef MINIZ_NO_TIME
  2929.       #include <utime.h>
  2930.     #endif
  2931.     #define MZ_FILE FILE
  2932.     #define MZ_FOPEN(f, m) fopen64(f, m)
  2933.     #define MZ_FCLOSE fclose
  2934.     #define MZ_FREAD fread
  2935.     #define MZ_FWRITE fwrite
  2936.     #define MZ_FTELL64 ftello64
  2937.     #define MZ_FSEEK64 fseeko64
  2938.     #define MZ_FILE_STAT_STRUCT stat64
  2939.     #define MZ_FILE_STAT stat64
  2940.     #define MZ_FFLUSH fflush
  2941.     #define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
  2942.     #define MZ_DELETE_FILE remove
  2943.   #else
  2944.     #ifndef MINIZ_NO_TIME
  2945.       #include <utime.h>
  2946.     #endif
  2947.     #define MZ_FILE FILE
  2948.     #define MZ_FOPEN(f, m) fopen(f, m)
  2949.     #define MZ_FCLOSE fclose
  2950.     #define MZ_FREAD fread
  2951.     #define MZ_FWRITE fwrite
  2952.     #define MZ_FTELL64 ftello
  2953.     #define MZ_FSEEK64 fseeko
  2954.     #define MZ_FILE_STAT_STRUCT stat
  2955.     #define MZ_FILE_STAT stat
  2956.     #define MZ_FFLUSH fflush
  2957.     #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  2958.     #define MZ_DELETE_FILE remove
  2959.   #endif // #ifdef _MSC_VER
  2960. #endif // #ifdef MINIZ_NO_STDIO
  2961.  
  2962. #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
  2963.  
  2964. // Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff.
  2965. enum
  2966. {
  2967.   // ZIP archive identifiers and record sizes
  2968.   MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
  2969.   MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
  2970.   // Central directory header record offsets
  2971.   MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
  2972.   MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16,
  2973.   MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
  2974.   MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
  2975.   // Local directory header offsets
  2976.   MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10,
  2977.   MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
  2978.   MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
  2979.   // End of central directory offsets
  2980.   MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
  2981.   MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
  2982. };
  2983.  
  2984. typedef struct
  2985. {
  2986.   void *m_p;
  2987.   size_t m_size, m_capacity;
  2988.   mz_uint m_element_size;
  2989. } mz_zip_array;
  2990.  
  2991. struct mz_zip_internal_state_tag
  2992. {
  2993.   mz_zip_array m_central_dir;
  2994.   mz_zip_array m_central_dir_offsets;
  2995.   mz_zip_array m_sorted_central_dir_offsets;
  2996.   MZ_FILE *m_pFile;
  2997.   void *m_pMem;
  2998.   size_t m_mem_size;
  2999.   size_t m_mem_capacity;
  3000. };
  3001.  
  3002. #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size
  3003. #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index]
  3004.  
  3005. static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray)
  3006. {
  3007.   pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
  3008.   memset(pArray, 0, sizeof(mz_zip_array));
  3009. }
  3010.  
  3011. static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing)
  3012. {
  3013.   void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE;
  3014.   if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; }
  3015.   if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE;
  3016.   pArray->m_p = pNew_p; pArray->m_capacity = new_capacity;
  3017.   return MZ_TRUE;
  3018. }
  3019.  
  3020. static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing)
  3021. {
  3022.   if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; }
  3023.   return MZ_TRUE;
  3024. }
  3025.  
  3026. static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing)
  3027. {
  3028.   if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; }
  3029.   pArray->m_size = new_size;
  3030.   return MZ_TRUE;
  3031. }
  3032.  
  3033. static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n)
  3034. {
  3035.   return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
  3036. }
  3037.  
  3038. static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n)
  3039. {
  3040.   size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE;
  3041.   memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size);
  3042.   return MZ_TRUE;
  3043. }
  3044.  
  3045. #ifndef MINIZ_NO_TIME
  3046. static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date)
  3047. {
  3048.   struct tm tm;
  3049.   memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1;
  3050.   tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31;
  3051.   tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62;
  3052.   return mktime(&tm);
  3053. }
  3054.  
  3055. static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date)
  3056. {
  3057. #ifdef _MSC_VER
  3058.   struct tm tm_struct;
  3059.   struct tm *tm = &tm_struct;
  3060.   errno_t err = localtime_s(tm, &time);
  3061.   if (err)
  3062.   {
  3063.     *pDOS_date = 0; *pDOS_time = 0;
  3064.     return;
  3065.   }
  3066. #else
  3067.   struct tm *tm = localtime(&time);
  3068. #endif
  3069.   *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1));
  3070.   *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday);
  3071. }
  3072. #endif
  3073.  
  3074. #ifndef MINIZ_NO_STDIO
  3075. static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date)
  3076. {
  3077. #ifdef MINIZ_NO_TIME
  3078.   (void)pFilename; *pDOS_date = *pDOS_time = 0;
  3079. #else
  3080.   struct MZ_FILE_STAT_STRUCT file_stat;
  3081.   // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
  3082.   if (MZ_FILE_STAT(pFilename, &file_stat) != 0)
  3083.     return MZ_FALSE;
  3084.   mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
  3085. #endif // #ifdef MINIZ_NO_TIME
  3086.   return MZ_TRUE;
  3087. }
  3088.  
  3089. #ifndef MINIZ_NO_TIME
  3090. static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time)
  3091. {
  3092.   struct utimbuf t; t.actime = access_time; t.modtime = modified_time;
  3093.   return !utime(pFilename, &t);
  3094. }
  3095. #endif // #ifndef MINIZ_NO_TIME
  3096. #endif // #ifndef MINIZ_NO_STDIO
  3097.  
  3098. static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags)
  3099. {
  3100.   (void)flags;
  3101.   if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  3102.     return MZ_FALSE;
  3103.  
  3104.   if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  3105.   if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  3106.   if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  3107.  
  3108.   pZip->m_zip_mode = MZ_ZIP_MODE_READING;
  3109.   pZip->m_archive_size = 0;
  3110.   pZip->m_central_directory_file_ofs = 0;
  3111.   pZip->m_total_files = 0;
  3112.  
  3113.   if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  3114.     return MZ_FALSE;
  3115.   memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  3116.   MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));
  3117.   MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));
  3118.   MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));
  3119.   return MZ_TRUE;
  3120. }
  3121.  
  3122. static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index)
  3123. {
  3124.   const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;
  3125.   const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
  3126.   mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3127.   mz_uint8 l = 0, r = 0;
  3128.   pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  3129.   pE = pL + MZ_MIN(l_len, r_len);
  3130.   while (pL < pE)
  3131.   {
  3132.     if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
  3133.       break;
  3134.     pL++; pR++;
  3135.   }
  3136.   return (pL == pE) ? (l_len < r_len) : (l < r);
  3137. }
  3138.  
  3139. #define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END
  3140.  
  3141. // Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.)
  3142. static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip)
  3143. {
  3144.   mz_zip_internal_state *pState = pZip->m_pState;
  3145.   const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  3146.   const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  3147.   mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  3148.   const int size = pZip->m_total_files;
  3149.   int start = (size - 2) >> 1, end;
  3150.   while (start >= 0)
  3151.   {
  3152.     int child, root = start;
  3153.     for ( ; ; )
  3154.     {
  3155.       if ((child = (root << 1) + 1) >= size)
  3156.         break;
  3157.       child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])));
  3158.       if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))
  3159.         break;
  3160.       MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child;
  3161.     }
  3162.     start--;
  3163.   }
  3164.  
  3165.   end = size - 1;
  3166.   while (end > 0)
  3167.   {
  3168.     int child, root = 0;
  3169.     MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
  3170.     for ( ; ; )
  3171.     {
  3172.       if ((child = (root << 1) + 1) >= end)
  3173.         break;
  3174.       child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]));
  3175.       if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))
  3176.         break;
  3177.       MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child;
  3178.     }
  3179.     end--;
  3180.   }
  3181. }
  3182.  
  3183. static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags)
  3184. {
  3185.   mz_uint cdir_size, num_this_disk, cdir_disk_index;
  3186.   mz_uint64 cdir_ofs;
  3187.   mz_int64 cur_file_ofs;
  3188.   const mz_uint8 *p;
  3189.   mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
  3190.   mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
  3191.   // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there.
  3192.   if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  3193.     return MZ_FALSE;
  3194.   // Find the end of central directory record by scanning the file from the end towards the beginning.
  3195.   cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
  3196.   for ( ; ; )
  3197.   {
  3198.     int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
  3199.     if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
  3200.       return MZ_FALSE;
  3201.     for (i = n - 4; i >= 0; --i)
  3202.       if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)
  3203.         break;
  3204.     if (i >= 0)
  3205.     {
  3206.       cur_file_ofs += i;
  3207.       break;
  3208.     }
  3209.     if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
  3210.       return MZ_FALSE;
  3211.     cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
  3212.   }
  3213.   // Read and verify the end of central directory record.
  3214.   if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  3215.     return MZ_FALSE;
  3216.   if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
  3217.       ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
  3218.     return MZ_FALSE;
  3219.  
  3220.   num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
  3221.   cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
  3222.   if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1)))
  3223.     return MZ_FALSE;
  3224.  
  3225.   if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
  3226.     return MZ_FALSE;
  3227.  
  3228.   cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
  3229.   if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size)
  3230.     return MZ_FALSE;
  3231.  
  3232.   pZip->m_central_directory_file_ofs = cdir_ofs;
  3233.  
  3234.   if (pZip->m_total_files)
  3235.   {
  3236.      mz_uint i, n;
  3237.  
  3238.     // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices.
  3239.     if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) ||
  3240.         (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE)))
  3241.       return MZ_FALSE;
  3242.  
  3243.     if (sort_central_dir)
  3244.     {
  3245.       if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE))
  3246.         return MZ_FALSE;
  3247.     }
  3248.  
  3249.     if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size)
  3250.       return MZ_FALSE;
  3251.  
  3252.     // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported).
  3253.     p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
  3254.     for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i)
  3255.     {
  3256.       mz_uint total_header_size, comp_size, decomp_size, disk_index;
  3257.       if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
  3258.         return MZ_FALSE;
  3259.       MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
  3260.       if (sort_central_dir)
  3261.         MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i;
  3262.       comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  3263.       decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  3264.       if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF))
  3265.         return MZ_FALSE;
  3266.       disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
  3267.       if ((disk_index != num_this_disk) && (disk_index != 1))
  3268.         return MZ_FALSE;
  3269.       if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
  3270.         return MZ_FALSE;
  3271.       if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n)
  3272.         return MZ_FALSE;
  3273.       n -= total_header_size; p += total_header_size;
  3274.     }
  3275.   }
  3276.  
  3277.   if (sort_central_dir)
  3278.     mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
  3279.  
  3280.   return MZ_TRUE;
  3281. }
  3282.  
  3283. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags)
  3284. {
  3285.   if ((!pZip) || (!pZip->m_pRead))
  3286.     return MZ_FALSE;
  3287.   if (!mz_zip_reader_init_internal(pZip, flags))
  3288.     return MZ_FALSE;
  3289.   pZip->m_archive_size = size;
  3290.   if (!mz_zip_reader_read_central_dir(pZip, flags))
  3291.   {
  3292.     mz_zip_reader_end(pZip);
  3293.     return MZ_FALSE;
  3294.   }
  3295.   return MZ_TRUE;
  3296. }
  3297.  
  3298. static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)
  3299. {
  3300.   mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  3301.   size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
  3302.   memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
  3303.   return s;
  3304. }
  3305.  
  3306. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags)
  3307. {
  3308.   if (!mz_zip_reader_init_internal(pZip, flags))
  3309.     return MZ_FALSE;
  3310.   pZip->m_archive_size = size;
  3311.   pZip->m_pRead = mz_zip_mem_read_func;
  3312.   pZip->m_pIO_opaque = pZip;
  3313. #ifdef __cplusplus
  3314.   pZip->m_pState->m_pMem = const_cast<void *>(pMem);
  3315. #else
  3316.   pZip->m_pState->m_pMem = (void *)pMem;
  3317. #endif
  3318.   pZip->m_pState->m_mem_size = size;
  3319.   if (!mz_zip_reader_read_central_dir(pZip, flags))
  3320.   {
  3321.     mz_zip_reader_end(pZip);
  3322.     return MZ_FALSE;
  3323.   }
  3324.   return MZ_TRUE;
  3325. }
  3326.  
  3327. #ifndef MINIZ_NO_STDIO
  3328. static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)
  3329. {
  3330.   mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  3331.   mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  3332.   if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  3333.     return 0;
  3334.   return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
  3335. }
  3336.  
  3337. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags)
  3338. {
  3339.   mz_uint64 file_size;
  3340.   MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
  3341.   if (!pFile)
  3342.     return MZ_FALSE;
  3343.   if (MZ_FSEEK64(pFile, 0, SEEK_END))
  3344.   {
  3345.     MZ_FCLOSE(pFile);
  3346.     return MZ_FALSE;
  3347.   }
  3348.   file_size = MZ_FTELL64(pFile);
  3349.   if (!mz_zip_reader_init_internal(pZip, flags))
  3350.   {
  3351.     MZ_FCLOSE(pFile);
  3352.     return MZ_FALSE;
  3353.   }
  3354.   pZip->m_pRead = mz_zip_file_read_func;
  3355.   pZip->m_pIO_opaque = pZip;
  3356.   pZip->m_pState->m_pFile = pFile;
  3357.   pZip->m_archive_size = file_size;
  3358.   if (!mz_zip_reader_read_central_dir(pZip, flags))
  3359.   {
  3360.     mz_zip_reader_end(pZip);
  3361.     return MZ_FALSE;
  3362.   }
  3363.   return MZ_TRUE;
  3364. }
  3365. #endif // #ifndef MINIZ_NO_STDIO
  3366.  
  3367. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip)
  3368. {
  3369.   return pZip ? pZip->m_total_files : 0;
  3370. }
  3371.  
  3372. static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index)
  3373. {
  3374.   if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3375.     return NULL;
  3376.   return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));
  3377. }
  3378.  
  3379. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index)
  3380. {
  3381.   mz_uint m_bit_flag;
  3382.   const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3383.   if (!p)
  3384.     return MZ_FALSE;
  3385.   m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  3386.   return (m_bit_flag & 1);
  3387. }
  3388.  
  3389. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index)
  3390. {
  3391.   mz_uint filename_len, external_attr;
  3392.   const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3393.   if (!p)
  3394.     return MZ_FALSE;
  3395.  
  3396.   // First see if the filename ends with a '/' character.
  3397.   filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3398.   if (filename_len)
  3399.   {
  3400.     if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
  3401.       return MZ_TRUE;
  3402.   }
  3403.  
  3404.   // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct.
  3405.   // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field.
  3406.   // FIXME: Remove this check? Is it necessary - we already check the filename.
  3407.   external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  3408.   if ((external_attr & 0x10) != 0)
  3409.     return MZ_TRUE;
  3410.  
  3411.   return MZ_FALSE;
  3412. }
  3413.  
  3414. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat)
  3415. {
  3416.   mz_uint n;
  3417.   const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3418.   if ((!p) || (!pStat))
  3419.     return MZ_FALSE;
  3420.  
  3421.   // Unpack the central directory record.
  3422.   pStat->m_file_index = file_index;
  3423.   pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
  3424.   pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
  3425.   pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
  3426.   pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  3427.   pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
  3428. #ifndef MINIZ_NO_TIME
  3429.   pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
  3430. #endif
  3431.   pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
  3432.   pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  3433.   pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  3434.   pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
  3435.   pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  3436.   pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  3437.  
  3438.   // Copy as much of the filename and comment as possible.
  3439.   n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
  3440.   memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0';
  3441.  
  3442.   n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
  3443.   pStat->m_comment_size = n;
  3444.   memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0';
  3445.  
  3446.   return MZ_TRUE;
  3447. }
  3448.  
  3449. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size)
  3450. {
  3451.   mz_uint n;
  3452.   const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3453.   if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; }
  3454.   n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3455.   if (filename_buf_size)
  3456.   {
  3457.     n = MZ_MIN(n, filename_buf_size - 1);
  3458.     memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  3459.     pFilename[n] = '\0';
  3460.   }
  3461.   return n + 1;
  3462. }
  3463.  
  3464. static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags)
  3465. {
  3466.   mz_uint i;
  3467.   if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE)
  3468.     return 0 == memcmp(pA, pB, len);
  3469.   for (i = 0; i < len; ++i)
  3470.     if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i]))
  3471.       return MZ_FALSE;
  3472.   return MZ_TRUE;
  3473. }
  3474.  
  3475. static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len)
  3476. {
  3477.   const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;
  3478.   mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3479.   mz_uint8 l = 0, r = 0;
  3480.   pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  3481.   pE = pL + MZ_MIN(l_len, r_len);
  3482.   while (pL < pE)
  3483.   {
  3484.     if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
  3485.       break;
  3486.     pL++; pR++;
  3487.   }
  3488.   return (pL == pE) ? (int)(l_len - r_len) : (l - r);
  3489. }
  3490.  
  3491. static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename)
  3492. {
  3493.   mz_zip_internal_state *pState = pZip->m_pState;
  3494.   const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  3495.   const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  3496.   mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  3497.   const int size = pZip->m_total_files;
  3498.   const mz_uint filename_len = (mz_uint)strlen(pFilename);
  3499.   int l = 0, h = size - 1;
  3500.   while (l <= h)
  3501.   {
  3502.     int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len);
  3503.     if (!comp)
  3504.       return file_index;
  3505.     else if (comp < 0)
  3506.       l = m + 1;
  3507.     else
  3508.       h = m - 1;
  3509.   }
  3510.   return -1;
  3511. }
  3512.  
  3513. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags)
  3514. {
  3515.   mz_uint file_index; size_t name_len, comment_len;
  3516.   if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3517.     return -1;
  3518.   if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
  3519.     return mz_zip_reader_locate_file_binary_search(pZip, pName);
  3520.   name_len = strlen(pName); if (name_len > 0xFFFF) return -1;
  3521.   comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1;
  3522.   for (file_index = 0; file_index < pZip->m_total_files; file_index++)
  3523.   {
  3524.     const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));
  3525.     mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3526.     const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  3527.     if (filename_len < name_len)
  3528.       continue;
  3529.     if (comment_len)
  3530.     {
  3531.       mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  3532.       const char *pFile_comment = pFilename + filename_len + file_extra_len;
  3533.       if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags)))
  3534.         continue;
  3535.     }
  3536.     if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len))
  3537.     {
  3538.       int ofs = filename_len - 1;
  3539.       do
  3540.       {
  3541.         if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':'))
  3542.           break;
  3543.       } while (--ofs >= 0);
  3544.       ofs++;
  3545.       pFilename += ofs; filename_len -= ofs;
  3546.     }
  3547.     if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
  3548.       return file_index;
  3549.   }
  3550.   return -1;
  3551. }
  3552.  
  3553. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)
  3554. {
  3555.   int status = TINFL_STATUS_DONE;
  3556.   mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
  3557.   mz_zip_archive_file_stat file_stat;
  3558.   void *pRead_buf;
  3559.   mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  3560.   tinfl_decompressor inflator;
  3561.  
  3562.   if ((buf_size) && (!pBuf))
  3563.     return MZ_FALSE;
  3564.  
  3565.   if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  3566.     return MZ_FALSE;
  3567.  
  3568.   // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes)
  3569.   if (!file_stat.m_comp_size)
  3570.     return MZ_TRUE;
  3571.  
  3572.   // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers).
  3573.   // I'm torn how to handle this case - should it fail instead?
  3574.   if (mz_zip_reader_is_file_a_directory(pZip, file_index))
  3575.     return MZ_TRUE;
  3576.  
  3577.   // Encryption and patch files are not supported.
  3578.   if (file_stat.m_bit_flag & (1 | 32))
  3579.     return MZ_FALSE;
  3580.  
  3581.   // This function only supports stored and deflate.
  3582.   if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))
  3583.     return MZ_FALSE;
  3584.  
  3585.   // Ensure supplied output buffer is large enough.
  3586.   needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size;
  3587.   if (buf_size < needed_size)
  3588.     return MZ_FALSE;
  3589.  
  3590.   // Read and parse the local directory entry.
  3591.   cur_file_ofs = file_stat.m_local_header_ofs;
  3592.   if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  3593.     return MZ_FALSE;
  3594.   if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  3595.     return MZ_FALSE;
  3596.  
  3597.   cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  3598.   if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  3599.     return MZ_FALSE;
  3600.  
  3601.   if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))
  3602.   {
  3603.     // The file is stored or the caller has requested the compressed data.
  3604.     if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size)
  3605.       return MZ_FALSE;
  3606.     return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
  3607.   }
  3608.  
  3609.   // Decompress the file either directly from memory or from a file input buffer.
  3610.   tinfl_init(&inflator);
  3611.  
  3612.   if (pZip->m_pState->m_pMem)
  3613.   {
  3614.     // Read directly from the archive in memory.
  3615.     pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  3616.     read_buf_size = read_buf_avail = file_stat.m_comp_size;
  3617.     comp_remaining = 0;
  3618.   }
  3619.   else if (pUser_read_buf)
  3620.   {
  3621.     // Use a user provided read buffer.
  3622.     if (!user_read_buf_size)
  3623.       return MZ_FALSE;
  3624.     pRead_buf = (mz_uint8 *)pUser_read_buf;
  3625.     read_buf_size = user_read_buf_size;
  3626.     read_buf_avail = 0;
  3627.     comp_remaining = file_stat.m_comp_size;
  3628.   }
  3629.   else
  3630.   {
  3631.     // Temporarily allocate a read buffer.
  3632.     read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE);
  3633. #ifdef _MSC_VER
  3634.     if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  3635. #else
  3636.     if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  3637. #endif
  3638.       return MZ_FALSE;
  3639.     if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))
  3640.       return MZ_FALSE;
  3641.     read_buf_avail = 0;
  3642.     comp_remaining = file_stat.m_comp_size;
  3643.   }
  3644.  
  3645.   do
  3646.   {
  3647.     size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
  3648.     if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))
  3649.     {
  3650.       read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  3651.       if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3652.       {
  3653.         status = TINFL_STATUS_FAILED;
  3654.         break;
  3655.       }
  3656.       cur_file_ofs += read_buf_avail;
  3657.       comp_remaining -= read_buf_avail;
  3658.       read_buf_ofs = 0;
  3659.     }
  3660.     in_buf_size = (size_t)read_buf_avail;
  3661.     status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
  3662.     read_buf_avail -= in_buf_size;
  3663.     read_buf_ofs += in_buf_size;
  3664.     out_buf_ofs += out_buf_size;
  3665.   } while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
  3666.  
  3667.   if (status == TINFL_STATUS_DONE)
  3668.   {
  3669.     // Make sure the entire file was decompressed, and check its CRC.
  3670.     if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
  3671.       status = TINFL_STATUS_FAILED;
  3672.   }
  3673.  
  3674.   if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
  3675.     pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3676.  
  3677.   return status == TINFL_STATUS_DONE;
  3678. }
  3679.  
  3680. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)
  3681. {
  3682.   int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  3683.   if (file_index < 0)
  3684.     return MZ_FALSE;
  3685.   return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size);
  3686. }
  3687.  
  3688. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags)
  3689. {
  3690.   return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0);
  3691. }
  3692.  
  3693. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags)
  3694. {
  3695.   return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0);
  3696. }
  3697.  
  3698. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags)
  3699. {
  3700.   mz_uint64 comp_size, uncomp_size, alloc_size;
  3701.   const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3702.   void *pBuf;
  3703.  
  3704.   if (pSize)
  3705.     *pSize = 0;
  3706.   if (!p)
  3707.     return NULL;
  3708.  
  3709.   comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  3710.   uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  3711.  
  3712.   alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
  3713. #ifdef _MSC_VER
  3714.   if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  3715. #else
  3716.   if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  3717. #endif
  3718.     return NULL;
  3719.   if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
  3720.     return NULL;
  3721.  
  3722.   if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags))
  3723.   {
  3724.     pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  3725.     return NULL;
  3726.   }
  3727.  
  3728.   if (pSize) *pSize = (size_t)alloc_size;
  3729.   return pBuf;
  3730. }
  3731.  
  3732. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags)
  3733. {
  3734.   int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  3735.   if (file_index < 0)
  3736.   {
  3737.     if (pSize) *pSize = 0;
  3738.     return MZ_FALSE;
  3739.   }
  3740.   return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
  3741. }
  3742.  
  3743. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)
  3744. {
  3745.   int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT;
  3746.   mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs;
  3747.   mz_zip_archive_file_stat file_stat;
  3748.   void *pRead_buf = NULL; void *pWrite_buf = NULL;
  3749.   mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  3750.  
  3751.   if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  3752.     return MZ_FALSE;
  3753.  
  3754.   // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes)
  3755.   if (!file_stat.m_comp_size)
  3756.     return MZ_TRUE;
  3757.  
  3758.   // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers).
  3759.   // I'm torn how to handle this case - should it fail instead?
  3760.   if (mz_zip_reader_is_file_a_directory(pZip, file_index))
  3761.     return MZ_TRUE;
  3762.  
  3763.   // Encryption and patch files are not supported.
  3764.   if (file_stat.m_bit_flag & (1 | 32))
  3765.     return MZ_FALSE;
  3766.  
  3767.   // This function only supports stored and deflate.
  3768.   if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))
  3769.     return MZ_FALSE;
  3770.  
  3771.   // Read and parse the local directory entry.
  3772.   cur_file_ofs = file_stat.m_local_header_ofs;
  3773.   if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  3774.     return MZ_FALSE;
  3775.   if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  3776.     return MZ_FALSE;
  3777.  
  3778.   cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  3779.   if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  3780.     return MZ_FALSE;
  3781.  
  3782.   // Decompress the file either directly from memory or from a file input buffer.
  3783.   if (pZip->m_pState->m_pMem)
  3784.   {
  3785.     pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  3786.     read_buf_size = read_buf_avail = file_stat.m_comp_size;
  3787.     comp_remaining = 0;
  3788.   }
  3789.   else
  3790.   {
  3791.     read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE);
  3792.     if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))
  3793.       return MZ_FALSE;
  3794.     read_buf_avail = 0;
  3795.     comp_remaining = file_stat.m_comp_size;
  3796.   }
  3797.  
  3798.   if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))
  3799.   {
  3800.     // The file is stored or the caller has requested the compressed data.
  3801.     if (pZip->m_pState->m_pMem)
  3802.     {
  3803. #ifdef _MSC_VER
  3804.       if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF))
  3805. #else
  3806.       if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF))
  3807. #endif
  3808.         return MZ_FALSE;
  3809.       if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
  3810.         status = TINFL_STATUS_FAILED;
  3811.       else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  3812.         file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size);
  3813.       cur_file_ofs += file_stat.m_comp_size;
  3814.       out_buf_ofs += file_stat.m_comp_size;
  3815.       comp_remaining = 0;
  3816.     }
  3817.     else
  3818.     {
  3819.       while (comp_remaining)
  3820.       {
  3821.         read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  3822.         if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3823.         {
  3824.           status = TINFL_STATUS_FAILED;
  3825.           break;
  3826.         }
  3827.  
  3828.         if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  3829.           file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
  3830.  
  3831.         if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3832.         {
  3833.           status = TINFL_STATUS_FAILED;
  3834.           break;
  3835.         }
  3836.         cur_file_ofs += read_buf_avail;
  3837.         out_buf_ofs += read_buf_avail;
  3838.         comp_remaining -= read_buf_avail;
  3839.       }
  3840.     }
  3841.   }
  3842.   else
  3843.   {
  3844.     tinfl_decompressor inflator;
  3845.     tinfl_init(&inflator);
  3846.  
  3847.     if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE)))
  3848.       status = TINFL_STATUS_FAILED;
  3849.     else
  3850.     {
  3851.       do
  3852.       {
  3853.         mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  3854.         size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  3855.         if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))
  3856.         {
  3857.           read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  3858.           if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3859.           {
  3860.             status = TINFL_STATUS_FAILED;
  3861.             break;
  3862.           }
  3863.           cur_file_ofs += read_buf_avail;
  3864.           comp_remaining -= read_buf_avail;
  3865.           read_buf_ofs = 0;
  3866.         }
  3867.  
  3868.         in_buf_size = (size_t)read_buf_avail;
  3869.         status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
  3870.         read_buf_avail -= in_buf_size;
  3871.         read_buf_ofs += in_buf_size;
  3872.  
  3873.         if (out_buf_size)
  3874.         {
  3875.           if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size)
  3876.           {
  3877.             status = TINFL_STATUS_FAILED;
  3878.             break;
  3879.           }
  3880.           file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
  3881.           if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size)
  3882.           {
  3883.             status = TINFL_STATUS_FAILED;
  3884.             break;
  3885.           }
  3886.         }
  3887.       } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT));
  3888.     }
  3889.   }
  3890.  
  3891.   if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)))
  3892.   {
  3893.     // Make sure the entire file was decompressed, and check its CRC.
  3894.     if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32))
  3895.       status = TINFL_STATUS_FAILED;
  3896.   }
  3897.  
  3898.   if (!pZip->m_pState->m_pMem)
  3899.     pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3900.   if (pWrite_buf)
  3901.     pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
  3902.  
  3903.   return status == TINFL_STATUS_DONE;
  3904. }
  3905.  
  3906. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)
  3907. {
  3908.   int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  3909.   if (file_index < 0)
  3910.     return MZ_FALSE;
  3911.   return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags);
  3912. }
  3913.  
  3914. #ifndef MINIZ_NO_STDIO
  3915. static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n)
  3916. {
  3917.   (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque);
  3918. }
  3919.  
  3920. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags)
  3921. {
  3922.   mz_bool status;
  3923.   mz_zip_archive_file_stat file_stat;
  3924.   MZ_FILE *pFile;
  3925.   if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  3926.     return MZ_FALSE;
  3927.   pFile = MZ_FOPEN(pDst_filename, "wb");
  3928.   if (!pFile)
  3929.     return MZ_FALSE;
  3930.   status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags);
  3931.   if (MZ_FCLOSE(pFile) == EOF)
  3932.     return MZ_FALSE;
  3933. #ifndef MINIZ_NO_TIME
  3934.   if (status)
  3935.     mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
  3936. #endif
  3937.   return status;
  3938. }
  3939. #endif // #ifndef MINIZ_NO_STDIO
  3940.  
  3941. mz_bool mz_zip_reader_end(mz_zip_archive *pZip)
  3942. {
  3943.   if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3944.     return MZ_FALSE;
  3945.  
  3946.   if (pZip->m_pState)
  3947.   {
  3948.     mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL;
  3949.     mz_zip_array_clear(pZip, &pState->m_central_dir);
  3950.     mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  3951.     mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  3952.  
  3953. #ifndef MINIZ_NO_STDIO
  3954.     if (pState->m_pFile)
  3955.     {
  3956.       MZ_FCLOSE(pState->m_pFile);
  3957.       pState->m_pFile = NULL;
  3958.     }
  3959. #endif // #ifndef MINIZ_NO_STDIO
  3960.  
  3961.     pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  3962.   }
  3963.   pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  3964.  
  3965.   return MZ_TRUE;
  3966. }
  3967.  
  3968. #ifndef MINIZ_NO_STDIO
  3969. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags)
  3970. {
  3971.   int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
  3972.   if (file_index < 0)
  3973.     return MZ_FALSE;
  3974.   return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
  3975. }
  3976. #endif
  3977.  
  3978. // ------------------- .ZIP archive writing
  3979.  
  3980. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  3981.  
  3982. static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); }
  3983. static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); }
  3984. #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
  3985. #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
  3986.  
  3987. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size)
  3988. {
  3989.   if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  3990.     return MZ_FALSE;
  3991.  
  3992.   if (pZip->m_file_offset_alignment)
  3993.   {
  3994.     // Ensure user specified file offset alignment is a power of 2.
  3995.     if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
  3996.       return MZ_FALSE;
  3997.   }
  3998.  
  3999.   if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  4000.   if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  4001.   if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  4002.  
  4003.   pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  4004.   pZip->m_archive_size = existing_size;
  4005.   pZip->m_central_directory_file_ofs = 0;
  4006.   pZip->m_total_files = 0;
  4007.  
  4008.   if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  4009.     return MZ_FALSE;
  4010.   memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  4011.   MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));
  4012.   MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));
  4013.   MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));
  4014.   return MZ_TRUE;
  4015. }
  4016.  
  4017. static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)
  4018. {
  4019.   mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4020.   mz_zip_internal_state *pState = pZip->m_pState;
  4021.   mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
  4022. #ifdef _MSC_VER
  4023.   if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  4024. #else
  4025.   if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  4026. #endif
  4027.     return 0;
  4028.   if (new_size > pState->m_mem_capacity)
  4029.   {
  4030.     void *pNew_block;
  4031.     size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2;
  4032.     if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
  4033.       return 0;
  4034.     pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity;
  4035.   }
  4036.   memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
  4037.   pState->m_mem_size = (size_t)new_size;
  4038.   return n;
  4039. }
  4040.  
  4041. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size)
  4042. {
  4043.   pZip->m_pWrite = mz_zip_heap_write_func;
  4044.   pZip->m_pIO_opaque = pZip;
  4045.   if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
  4046.     return MZ_FALSE;
  4047.   if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning)))
  4048.   {
  4049.     if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size)))
  4050.     {
  4051.       mz_zip_writer_end(pZip);
  4052.       return MZ_FALSE;
  4053.     }
  4054.     pZip->m_pState->m_mem_capacity = initial_allocation_size;
  4055.   }
  4056.   return MZ_TRUE;
  4057. }
  4058.  
  4059. #ifndef MINIZ_NO_STDIO
  4060. static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)
  4061. {
  4062.   mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4063.   mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  4064.   if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  4065.     return 0;
  4066.   return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
  4067. }
  4068.  
  4069. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning)
  4070. {
  4071.   MZ_FILE *pFile;
  4072.   pZip->m_pWrite = mz_zip_file_write_func;
  4073.   pZip->m_pIO_opaque = pZip;
  4074.   if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
  4075.     return MZ_FALSE;
  4076.   if (NULL == (pFile = MZ_FOPEN(pFilename, "wb")))
  4077.   {
  4078.     mz_zip_writer_end(pZip);
  4079.     return MZ_FALSE;
  4080.   }
  4081.   pZip->m_pState->m_pFile = pFile;
  4082.   if (size_to_reserve_at_beginning)
  4083.   {
  4084.     mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf);
  4085.     do
  4086.     {
  4087.       size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
  4088.       if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n)
  4089.       {
  4090.         mz_zip_writer_end(pZip);
  4091.         return MZ_FALSE;
  4092.       }
  4093.       cur_ofs += n; size_to_reserve_at_beginning -= n;
  4094.     } while (size_to_reserve_at_beginning);
  4095.   }
  4096.   return MZ_TRUE;
  4097. }
  4098. #endif // #ifndef MINIZ_NO_STDIO
  4099.  
  4100. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename)
  4101. {
  4102.   mz_zip_internal_state *pState;
  4103.   if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  4104.     return MZ_FALSE;
  4105.   // No sense in trying to write to an archive that's already at the support max size
  4106.   if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  4107.     return MZ_FALSE;
  4108.  
  4109.   pState = pZip->m_pState;
  4110.  
  4111.   if (pState->m_pFile)
  4112.   {
  4113. #ifdef MINIZ_NO_STDIO
  4114.     pFilename; return MZ_FALSE;
  4115. #else
  4116.     // Archive is being read from stdio - try to reopen as writable.
  4117.     if (pZip->m_pIO_opaque != pZip)
  4118.       return MZ_FALSE;
  4119.     if (!pFilename)
  4120.       return MZ_FALSE;
  4121.     pZip->m_pWrite = mz_zip_file_write_func;
  4122.     if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile)))
  4123.     {
  4124.       // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it.
  4125.       mz_zip_reader_end(pZip);
  4126.       return MZ_FALSE;
  4127.     }
  4128. #endif // #ifdef MINIZ_NO_STDIO
  4129.   }
  4130.   else if (pState->m_pMem)
  4131.   {
  4132.     // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback.
  4133.     if (pZip->m_pIO_opaque != pZip)
  4134.       return MZ_FALSE;
  4135.     pState->m_mem_capacity = pState->m_mem_size;
  4136.     pZip->m_pWrite = mz_zip_heap_write_func;
  4137.   }
  4138.   // Archive is being read via a user provided read function - make sure the user has specified a write function too.
  4139.   else if (!pZip->m_pWrite)
  4140.     return MZ_FALSE;
  4141.  
  4142.   // Start writing new files at the archive's current central directory location.
  4143.   pZip->m_archive_size = pZip->m_central_directory_file_ofs;
  4144.   pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  4145.   pZip->m_central_directory_file_ofs = 0;
  4146.  
  4147.   return MZ_TRUE;
  4148. }
  4149.  
  4150. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags)
  4151. {
  4152.   return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0);
  4153. }
  4154.  
  4155. typedef struct
  4156. {
  4157.   mz_zip_archive *m_pZip;
  4158.   mz_uint64 m_cur_archive_file_ofs;
  4159.   mz_uint64 m_comp_size;
  4160. } mz_zip_writer_add_state;
  4161.  
  4162. static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser)
  4163. {
  4164.   mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
  4165.   if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len)
  4166.     return MZ_FALSE;
  4167.   pState->m_cur_archive_file_ofs += len;
  4168.   pState->m_comp_size += len;
  4169.   return MZ_TRUE;
  4170. }
  4171.  
  4172. static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date)
  4173. {
  4174.   (void)pZip;
  4175.   memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
  4176.   MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
  4177.   MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  4178.   MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
  4179.   MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
  4180.   MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
  4181.   MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
  4182.   MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
  4183.   MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
  4184.   MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  4185.   MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
  4186.   MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
  4187.   return MZ_TRUE;
  4188. }
  4189.  
  4190. static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes)
  4191. {
  4192.   (void)pZip;
  4193.   memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  4194.   MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
  4195.   MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  4196.   MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
  4197.   MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
  4198.   MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
  4199.   MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
  4200.   MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
  4201.   MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
  4202.   MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  4203.   MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
  4204.   MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
  4205.   MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
  4206.   MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
  4207.   MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
  4208.   return MZ_TRUE;
  4209. }
  4210.  
  4211. static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes)
  4212. {
  4213.   mz_zip_internal_state *pState = pZip->m_pState;
  4214.   mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
  4215.   size_t orig_central_dir_size = pState->m_central_dir.m_size;
  4216.   mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  4217.  
  4218.   // No zip64 support yet
  4219.   if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF))
  4220.     return MZ_FALSE;
  4221.  
  4222.   if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes))
  4223.     return MZ_FALSE;
  4224.  
  4225.   if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
  4226.       (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) ||
  4227.       (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) ||
  4228.       (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) ||
  4229.       (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1)))
  4230.   {
  4231.     // Try to push the central directory array back into its original state.
  4232.     mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);
  4233.     return MZ_FALSE;
  4234.   }
  4235.  
  4236.   return MZ_TRUE;
  4237. }
  4238.  
  4239. static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name)
  4240. {
  4241.   // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes.
  4242.   if (*pArchive_name == '/')
  4243.     return MZ_FALSE;
  4244.   while (*pArchive_name)
  4245.   {
  4246.     if ((*pArchive_name == '\\') || (*pArchive_name == ':'))
  4247.       return MZ_FALSE;
  4248.     pArchive_name++;
  4249.   }
  4250.   return MZ_TRUE;
  4251. }
  4252.  
  4253. static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip)
  4254. {
  4255.   mz_uint32 n;
  4256.   if (!pZip->m_file_offset_alignment)
  4257.     return 0;
  4258.   n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
  4259.   return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1);
  4260. }
  4261.  
  4262. static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n)
  4263. {
  4264.   char buf[4096];
  4265.   memset(buf, 0, MZ_MIN(sizeof(buf), n));
  4266.   while (n)
  4267.   {
  4268.     mz_uint32 s = MZ_MIN(sizeof(buf), n);
  4269.     if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
  4270.       return MZ_FALSE;
  4271.     cur_file_ofs += s; n -= s;
  4272.   }
  4273.   return MZ_TRUE;
  4274. }
  4275.  
  4276. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32)
  4277. {
  4278.   mz_uint16 method = 0, dos_time = 0, dos_date = 0;
  4279.   mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
  4280.   mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
  4281.   size_t archive_name_size;
  4282.   mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  4283.   tdefl_compressor *pComp = NULL;
  4284.   mz_bool store_data_uncompressed;
  4285.   mz_zip_internal_state *pState;
  4286.  
  4287.   if ((int)level_and_flags < 0)
  4288.     level_and_flags = MZ_DEFAULT_LEVEL;
  4289.   level = level_and_flags & 0xF;
  4290.   store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
  4291.  
  4292.   if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
  4293.     return MZ_FALSE;
  4294.  
  4295.   pState = pZip->m_pState;
  4296.  
  4297.   if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
  4298.     return MZ_FALSE;
  4299.   // No zip64 support yet
  4300.   if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF))
  4301.     return MZ_FALSE;
  4302.   if (!mz_zip_writer_validate_archive_name(pArchive_name))
  4303.     return MZ_FALSE;
  4304.  
  4305. #ifndef MINIZ_NO_TIME
  4306.   {
  4307.     time_t cur_time; time(&cur_time);
  4308.     mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
  4309.   }
  4310. #endif // #ifndef MINIZ_NO_TIME
  4311.  
  4312.   archive_name_size = strlen(pArchive_name);
  4313.   if (archive_name_size > 0xFFFF)
  4314.     return MZ_FALSE;
  4315.  
  4316.   num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  4317.  
  4318.   // no zip64 support yet
  4319.   if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF))
  4320.     return MZ_FALSE;
  4321.  
  4322.   if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/'))
  4323.   {
  4324.     // Set DOS Subdirectory attribute bit.
  4325.     ext_attributes |= 0x10;
  4326.     // Subdirectories cannot contain data.
  4327.     if ((buf_size) || (uncomp_size))
  4328.       return MZ_FALSE;
  4329.   }
  4330.  
  4331.   // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.)
  4332.   if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
  4333.     return MZ_FALSE;
  4334.  
  4335.   if ((!store_data_uncompressed) && (buf_size))
  4336.   {
  4337.     if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
  4338.       return MZ_FALSE;
  4339.   }
  4340.  
  4341.   if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header)))
  4342.   {
  4343.     pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  4344.     return MZ_FALSE;
  4345.   }
  4346.   local_dir_header_ofs += num_alignment_padding_bytes;
  4347.   if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }
  4348.   cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header);
  4349.  
  4350.   MZ_CLEAR_OBJ(local_dir_header);
  4351.   if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)
  4352.   {
  4353.     pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  4354.     return MZ_FALSE;
  4355.   }
  4356.   cur_archive_file_ofs += archive_name_size;
  4357.  
  4358.   if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  4359.   {
  4360.     uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size);
  4361.     uncomp_size = buf_size;
  4362.     if (uncomp_size <= 3)
  4363.     {
  4364.       level = 0;
  4365.       store_data_uncompressed = MZ_TRUE;
  4366.     }
  4367.   }
  4368.  
  4369.   if (store_data_uncompressed)
  4370.   {
  4371.     if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size)
  4372.     {
  4373.       pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  4374.       return MZ_FALSE;
  4375.     }
  4376.  
  4377.     cur_archive_file_ofs += buf_size;
  4378.     comp_size = buf_size;
  4379.  
  4380.     if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
  4381.       method = MZ_DEFLATED;
  4382.   }
  4383.   else if (buf_size)
  4384.   {
  4385.     mz_zip_writer_add_state state;
  4386.  
  4387.     state.m_pZip = pZip;
  4388.     state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  4389.     state.m_comp_size = 0;
  4390.  
  4391.     if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) ||
  4392.         (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE))
  4393.     {
  4394.       pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  4395.       return MZ_FALSE;
  4396.     }
  4397.  
  4398.     comp_size = state.m_comp_size;
  4399.     cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  4400.  
  4401.     method = MZ_DEFLATED;
  4402.   }
  4403.  
  4404.   pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  4405.   pComp = NULL;
  4406.  
  4407.   // no zip64 support yet
  4408.   if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  4409.     return MZ_FALSE;
  4410.  
  4411.   if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  4412.     return MZ_FALSE;
  4413.  
  4414.   if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))
  4415.     return MZ_FALSE;
  4416.  
  4417.   if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  4418.     return MZ_FALSE;
  4419.  
  4420.   pZip->m_total_files++;
  4421.   pZip->m_archive_size = cur_archive_file_ofs;
  4422.  
  4423.   return MZ_TRUE;
  4424. }
  4425.  
  4426. #ifndef MINIZ_NO_STDIO
  4427. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)
  4428. {
  4429.   mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
  4430.   mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
  4431.   mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0;
  4432.   size_t archive_name_size;
  4433.   mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  4434.   MZ_FILE *pSrc_file = NULL;
  4435.  
  4436.   if ((int)level_and_flags < 0)
  4437.     level_and_flags = MZ_DEFAULT_LEVEL;
  4438.   level = level_and_flags & 0xF;
  4439.  
  4440.   if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
  4441.     return MZ_FALSE;
  4442.   if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
  4443.     return MZ_FALSE;
  4444.   if (!mz_zip_writer_validate_archive_name(pArchive_name))
  4445.     return MZ_FALSE;
  4446.  
  4447.   archive_name_size = strlen(pArchive_name);
  4448.   if (archive_name_size > 0xFFFF)
  4449.     return MZ_FALSE;
  4450.  
  4451.   num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  4452.  
  4453.   // no zip64 support yet
  4454.   if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF))
  4455.     return MZ_FALSE;
  4456.  
  4457.   if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
  4458.     return MZ_FALSE;
  4459.    
  4460.   pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
  4461.   if (!pSrc_file)
  4462.     return MZ_FALSE;
  4463.   MZ_FSEEK64(pSrc_file, 0, SEEK_END);
  4464.   uncomp_size = MZ_FTELL64(pSrc_file);
  4465.   MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
  4466.  
  4467.   if (uncomp_size > 0xFFFFFFFF)
  4468.   {
  4469.     // No zip64 support yet
  4470.     MZ_FCLOSE(pSrc_file);
  4471.     return MZ_FALSE;
  4472.   }
  4473.   if (uncomp_size <= 3)
  4474.     level = 0;
  4475.  
  4476.   if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header)))
  4477.   {
  4478.     MZ_FCLOSE(pSrc_file);
  4479.     return MZ_FALSE;
  4480.   }
  4481.   local_dir_header_ofs += num_alignment_padding_bytes;
  4482.   if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }
  4483.   cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header);
  4484.  
  4485.   MZ_CLEAR_OBJ(local_dir_header);
  4486.   if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)
  4487.   {
  4488.     MZ_FCLOSE(pSrc_file);
  4489.     return MZ_FALSE;
  4490.   }
  4491.   cur_archive_file_ofs += archive_name_size;
  4492.  
  4493.   if (uncomp_size)
  4494.   {
  4495.     mz_uint64 uncomp_remaining = uncomp_size;
  4496.     void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
  4497.     if (!pRead_buf)
  4498.     {
  4499.       MZ_FCLOSE(pSrc_file);
  4500.       return MZ_FALSE;
  4501.     }
  4502.  
  4503.     if (!level)
  4504.     {
  4505.       while (uncomp_remaining)
  4506.       {
  4507.         mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
  4508.         if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n))
  4509.         {
  4510.           pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4511.           MZ_FCLOSE(pSrc_file);
  4512.           return MZ_FALSE;
  4513.         }
  4514.         uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
  4515.         uncomp_remaining -= n;
  4516.         cur_archive_file_ofs += n;
  4517.       }
  4518.       comp_size = uncomp_size;
  4519.     }
  4520.     else
  4521.     {
  4522.       mz_bool result = MZ_FALSE;
  4523.       mz_zip_writer_add_state state;
  4524.       tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
  4525.       if (!pComp)
  4526.       {
  4527.         pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4528.         MZ_FCLOSE(pSrc_file);
  4529.         return MZ_FALSE;
  4530.       }
  4531.  
  4532.       state.m_pZip = pZip;
  4533.       state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  4534.       state.m_comp_size = 0;
  4535.  
  4536.       if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY)
  4537.       {
  4538.         pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  4539.         pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4540.         MZ_FCLOSE(pSrc_file);
  4541.         return MZ_FALSE;
  4542.       }
  4543.  
  4544.       for ( ; ; )
  4545.       {
  4546.         size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE);
  4547.         tdefl_status status;
  4548.  
  4549.         if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
  4550.           break;
  4551.  
  4552.         uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
  4553.         uncomp_remaining -= in_buf_size;
  4554.  
  4555.         status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH);
  4556.         if (status == TDEFL_STATUS_DONE)
  4557.         {
  4558.           result = MZ_TRUE;
  4559.           break;
  4560.         }
  4561.         else if (status != TDEFL_STATUS_OKAY)
  4562.           break;
  4563.       }
  4564.  
  4565.       pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  4566.  
  4567.       if (!result)
  4568.       {
  4569.         pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4570.         MZ_FCLOSE(pSrc_file);
  4571.         return MZ_FALSE;
  4572.       }
  4573.  
  4574.       comp_size = state.m_comp_size;
  4575.       cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  4576.  
  4577.       method = MZ_DEFLATED;
  4578.     }
  4579.  
  4580.     pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4581.   }
  4582.  
  4583.   MZ_FCLOSE(pSrc_file); pSrc_file = NULL;
  4584.  
  4585.   // no zip64 support yet
  4586.   if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  4587.     return MZ_FALSE;
  4588.  
  4589.   if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  4590.     return MZ_FALSE;
  4591.  
  4592.   if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))
  4593.     return MZ_FALSE;
  4594.  
  4595.   if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  4596.     return MZ_FALSE;
  4597.  
  4598.   pZip->m_total_files++;
  4599.   pZip->m_archive_size = cur_archive_file_ofs;
  4600.  
  4601.   return MZ_TRUE;
  4602. }
  4603. #endif // #ifndef MINIZ_NO_STDIO
  4604.  
  4605. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index)
  4606. {
  4607.   mz_uint n, bit_flags, num_alignment_padding_bytes;
  4608.   mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
  4609.   mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
  4610.   mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  4611.   mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  4612.   size_t orig_central_dir_size;
  4613.   mz_zip_internal_state *pState;
  4614.   void *pBuf; const mz_uint8 *pSrc_central_header;
  4615.  
  4616.   if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  4617.     return MZ_FALSE;
  4618.   if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
  4619.     return MZ_FALSE;
  4620.   pState = pZip->m_pState;
  4621.  
  4622.   num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  4623.  
  4624.   // no zip64 support yet
  4625.   if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  4626.     return MZ_FALSE;
  4627.  
  4628.   cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  4629.   cur_dst_file_ofs = pZip->m_archive_size;
  4630.  
  4631.   if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4632.     return MZ_FALSE;
  4633.   if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  4634.     return MZ_FALSE;
  4635.   cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  4636.  
  4637.   if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes))
  4638.     return MZ_FALSE;
  4639.   cur_dst_file_ofs += num_alignment_padding_bytes;
  4640.   local_dir_header_ofs = cur_dst_file_ofs;
  4641.   if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }
  4642.  
  4643.   if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4644.     return MZ_FALSE;
  4645.   cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  4646.  
  4647.   n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  4648.   comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4649.  
  4650.   if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining)))))
  4651.     return MZ_FALSE;
  4652.  
  4653.   while (comp_bytes_remaining)
  4654.   {
  4655.     n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
  4656.     if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n)
  4657.     {
  4658.       pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4659.       return MZ_FALSE;
  4660.     }
  4661.     cur_src_file_ofs += n;
  4662.  
  4663.     if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)
  4664.     {
  4665.       pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4666.       return MZ_FALSE;
  4667.     }
  4668.     cur_dst_file_ofs += n;
  4669.  
  4670.     comp_bytes_remaining -= n;
  4671.   }
  4672.  
  4673.   bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
  4674.   if (bit_flags & 8)
  4675.   {
  4676.     // Copy data descriptor
  4677.     if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4)
  4678.     {
  4679.       pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4680.       return MZ_FALSE;
  4681.     }
  4682.  
  4683.     n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
  4684.     if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)
  4685.     {
  4686.       pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4687.       return MZ_FALSE;
  4688.     }
  4689.  
  4690.     cur_src_file_ofs += n;
  4691.     cur_dst_file_ofs += n;
  4692.   }
  4693.   pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4694.  
  4695.   // no zip64 support yet
  4696.   if (cur_dst_file_ofs > 0xFFFFFFFF)
  4697.     return MZ_FALSE;
  4698.  
  4699.   orig_central_dir_size = pState->m_central_dir.m_size;
  4700.  
  4701.   memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  4702.   MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs);
  4703.   if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
  4704.     return MZ_FALSE;
  4705.  
  4706.   n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4707.   if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n))
  4708.   {
  4709.     mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);
  4710.     return MZ_FALSE;
  4711.   }
  4712.  
  4713.   if (pState->m_central_dir.m_size > 0xFFFFFFFF)
  4714.     return MZ_FALSE;
  4715.   n = (mz_uint32)orig_central_dir_size;
  4716.   if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1))
  4717.   {
  4718.     mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);
  4719.     return MZ_FALSE;
  4720.   }
  4721.  
  4722.   pZip->m_total_files++;
  4723.   pZip->m_archive_size = cur_dst_file_ofs;
  4724.  
  4725.   return MZ_TRUE;
  4726. }
  4727.  
  4728. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip)
  4729. {
  4730.   mz_zip_internal_state *pState;
  4731.   mz_uint64 central_dir_ofs, central_dir_size;
  4732.   mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
  4733.  
  4734.   if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  4735.     return MZ_FALSE;
  4736.  
  4737.   pState = pZip->m_pState;
  4738.  
  4739.   // no zip64 support yet
  4740.   if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  4741.     return MZ_FALSE;
  4742.  
  4743.   central_dir_ofs = 0;
  4744.   central_dir_size = 0;
  4745.   if (pZip->m_total_files)
  4746.   {
  4747.     // Write central directory
  4748.     central_dir_ofs = pZip->m_archive_size;
  4749.     central_dir_size = pState->m_central_dir.m_size;
  4750.     pZip->m_central_directory_file_ofs = central_dir_ofs;
  4751.     if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size)
  4752.       return MZ_FALSE;
  4753.     pZip->m_archive_size += central_dir_size;
  4754.   }
  4755.  
  4756.   // Write end of central directory record
  4757.   MZ_CLEAR_OBJ(hdr);
  4758.   MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
  4759.   MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files);
  4760.   MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
  4761.   MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
  4762.   MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
  4763.  
  4764.   if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr))
  4765.     return MZ_FALSE;
  4766. #ifndef MINIZ_NO_STDIO
  4767.   if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF))
  4768.     return MZ_FALSE;
  4769. #endif // #ifndef MINIZ_NO_STDIO
  4770.  
  4771.   pZip->m_archive_size += sizeof(hdr);
  4772.  
  4773.   pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
  4774.   return MZ_TRUE;
  4775. }
  4776.  
  4777. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize)
  4778. {
  4779.   if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize))
  4780.     return MZ_FALSE;
  4781.   if (pZip->m_pWrite != mz_zip_heap_write_func)
  4782.     return MZ_FALSE;
  4783.   if (!mz_zip_writer_finalize_archive(pZip))
  4784.     return MZ_FALSE;
  4785.  
  4786.   *pBuf = pZip->m_pState->m_pMem;
  4787.   *pSize = pZip->m_pState->m_mem_size;
  4788.   pZip->m_pState->m_pMem = NULL;
  4789.   pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
  4790.   return MZ_TRUE;
  4791. }
  4792.  
  4793. mz_bool mz_zip_writer_end(mz_zip_archive *pZip)
  4794. {
  4795.   mz_zip_internal_state *pState;
  4796.   mz_bool status = MZ_TRUE;
  4797.   if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
  4798.     return MZ_FALSE;
  4799.  
  4800.   pState = pZip->m_pState;
  4801.   pZip->m_pState = NULL;
  4802.   mz_zip_array_clear(pZip, &pState->m_central_dir);
  4803.   mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  4804.   mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  4805.  
  4806. #ifndef MINIZ_NO_STDIO
  4807.   if (pState->m_pFile)
  4808.   {
  4809.     MZ_FCLOSE(pState->m_pFile);
  4810.     pState->m_pFile = NULL;
  4811.   }
  4812. #endif // #ifndef MINIZ_NO_STDIO
  4813.  
  4814.   if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem))
  4815.   {
  4816.     pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
  4817.     pState->m_pMem = NULL;
  4818.   }
  4819.  
  4820.   pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  4821.   pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  4822.   return status;
  4823. }
  4824.  
  4825. #ifndef MINIZ_NO_STDIO
  4826. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)
  4827. {
  4828.   mz_bool status, created_new_archive = MZ_FALSE;
  4829.   mz_zip_archive zip_archive;
  4830.   struct MZ_FILE_STAT_STRUCT file_stat;
  4831.   MZ_CLEAR_OBJ(zip_archive);
  4832.   if ((int)level_and_flags < 0)
  4833.      level_and_flags = MZ_DEFAULT_LEVEL;
  4834.   if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
  4835.     return MZ_FALSE;
  4836.   if (!mz_zip_writer_validate_archive_name(pArchive_name))
  4837.     return MZ_FALSE;
  4838.   if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0)
  4839.   {
  4840.     // Create a new archive.
  4841.     if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
  4842.       return MZ_FALSE;
  4843.     created_new_archive = MZ_TRUE;
  4844.   }
  4845.   else
  4846.   {
  4847.     // Append to an existing archive.
  4848.     if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  4849.       return MZ_FALSE;
  4850.     if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename))
  4851.     {
  4852.       mz_zip_reader_end(&zip_archive);
  4853.       return MZ_FALSE;
  4854.     }
  4855.   }
  4856.   status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0);
  4857.   // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.)
  4858.   if (!mz_zip_writer_finalize_archive(&zip_archive))
  4859.     status = MZ_FALSE;
  4860.   if (!mz_zip_writer_end(&zip_archive))
  4861.     status = MZ_FALSE;
  4862.   if ((!status) && (created_new_archive))
  4863.   {
  4864.     // It's a new archive and something went wrong, so just delete it.
  4865.     int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
  4866.     (void)ignoredStatus;
  4867.   }
  4868.   return status;
  4869. }
  4870.  
  4871. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags)
  4872. {
  4873.   int file_index;
  4874.   mz_zip_archive zip_archive;
  4875.   void *p = NULL;
  4876.  
  4877.   if (pSize)
  4878.     *pSize = 0;
  4879.  
  4880.   if ((!pZip_filename) || (!pArchive_name))
  4881.     return NULL;
  4882.  
  4883.   MZ_CLEAR_OBJ(zip_archive);
  4884.   if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  4885.     return NULL;
  4886.  
  4887.   if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0)
  4888.     p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
  4889.  
  4890.   mz_zip_reader_end(&zip_archive);
  4891.   return p;
  4892. }
  4893.  
  4894. #endif // #ifndef MINIZ_NO_STDIO
  4895.  
  4896. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  4897.  
  4898. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  4899.  
  4900. #ifdef __cplusplus
  4901. }
  4902. #endif
  4903.  
  4904. #endif // MINIZ_HEADER_FILE_ONLY
  4905.  
  4906. /*
  4907.   This is free and unencumbered software released into the public domain.
  4908.  
  4909.   Anyone is free to copy, modify, publish, use, compile, sell, or
  4910.   distribute this software, either in source code form or as a compiled
  4911.   binary, for any purpose, commercial or non-commercial, and by any
  4912.   means.
  4913.  
  4914.   In jurisdictions that recognize copyright laws, the author or authors
  4915.   of this software dedicate any and all copyright interest in the
  4916.   software to the public domain. We make this dedication for the benefit
  4917.   of the public at large and to the detriment of our heirs and
  4918.   successors. We intend this dedication to be an overt act of
  4919.   relinquishment in perpetuity of all present and future rights to this
  4920.   software under copyright law.
  4921.  
  4922.   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  4923.   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4924.   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  4925.   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  4926.   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  4927.   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  4928.   OTHER DEALINGS IN THE SOFTWARE.
  4929.  
  4930.   For more information, please refer to <http://unlicense.org/>
  4931. */
Add Comment
Please, Sign In to add comment