1 /* miniz.c 2.0.6 beta - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending,
2    PNG writing See "unlicense" statement at the end of this file. Rich Geldreich
3    <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950:
4    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
7    just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see
8    the list below for more macros).
9 
10    * Low-level Deflate/Inflate implementation notes:
11 
12      Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks,
13    lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs
14    and compresses approximately as well as zlib.
15 
16      Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single
17    function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger
18    power of 2) wrapping buffer, or into a memory block large enough to hold the entire file.
19 
20      The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation.
21 
22    * zlib-style API notes:
23 
24      miniz.c implements a fairly large subset of zlib. There's enough functionality present for it
25    to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation
26    callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
27         inflateInit/inflateInit2/inflate/inflateEnd
28         compress, compress2, compressBound, uncompress
29         CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines.
30         Supports raw deflate streams or standard zlib streams with adler-32 checking.
31 
32      Limitations:
33       The callback API's are not implemented yet. No support for gzip headers or zlib static
34    dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return
35    status codes, but there are no guarantees that miniz.c pulls this off perfectly.
36 
37    * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by
38      Alex Evans. Supports 1-4 bytes/pixel images.
39 
40    * ZIP archive API notes:
41 
42      The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough
43    abstraction to get the job done with minimal fuss. There are simple API's to retrieve file
44    information, read files from existing archives, create new archives, append new files to existing
45    archives, or clone archive data from one archive to another. It supports archives located in
46    memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks.
47 
48      - Archive reading: Just call this function to read a single file from a disk archive:
49 
50       void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char
51    *pArchive_name, size_t *pSize, mz_uint zip_flags);
52 
53      For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire
54    central directory is located and read as-is into memory, and subsequent file access only occurs
55    when reading individual files.
56 
57      - Archives file scanning: The simple way is to use this function to scan a loaded archive for a
58    specific file:
59 
60      int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment,
61    mz_uint flags);
62 
63      The locate operation can optionally check file comments too, which (as one example) can be used
64    to identify multiple versions of the same file in an archive. This function uses a simple linear
65    search through the central directory, so it's not very fast.
66 
67      Alternately, you can iterate through all the files in an archive (using
68    mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling
69    mz_zip_reader_file_stat().
70 
71      - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes
72    compressed file data to disk and builds an exact image of the central directory in memory. The
73    central directory image is written all at once at the end of the archive file when the archive is
74    finalized.
75 
76      The archive writer can optionally align each file's local header and file data to any power of
77    2 alignment, which can be useful when the archive will be read from optical media. Also, the
78    writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives
79    written using either feature are still readable by any ZIP tool.
80 
81      - Archive appending: The simple way to add a single file to an archive is to call this
82    function:
83 
84       mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char
85    *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size,
86    mz_uint level_and_flags);
87 
88      The archive will be created if it doesn't already exist, otherwise it'll be appended to.
89      Note the appending is done in-place and is not an atomic operation, so if something goes wrong
90      during the operation it's possible the archive could be left without a central directory
91    (although the local file headers and file data will be fine, so the archive will be recoverable).
92 
93      For more complex archive modification scenarios:
94      1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those
95    bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader()
96    function (which compiles the compressed file data as-is). When you're done, delete the old
97    archive and rename the newly written archive, and you're done. This is safe but requires a bunch
98    of temporary disk space or heap memory.
99 
100      2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
101    mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which
102    will write an updated central directory to the original archive. (This is basically what
103    mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central
104    directory could be lost with this method if anything goes wrong, though.
105 
106      - ZIP archive support limitations:
107      No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or
108    deflated files. Requires streams capable of seeking.
109 
110    * This is a header file library, like stb_image.c. To get only a header file, either cut and
111    paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include
112    miniz.c from it.
113 
114    * Important: For best perf. be sure to customize the below macros for your target platform:
115      #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
116      #define MINIZ_LITTLE_ENDIAN 1
117      #define MINIZ_HAS_64BIT_REGISTERS 1
118 
119    * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c
120    to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able
121    to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
122 */
123 #pragma once
124 
125 /* Defines to completely disable specific portions of miniz.c:
126    If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl,
127    and tdefl. */
128 
129 /* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */
130 /*#define MINIZ_NO_STDIO */
131 
132 /* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current
133  * time, or */
134 /* get/set file times, and the C run-time funcs that get/set times won't be called. */
135 /* The current downside is the times written to your archives will be from 1979. */
136 /*#define MINIZ_NO_TIME */
137 
138 /* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */
139 /*#define MINIZ_NO_ARCHIVE_APIS */
140 
141 /* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */
142 /*#define MINIZ_NO_ARCHIVE_WRITING_APIS */
143 
144 /* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */
145 /*#define MINIZ_NO_ZLIB_APIS */
146 
147 /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock
148  * zlib. */
149 /*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */
150 
151 /* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
152    Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user
153    alloc/free/realloc callbacks to the zlib and archive API's, and a few stand-alone helper API's
154    which don't provide custom user functions (such as tdefl_compress_mem_to_heap() and
155    tinfl_decompress_mem_to_heap()) won't work. */
156 /*#define MINIZ_NO_MALLOC */
157 
158 #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
159 /* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */
160 #define MINIZ_NO_TIME
161 #endif
162 
163 #include <stddef.h>
164 
165 #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
166 #include <time.h>
167 #endif
168 
169 #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || \
170     defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) ||  \
171     defined(__x86_64__)
172 /* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */
173 #define MINIZ_X86_OR_X64_CPU 1
174 #else
175 #define MINIZ_X86_OR_X64_CPU 0
176 #endif
177 
178 #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
179 /* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */
180 #define MINIZ_LITTLE_ENDIAN 1
181 #else
182 #define MINIZ_LITTLE_ENDIAN 0
183 #endif
184 
185 #if MINIZ_X86_OR_X64_CPU
186 /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and
187  * stores from unaligned addresses. */
188 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
189 #else
190 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0
191 #endif
192 
193 #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || \
194     defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
195 /* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and
196  * don't involve compiler generated calls to helper functions). */
197 #define MINIZ_HAS_64BIT_REGISTERS 1
198 #else
199 #define MINIZ_HAS_64BIT_REGISTERS 0
200 #endif
201 
202 #ifdef __cplusplus
203 extern "C" {
204 #endif
205 
206 /* ------------------- zlib-style API Definitions. */
207 
208 /* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members.
209  * Beware: mz_ulong can be either 32 or 64-bits! */
210 typedef unsigned long mz_ulong;
211 
212 /* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've
213  * modified the MZ_MALLOC macro) to release a block allocated from the heap. */
214 void mz_free(void *p);
215 
216 #define MZ_ADLER32_INIT (1)
217 /* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */
218 mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
219 
220 #define MZ_CRC32_INIT (0)
221 /* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */
222 mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
223 
224 /* Compression strategies. */
225 enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
226 
227 /* Method */
228 #define MZ_DEFLATED 8
229 
230 /* Heap allocation callbacks.
231 Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not
232 unsigned long. */
233 typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
234 typedef void (*mz_free_func)(void *opaque, void *address);
235 typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
236 
237 /* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not
238  * zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */
239 enum {
240   MZ_NO_COMPRESSION = 0,
241   MZ_BEST_SPEED = 1,
242   MZ_BEST_COMPRESSION = 9,
243   MZ_UBER_COMPRESSION = 10,
244   MZ_DEFAULT_LEVEL = 6,
245   MZ_DEFAULT_COMPRESSION = -1
246 };
247 
248 #define MZ_VERSION "10.0.1"
249 #define MZ_VERNUM 0xA010
250 #define MZ_VER_MAJOR 10
251 #define MZ_VER_MINOR 0
252 #define MZ_VER_REVISION 1
253 #define MZ_VER_SUBREVISION 0
254 
255 #ifndef MINIZ_NO_ZLIB_APIS
256 
257 /* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for
258  * advanced use (refer to the zlib docs). */
259 enum {
260   MZ_NO_FLUSH = 0,
261   MZ_PARTIAL_FLUSH = 1,
262   MZ_SYNC_FLUSH = 2,
263   MZ_FULL_FLUSH = 3,
264   MZ_FINISH = 4,
265   MZ_BLOCK = 5
266 };
267 
268 /* Return status codes. MZ_PARAM_ERROR is non-standard. */
269 enum {
270   MZ_OK = 0,
271   MZ_STREAM_END = 1,
272   MZ_NEED_DICT = 2,
273   MZ_ERRNO = -1,
274   MZ_STREAM_ERROR = -2,
275   MZ_DATA_ERROR = -3,
276   MZ_MEM_ERROR = -4,
277   MZ_BUF_ERROR = -5,
278   MZ_VERSION_ERROR = -6,
279   MZ_PARAM_ERROR = -10000
280 };
281 
282 /* Window bits */
283 #define MZ_DEFAULT_WINDOW_BITS 15
284 
285 struct mz_internal_state;
286 
287 /* Compression/decompression stream struct. */
288 typedef struct mz_stream_s {
289   const unsigned char *next_in; /* pointer to next byte to read */
290   unsigned int avail_in;        /* number of bytes available at next_in */
291   mz_ulong total_in;            /* total number of bytes consumed so far */
292 
293   unsigned char *next_out; /* pointer to next byte to write */
294   unsigned int avail_out;  /* number of bytes that can be written to next_out */
295   mz_ulong total_out;      /* total number of bytes produced so far */
296 
297   char *msg;                       /* error msg (unused) */
298   struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */
299 
300   mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */
301   mz_free_func zfree;   /* optional heap free function (defaults to free) */
302   void *opaque;         /* heap alloc function user pointer */
303 
304   int data_type;     /* data_type (unused) */
305   mz_ulong adler;    /* adler32 of the source or uncompressed data */
306   mz_ulong reserved; /* not used */
307 } mz_stream;
308 
309 typedef mz_stream *mz_streamp;
310 
311 /* Returns the version string of miniz.c. */
312 const char *mz_version(void);
313 
314 /* mz_deflateInit() initializes a compressor with default options: */
315 /* Parameters: */
316 /*  pStream must point to an initialized mz_stream struct. */
317 /*  level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */
318 /*  level 1 enables a specially optimized compression function that's been optimized purely for
319  * performance, not ratio. */
320 /*  (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and
321  * MINIZ_LITTLE_ENDIAN are defined.) */
322 /* Return values: */
323 /*  MZ_OK on success. */
324 /*  MZ_STREAM_ERROR if the stream is bogus. */
325 /*  MZ_PARAM_ERROR if the input parameters are bogus. */
326 /*  MZ_MEM_ERROR on out of memory. */
327 int mz_deflateInit(mz_streamp pStream, int level);
328 
329 /* mz_deflateInit2() is like mz_deflate(), except with more control: */
330 /* Additional parameters: */
331 /*   method must be MZ_DEFLATED */
332 /*   window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib
333  * header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */
334 /*   mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */
335 int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level,
336                     int strategy);
337 
338 /* Quickly resets a compressor without having to reallocate anything. Same as calling
339  * mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */
340 int mz_deflateReset(mz_streamp pStream);
341 
342 /* mz_deflate() compresses the input to output, consuming as much of the input and producing as much
343  * output as possible. */
344 /* Parameters: */
345 /*   pStream is the stream to read from and write to. You must initialize/update the next_in,
346  * avail_in, next_out, and avail_out members. */
347 /*   flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */
348 /* Return values: */
349 /*   MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's
350  * more output to be written but the output buffer is full). */
351 /*   MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call
352  * mz_deflate() on the stream anymore. */
353 /*   MZ_STREAM_ERROR if the stream is bogus. */
354 /*   MZ_PARAM_ERROR if one of the parameters is invalid. */
355 /*   MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are
356  * empty. (Fill up the input buffer or free up some output space and try again.) */
357 int mz_deflate(mz_streamp pStream, int flush);
358 
359 /* mz_deflateEnd() deinitializes a compressor: */
360 /* Return values: */
361 /*  MZ_OK on success. */
362 /*  MZ_STREAM_ERROR if the stream is bogus. */
363 int mz_deflateEnd(mz_streamp pStream);
364 
365 /* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be
366  * generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */
367 mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
368 
369 /* Single-call compression functions mz_compress() and mz_compress2(): */
370 /* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */
371 int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource,
372                 mz_ulong source_len);
373 int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource,
374                  mz_ulong source_len, int level);
375 
376 /* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be
377  * generated by calling mz_compress(). */
378 mz_ulong mz_compressBound(mz_ulong source_len);
379 
380 /* Initializes a decompressor. */
381 int mz_inflateInit(mz_streamp pStream);
382 
383 /* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window
384  * size and whether or not the stream has been wrapped with a zlib header/footer: */
385 /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
386  * -MZ_DEFAULT_WINDOW_BITS (raw deflate). */
387 int mz_inflateInit2(mz_streamp pStream, int window_bits);
388 
389 /* Decompresses the input stream to the output, consuming only as much of the input as needed, and
390  * writing as much to the output as possible. */
391 /* Parameters: */
392 /*   pStream is the stream to read from and write to. You must initialize/update the next_in,
393  * avail_in, next_out, and avail_out members. */
394 /*   flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */
395 /*   On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both
396  * sized large enough to decompress the entire stream in a single call (this is slightly faster). */
397 /*   MZ_FINISH implies that there are no more source bytes available beside what's already in the
398  * input buffer, and that the output buffer is large enough to hold the rest of the decompressed
399  * data. */
400 /* Return values: */
401 /*   MZ_OK on success. Either more input is needed but not available, and/or there's more output to
402  * be written but the output buffer is full. */
403 /*   MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For
404  * zlib streams, the adler-32 of the decompressed data has also been verified. */
405 /*   MZ_STREAM_ERROR if the stream is bogus. */
406 /*   MZ_DATA_ERROR if the deflate stream is invalid. */
407 /*   MZ_PARAM_ERROR if one of the parameters is invalid. */
408 /*   MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the
409  * inflater needs more input to continue, or if the output buffer is not large enough. Call
410  * mz_inflate() again */
411 /*   with more input data, or with more room in the output buffer (except when using single call
412  * decompression, described above). */
413 int mz_inflate(mz_streamp pStream, int flush);
414 
415 /* Deinitializes a decompressor. */
416 int mz_inflateEnd(mz_streamp pStream);
417 
418 /* Single-call decompression. */
419 /* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */
420 int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource,
421                   mz_ulong source_len);
422 
423 /* Returns a string description of the specified error code, or NULL if the error code is invalid.
424  */
425 const char *mz_error(int err);
426 
427 /* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in
428  * replacement for the subset of zlib that miniz.c supports. */
429 /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same
430  * project. */
431 #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
432 typedef unsigned char Byte;
433 typedef unsigned int uInt;
434 typedef mz_ulong uLong;
435 typedef Byte Bytef;
436 typedef uInt uIntf;
437 typedef char charf;
438 typedef int intf;
439 typedef void *voidpf;
440 typedef uLong uLongf;
441 typedef void *voidp;
442 typedef void *const voidpc;
443 #define Z_NULL 0
444 #define Z_NO_FLUSH MZ_NO_FLUSH
445 #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
446 #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
447 #define Z_FULL_FLUSH MZ_FULL_FLUSH
448 #define Z_FINISH MZ_FINISH
449 #define Z_BLOCK MZ_BLOCK
450 #define Z_OK MZ_OK
451 #define Z_STREAM_END MZ_STREAM_END
452 #define Z_NEED_DICT MZ_NEED_DICT
453 #define Z_ERRNO MZ_ERRNO
454 #define Z_STREAM_ERROR MZ_STREAM_ERROR
455 #define Z_DATA_ERROR MZ_DATA_ERROR
456 #define Z_MEM_ERROR MZ_MEM_ERROR
457 #define Z_BUF_ERROR MZ_BUF_ERROR
458 #define Z_VERSION_ERROR MZ_VERSION_ERROR
459 #define Z_PARAM_ERROR MZ_PARAM_ERROR
460 #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
461 #define Z_BEST_SPEED MZ_BEST_SPEED
462 #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
463 #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
464 #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
465 #define Z_FILTERED MZ_FILTERED
466 #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
467 #define Z_RLE MZ_RLE
468 #define Z_FIXED MZ_FIXED
469 #define Z_DEFLATED MZ_DEFLATED
470 #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
471 #define alloc_func mz_alloc_func
472 #define free_func mz_free_func
473 #define internal_state mz_internal_state
474 #define z_stream mz_stream
475 #define deflateInit mz_deflateInit
476 #define deflateInit2 mz_deflateInit2
477 #define deflateReset mz_deflateReset
478 #define deflate mz_deflate
479 #define deflateEnd mz_deflateEnd
480 #define deflateBound mz_deflateBound
481 #define compress mz_compress
482 #define compress2 mz_compress2
483 #define compressBound mz_compressBound
484 #define inflateInit mz_inflateInit
485 #define inflateInit2 mz_inflateInit2
486 #define inflate mz_inflate
487 #define inflateEnd mz_inflateEnd
488 #define uncompress mz_uncompress
489 #define crc32 mz_crc32
490 #define adler32 mz_adler32
491 #define MAX_WBITS 15
492 #define MAX_MEM_LEVEL 9
493 #define zError mz_error
494 #define ZLIB_VERSION MZ_VERSION
495 #define ZLIB_VERNUM MZ_VERNUM
496 #define ZLIB_VER_MAJOR MZ_VER_MAJOR
497 #define ZLIB_VER_MINOR MZ_VER_MINOR
498 #define ZLIB_VER_REVISION MZ_VER_REVISION
499 #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
500 #define zlibVersion mz_version
501 #define zlib_version mz_version()
502 #endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */
503 
504 #endif /* MINIZ_NO_ZLIB_APIS */
505 
506 #ifdef __cplusplus
507 }
508 #endif
509 #pragma once
510 #include <assert.h>
511 #include <stdint.h>
512 #include <stdlib.h>
513 #include <string.h>
514 #include "rmalloc.h"
515 
516 /* ------------------- Types and macros */
517 typedef unsigned char mz_uint8;
518 typedef signed short mz_int16;
519 typedef unsigned short mz_uint16;
520 typedef unsigned int mz_uint32;
521 typedef unsigned int mz_uint;
522 typedef int64_t mz_int64;
523 typedef uint64_t mz_uint64;
524 typedef int mz_bool;
525 
526 #define MZ_FALSE (0)
527 #define MZ_TRUE (1)
528 
529 /* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */
530 #ifdef _MSC_VER
531 #define MZ_MACRO_END while (0, 0)
532 #else
533 #define MZ_MACRO_END while (0)
534 #endif
535 
536 #ifdef MINIZ_NO_STDIO
537 #define MZ_FILE void *
538 #else
539 #include <stdio.h>
540 #define MZ_FILE FILE
541 #endif /* #ifdef MINIZ_NO_STDIO */
542 
543 #ifdef MINIZ_NO_TIME
544 typedef struct mz_dummy_time_t_tag {
545   int m_dummy;
546 } mz_dummy_time_t;
547 #define MZ_TIME_T mz_dummy_time_t
548 #else
549 #define MZ_TIME_T time_t
550 #endif
551 
552 #define MZ_ASSERT(x) assert(x)
553 
554 #ifdef MINIZ_NO_MALLOC
555 #define MZ_MALLOC(x) NULL
556 #define MZ_FREE(x) (void)x, ((void)0)
557 #define MZ_REALLOC(p, x) NULL
558 #else
559 #define MZ_MALLOC(x) rm_malloc(x)
560 #define MZ_FREE(x) rm_free(x)
561 #define MZ_REALLOC(p, x) realloc(p, x)
562 #endif
563 
564 #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
565 #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
566 #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
567 
568 #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
569 #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
570 #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
571 #else
572 #define MZ_READ_LE16(p) \
573   ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
574 #define MZ_READ_LE32(p)                                                                        \
575   ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
576    ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) |                                          \
577    ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
578 #endif
579 
580 #define MZ_READ_LE64(p)           \
581   (((mz_uint64)MZ_READ_LE32(p)) | \
582    (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U))
583 
584 #ifdef _MSC_VER
585 #define MZ_FORCEINLINE __forceinline
586 #elif defined(__GNUC__)
587 #define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__))
588 #else
589 #define MZ_FORCEINLINE inline
590 #endif
591 
592 #ifdef __cplusplus
593 extern "C" {
594 #endif
595 
596 extern void *miniz_def_alloc_func(void *opaque, size_t items, size_t size);
597 extern void miniz_def_free_func(void *opaque, void *address);
598 extern void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size);
599 
600 #define MZ_UINT16_MAX (0xFFFFU)
601 #define MZ_UINT32_MAX (0xFFFFFFFFU)
602 
603 #ifdef __cplusplus
604 }
605 #endif
606 #pragma once
607 
608 #ifdef __cplusplus
609 extern "C" {
610 #endif
611 /* ------------------- Low-level Compression API Definitions */
612 
613 /* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and
614  * raw/dynamic blocks will be output more frequently). */
615 #define TDEFL_LESS_MEMORY 0
616 
617 /* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of
618  * probes per dictionary search): */
619 /* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search.
620  * 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best
621  * compression). */
622 enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF };
623 
624 /* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data,
625  * and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */
626 /* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib
627  * headers). */
628 /* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy
629  * parsing. */
630 /* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to
631  * the minimum, but the output may vary from run to run given the same input (depending on the
632  * contents of memory). */
633 /* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */
634 /* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */
635 /* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */
636 /* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */
637 /* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see
638  * TDEFL_MAX_PROBES_MASK). */
639 enum {
640   TDEFL_WRITE_ZLIB_HEADER = 0x01000,
641   TDEFL_COMPUTE_ADLER32 = 0x02000,
642   TDEFL_GREEDY_PARSING_FLAG = 0x04000,
643   TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
644   TDEFL_RLE_MATCHES = 0x10000,
645   TDEFL_FILTER_MATCHES = 0x20000,
646   TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
647   TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
648 };
649 
650 /* High level compression functions: */
651 /* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
652  */
653 /* On entry: */
654 /*  pSrc_buf, src_buf_len: Pointer and size of source block to compress. */
655 /*  flags: The max match finder probes (default is 128) logically OR'd against the above flags.
656  * Higher probes are slower but improve compression. */
657 /* On return: */
658 /*  Function returns a pointer to the compressed data, or NULL on failure. */
659 /*  *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on
660  * uncompressible data. */
661 /*  The caller must free() the returned block when it's no longer needed. */
662 void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len,
663                                  int flags);
664 
665 /* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */
666 /* Returns 0 on failure. */
667 size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf,
668                                  size_t src_buf_len, int flags);
669 
670 /* Compresses an image to a compressed PNG file in memory. */
671 /* On entry: */
672 /*  pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */
673 /*  The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top
674  * scanline is stored first in memory. */
675 /*  level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or
676  * a decent default is MZ_DEFAULT_LEVEL */
677 /*  If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */
678 /* On return: */
679 /*  Function returns a pointer to the compressed data, or NULL on failure. */
680 /*  *pLen_out will be set to the size of the PNG image file. */
681 /*  The caller must mz_free() the returned heap block (which will typically be larger than
682  * *pLen_out) when it's no longer needed. */
683 void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans,
684                                                  size_t *pLen_out, mz_uint level, mz_bool flip);
685 void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans,
686                                               size_t *pLen_out);
687 
688 /* Output stream interface. The compressor uses this interface to write compressed data. It'll
689  * typically be called TDEFL_OUT_BUF_SIZE at a time. */
690 typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
691 
692 /* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this
693  * function internally. */
694 mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
695                                      tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user,
696                                      int flags);
697 
698 enum {
699   TDEFL_MAX_HUFF_TABLES = 3,
700   TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
701   TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
702   TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
703   TDEFL_LZ_DICT_SIZE = 32768,
704   TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
705   TDEFL_MIN_MATCH_LEN = 3,
706   TDEFL_MAX_MATCH_LEN = 258
707 };
708 
709 /* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using
710  * static/fixed Huffman codes). */
711 #if TDEFL_LESS_MEMORY
712 enum {
713   TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
714   TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
715   TDEFL_MAX_HUFF_SYMBOLS = 288,
716   TDEFL_LZ_HASH_BITS = 12,
717   TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
718   TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
719   TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
720 };
721 #else
722 enum {
723   TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
724   TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
725   TDEFL_MAX_HUFF_SYMBOLS = 288,
726   TDEFL_LZ_HASH_BITS = 15,
727   TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
728   TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
729   TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
730 };
731 #endif
732 
733 /* The low-level tdefl functions below may be used directly if the above helper functions aren't
734  * flexible enough. The low-level functions don't make any heap allocations, unlike the above helper
735  * functions. */
736 typedef enum {
737   TDEFL_STATUS_BAD_PARAM = -2,
738   TDEFL_STATUS_PUT_BUF_FAILED = -1,
739   TDEFL_STATUS_OKAY = 0,
740   TDEFL_STATUS_DONE = 1
741 } tdefl_status;
742 
743 /* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */
744 typedef enum {
745   TDEFL_NO_FLUSH = 0,
746   TDEFL_SYNC_FLUSH = 2,
747   TDEFL_FULL_FLUSH = 3,
748   TDEFL_FINISH = 4
749 } tdefl_flush;
750 
751 /* tdefl's compression state structure. */
752 typedef struct {
753   tdefl_put_buf_func_ptr m_pPut_buf_func;
754   void *m_pPut_buf_user;
755   mz_uint m_flags, m_max_probes[2];
756   int m_greedy_parsing;
757   mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
758   mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
759   mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
760   mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs,
761       m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;
762   tdefl_status m_prev_return_status;
763   const void *m_pIn_buf;
764   void *m_pOut_buf;
765   size_t *m_pIn_buf_size, *m_pOut_buf_size;
766   tdefl_flush m_flush;
767   const mz_uint8 *m_pSrc;
768   size_t m_src_buf_left, m_out_buf_ofs;
769   mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
770   mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
771   mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
772   mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
773   mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
774   mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
775   mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
776   mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
777 } tdefl_compressor;
778 
779 /* Initializes the compressor. */
780 /* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate
781  * memory. */
782 /* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the
783  * user should call the tdefl_compress_buffer() API for compression. */
784 /* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */
785 /* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */
786 tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func,
787                         void *pPut_buf_user, int flags);
788 
789 /* Compresses a block of data, consuming as much of the specified input buffer as possible, and
790  * writing as much compressed data to the specified output buffer as possible. */
791 tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size,
792                             void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
793 
794 /* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL
795  * tdefl_put_buf_func_ptr. */
796 /* tdefl_compress_buffer() always consumes the entire input buffer. */
797 tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size,
798                                    tdefl_flush flush);
799 
800 tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
801 mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
802 
803 /* Create tdefl_compress() flags given zlib-style compression parameters. */
804 /* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some
805  * files) */
806 /* window_bits may be -15 (raw deflate) or 15 (zlib) */
807 /* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */
808 mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
809 
810 /* Allocate the tdefl_compressor structure in C so that */
811 /* non-C language bindings to tdefl_ API don't need to worry about */
812 /* structure size and allocation mechanism. */
813 tdefl_compressor *tdefl_compressor_alloc();
814 void tdefl_compressor_free(tdefl_compressor *pComp);
815 
816 #ifdef __cplusplus
817 }
818 #endif
819 #pragma once
820 
821 /* ------------------- Low-level Decompression API Definitions */
822 
823 #ifdef __cplusplus
824 extern "C" {
825 #endif
826 /* Decompression flags used by tinfl_decompress(). */
827 /* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32
828  * checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */
829 /* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the
830  * supplied input buffer. If clear, the input buffer contains all remaining input. */
831 /* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the
832  * entire decompressed stream. If clear, the output buffer is at least the size of the dictionary
833  * (typically 32KB). */
834 /* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */
835 enum {
836   TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
837   TINFL_FLAG_HAS_MORE_INPUT = 2,
838   TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
839   TINFL_FLAG_COMPUTE_ADLER32 = 8
840 };
841 
842 /* High level decompression functions: */
843 /* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via
844  * malloc(). */
845 /* On entry: */
846 /*  pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */
847 /* On return: */
848 /*  Function returns a pointer to the decompressed data, or NULL on failure. */
849 /*  *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on
850  * uncompressible data. */
851 /*  The caller must call mz_free() on the returned block when it's no longer needed. */
852 void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len,
853                                    int flags);
854 
855 /* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */
856 /* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
857  */
858 #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
859 size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf,
860                                    size_t src_buf_len, int flags);
861 
862 /* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and
863  * a user provided callback function will be called to flush the buffer. */
864 /* Returns 1 on success or 0 on failure. */
865 typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
866 int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
867                                      tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user,
868                                      int flags);
869 
870 struct tinfl_decompressor_tag;
871 typedef struct tinfl_decompressor_tag tinfl_decompressor;
872 
873 /* Allocate the tinfl_decompressor structure in C so that */
874 /* non-C language bindings to tinfl_ API don't need to worry about */
875 /* structure size and allocation mechanism. */
876 
877 tinfl_decompressor *tinfl_decompressor_alloc();
878 void tinfl_decompressor_free(tinfl_decompressor *pDecomp);
879 
880 /* Max size of LZ dictionary. */
881 #define TINFL_LZ_DICT_SIZE 32768
882 
883 /* Return status. */
884 typedef enum {
885   /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the
886      caller is indicating that no more are available. The compressed data */
887   /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue
888      processing the input but this is a BAD sign (either the data is corrupted or you called it
889      incorrectly). */
890   /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS
891      again. */
892   TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4,
893 
894   /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try
895      calling it again, but if you get this error the calling code is wrong.) */
896   TINFL_STATUS_BAD_PARAM = -3,
897 
898   /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data
899      didn't match. If you call it again it'll return TINFL_STATUS_DONE. */
900   TINFL_STATUS_ADLER32_MISMATCH = -2,
901 
902   /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you
903      call it again without resetting via tinfl_init() it it'll just keep on returning the same
904      status failure code. */
905   TINFL_STATUS_FAILED = -1,
906 
907   /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */
908 
909   /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has
910      consumed every byte that it needed, has successfully reached the end of the deflate stream, and
911    */
912   /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed
913      data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */
914   TINFL_STATUS_DONE = 0,
915 
916   /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any
917      more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */
918   /* flag on the next call if you don't have any more source data. If the source data was somehow
919      corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */
920   /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */
921   TINFL_STATUS_NEEDS_MORE_INPUT = 1,
922 
923   /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available,
924      but it cannot write this data into the output buffer. */
925   /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot
926      of uncompressed data to the caller. I've been assuming you know how much uncompressed data to
927      expect */
928   /* (either exact or worst case) and will stop calling the inflator and fail after receiving too
929      much. In pure streaming scenarios where you have no idea how many bytes to expect this may not
930      be possible */
931   /* so I may need to add some code to address this. */
932   TINFL_STATUS_HAS_MORE_OUTPUT = 2
933 } tinfl_status;
934 
935 /* Initializes the decompressor to its initial state. */
936 #define tinfl_init(r) \
937   do {                \
938     (r)->m_state = 0; \
939   }                   \
940   MZ_MACRO_END
941 #define tinfl_get_adler32(r) (r)->m_check_adler32
942 
943 /* Main low-level decompressor coroutine function. This is the only function actually needed for
944  * decompression. All the other functions are just high-level helpers for improved usability. */
945 /* This is a universal API, i.e. it can be used as a building block to build any desired higher
946  * level decompression API. In the limit case, it can be called once per every byte input or output.
947  */
948 tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next,
949                               size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
950                               mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
951                               const mz_uint32 decomp_flags);
952 
953 /* Internal/private bits follow. */
954 enum {
955   TINFL_MAX_HUFF_TABLES = 3,
956   TINFL_MAX_HUFF_SYMBOLS_0 = 288,
957   TINFL_MAX_HUFF_SYMBOLS_1 = 32,
958   TINFL_MAX_HUFF_SYMBOLS_2 = 19,
959   TINFL_FAST_LOOKUP_BITS = 10,
960   TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
961 };
962 
963 typedef struct {
964   mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
965   mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
966 } tinfl_huff_table;
967 
968 #if MINIZ_HAS_64BIT_REGISTERS
969 #define TINFL_USE_64BIT_BITBUF 1
970 #else
971 #define TINFL_USE_64BIT_BITBUF 0
972 #endif
973 
974 #if TINFL_USE_64BIT_BITBUF
975 typedef mz_uint64 tinfl_bit_buf_t;
976 #define TINFL_BITBUF_SIZE (64)
977 #else
978 typedef mz_uint32 tinfl_bit_buf_t;
979 #define TINFL_BITBUF_SIZE (32)
980 #endif
981 
982 struct tinfl_decompressor_tag {
983   mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32,
984       m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
985   tinfl_bit_buf_t m_bit_buf;
986   size_t m_dist_from_out_buf_start;
987   tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
988   mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
989 };
990 
991 #ifdef __cplusplus
992 }
993 #endif
994 
995 #pragma once
996 
997 /* ------------------- ZIP archive reading/writing */
998 
999 #ifndef MINIZ_NO_ARCHIVE_APIS
1000 
1001 #ifdef __cplusplus
1002 extern "C" {
1003 #endif
1004 
1005 enum {
1006   /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty
1007      conservative. */
1008   MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
1009   MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512,
1010   MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512
1011 };
1012 
1013 typedef struct {
1014   /* Central directory file index. */
1015   mz_uint32 m_file_index;
1016 
1017   /* Byte offset of this entry in the archive's central directory. Note we currently only support up
1018    * to UINT_MAX or less bytes in the central dir. */
1019   mz_uint64 m_central_dir_ofs;
1020 
1021   /* These fields are copied directly from the zip's central dir. */
1022   mz_uint16 m_version_made_by;
1023   mz_uint16 m_version_needed;
1024   mz_uint16 m_bit_flag;
1025   mz_uint16 m_method;
1026 
1027 #ifndef MINIZ_NO_TIME
1028   MZ_TIME_T m_time;
1029 #endif
1030 
1031   /* CRC-32 of uncompressed data. */
1032   mz_uint32 m_crc32;
1033 
1034   /* File's compressed size. */
1035   mz_uint64 m_comp_size;
1036 
1037   /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512
1038    * bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes.
1039    */
1040   mz_uint64 m_uncomp_size;
1041 
1042   /* Zip internal and external file attributes. */
1043   mz_uint16 m_internal_attr;
1044   mz_uint32 m_external_attr;
1045 
1046   /* Entry's local header file offset in bytes. */
1047   mz_uint64 m_local_header_ofs;
1048 
1049   /* Size of comment in bytes. */
1050   mz_uint32 m_comment_size;
1051 
1052   /* MZ_TRUE if the entry appears to be a directory. */
1053   mz_bool m_is_directory;
1054 
1055   /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */
1056   mz_bool m_is_encrypted;
1057 
1058   /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we
1059    * support. */
1060   mz_bool m_is_supported;
1061 
1062   /* Filename. If string ends in '/' it's a subdirectory entry. */
1063   /* Guaranteed to be zero terminated, may be truncated to fit. */
1064   char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
1065 
1066   /* Comment field. */
1067   /* Guaranteed to be zero terminated, may be truncated to fit. */
1068   char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
1069 
1070 } mz_zip_archive_file_stat;
1071 
1072 typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n);
1073 typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n);
1074 typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque);
1075 
1076 struct mz_zip_internal_state_tag;
1077 typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
1078 
1079 typedef enum {
1080   MZ_ZIP_MODE_INVALID = 0,
1081   MZ_ZIP_MODE_READING = 1,
1082   MZ_ZIP_MODE_WRITING = 2,
1083   MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
1084 } mz_zip_mode;
1085 
1086 typedef enum {
1087   MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
1088   MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
1089   MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
1090   MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800,
1091   MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG =
1092       0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its
1093                  validated to ensure the func finds the file in the central dir (intended for
1094                  testing) */
1095   MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress
1096                                                  the entire file and check the crc32 */
1097   MZ_ZIP_FLAG_WRITE_ZIP64 =
1098       0x4000, /* always use the zip64 file format, instead of the original zip file format with
1099                  automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */
1100   MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000,
1101   MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000
1102 } mz_zip_flags;
1103 
1104 typedef enum {
1105   MZ_ZIP_TYPE_INVALID = 0,
1106   MZ_ZIP_TYPE_USER,
1107   MZ_ZIP_TYPE_MEMORY,
1108   MZ_ZIP_TYPE_HEAP,
1109   MZ_ZIP_TYPE_FILE,
1110   MZ_ZIP_TYPE_CFILE,
1111   MZ_ZIP_TOTAL_TYPES
1112 } mz_zip_type;
1113 
1114 /* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */
1115 typedef enum {
1116   MZ_ZIP_NO_ERROR = 0,
1117   MZ_ZIP_UNDEFINED_ERROR,
1118   MZ_ZIP_TOO_MANY_FILES,
1119   MZ_ZIP_FILE_TOO_LARGE,
1120   MZ_ZIP_UNSUPPORTED_METHOD,
1121   MZ_ZIP_UNSUPPORTED_ENCRYPTION,
1122   MZ_ZIP_UNSUPPORTED_FEATURE,
1123   MZ_ZIP_FAILED_FINDING_CENTRAL_DIR,
1124   MZ_ZIP_NOT_AN_ARCHIVE,
1125   MZ_ZIP_INVALID_HEADER_OR_CORRUPTED,
1126   MZ_ZIP_UNSUPPORTED_MULTIDISK,
1127   MZ_ZIP_DECOMPRESSION_FAILED,
1128   MZ_ZIP_COMPRESSION_FAILED,
1129   MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE,
1130   MZ_ZIP_CRC_CHECK_FAILED,
1131   MZ_ZIP_UNSUPPORTED_CDIR_SIZE,
1132   MZ_ZIP_ALLOC_FAILED,
1133   MZ_ZIP_FILE_OPEN_FAILED,
1134   MZ_ZIP_FILE_CREATE_FAILED,
1135   MZ_ZIP_FILE_WRITE_FAILED,
1136   MZ_ZIP_FILE_READ_FAILED,
1137   MZ_ZIP_FILE_CLOSE_FAILED,
1138   MZ_ZIP_FILE_SEEK_FAILED,
1139   MZ_ZIP_FILE_STAT_FAILED,
1140   MZ_ZIP_INVALID_PARAMETER,
1141   MZ_ZIP_INVALID_FILENAME,
1142   MZ_ZIP_BUF_TOO_SMALL,
1143   MZ_ZIP_INTERNAL_ERROR,
1144   MZ_ZIP_FILE_NOT_FOUND,
1145   MZ_ZIP_ARCHIVE_TOO_LARGE,
1146   MZ_ZIP_VALIDATION_FAILED,
1147   MZ_ZIP_WRITE_CALLBACK_FAILED,
1148   MZ_ZIP_TOTAL_ERRORS
1149 } mz_zip_error;
1150 
1151 typedef struct {
1152   mz_uint64 m_archive_size;
1153   mz_uint64 m_central_directory_file_ofs;
1154 
1155   /* We only support up to UINT32_MAX files in zip64 mode. */
1156   mz_uint32 m_total_files;
1157   mz_zip_mode m_zip_mode;
1158   mz_zip_type m_zip_type;
1159   mz_zip_error m_last_error;
1160 
1161   mz_uint64 m_file_offset_alignment;
1162 
1163   mz_alloc_func m_pAlloc;
1164   mz_free_func m_pFree;
1165   mz_realloc_func m_pRealloc;
1166   void *m_pAlloc_opaque;
1167 
1168   mz_file_read_func m_pRead;
1169   mz_file_write_func m_pWrite;
1170   mz_file_needs_keepalive m_pNeeds_keepalive;
1171   void *m_pIO_opaque;
1172 
1173   mz_zip_internal_state *m_pState;
1174 
1175 } mz_zip_archive;
1176 
1177 typedef struct {
1178   mz_zip_archive *pZip;
1179   mz_uint flags;
1180 
1181   int status;
1182 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
1183   mz_uint file_crc32;
1184 #endif
1185   mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs;
1186   mz_zip_archive_file_stat file_stat;
1187   void *pRead_buf;
1188   void *pWrite_buf;
1189 
1190   size_t out_blk_remain;
1191 
1192   tinfl_decompressor inflator;
1193 
1194 } mz_zip_reader_extract_iter_state;
1195 
1196 /* -------- ZIP reading */
1197 
1198 /* Inits a ZIP archive reader. */
1199 /* These functions read and validate the archive's central directory. */
1200 mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags);
1201 
1202 mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags);
1203 
1204 #ifndef MINIZ_NO_STDIO
1205 /* Read a archive from a disk file. */
1206 /* file_start_ofs is the file offset where the archive actually begins, or 0. */
1207 /* actual_archive_size is the true total size of the archive, which may be smaller than the file's
1208  * actual size on disk. If zero the entire file is treated as the archive. */
1209 mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags);
1210 mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags,
1211                                    mz_uint64 file_start_ofs, mz_uint64 archive_size);
1212 
1213 /* Read an archive from an already opened FILE, beginning at the current file position. */
1214 /* The archive is assumed to be archive_size bytes long. If archive_size is < 0, then the entire
1215  * rest of the file is assumed to contain the archive. */
1216 /* The FILE will NOT be closed when mz_zip_reader_end() is called. */
1217 mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size,
1218                                  mz_uint flags);
1219 #endif
1220 
1221 /* Ends archive reading, freeing all allocations, and closing the input archive file if
1222  * mz_zip_reader_init_file() was used. */
1223 mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
1224 
1225 /* -------- ZIP reading or writing */
1226 
1227 /* Clears a mz_zip_archive struct to all zeros. */
1228 /* Important: This must be done before passing the struct to any mz_zip functions. */
1229 void mz_zip_zero_struct(mz_zip_archive *pZip);
1230 
1231 mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip);
1232 mz_zip_type mz_zip_get_type(mz_zip_archive *pZip);
1233 
1234 /* Returns the total number of files in the archive. */
1235 mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
1236 
1237 mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip);
1238 mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip);
1239 MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip);
1240 
1241 /* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */
1242 size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n);
1243 
1244 /* Attempts to locates a file in the archive's central directory. */
1245 /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */
1246 /* Returns -1 if the file cannot be found. */
1247 int mz_zip_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment,
1248                        mz_uint flags);
1249 /* Returns MZ_FALSE if the file cannot be found. */
1250 mz_bool mz_zip_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment,
1251                               mz_uint flags, mz_uint32 *pIndex);
1252 
1253 /* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions
1254  * retrieve/manipulate this field. */
1255 /* Note that the m_last_error functionality is not thread safe. */
1256 mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num);
1257 mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip);
1258 mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip);
1259 mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip);
1260 const char *mz_zip_get_error_string(mz_zip_error mz_err);
1261 
1262 /* MZ_TRUE if the archive file entry is a directory entry. */
1263 mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index);
1264 
1265 /* MZ_TRUE if the file is encrypted/strong encrypted. */
1266 mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index);
1267 
1268 /* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is
1269  * not a compressed patch file. */
1270 mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index);
1271 
1272 /* Retrieves the filename of an archive file entry. */
1273 /* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function
1274  * returns the number of bytes needed to fully store the filename. */
1275 mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename,
1276                                    mz_uint filename_buf_size);
1277 
1278 /* Attempts to locates a file in the archive's central directory. */
1279 /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */
1280 /* Returns -1 if the file cannot be found. */
1281 int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment,
1282                               mz_uint flags);
1283 int mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment,
1284                                  mz_uint flags, mz_uint32 *file_index);
1285 
1286 /* Returns detailed information about an archive file entry. */
1287 mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
1288                                 mz_zip_archive_file_stat *pStat);
1289 
1290 /* MZ_TRUE if the file is in zip64 format. */
1291 /* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it
1292  * contained any zip64 extended file information fields in the central directory. */
1293 mz_bool mz_zip_is_zip64(mz_zip_archive *pZip);
1294 
1295 /* Returns the total central directory size in bytes. */
1296 /* The current max supported size is <= MZ_UINT32_MAX. */
1297 size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip);
1298 
1299 /* Extracts a archive file to a memory buffer using no memory allocation. */
1300 /* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */
1301 mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf,
1302                                               size_t buf_size, mz_uint flags, void *pUser_read_buf,
1303                                               size_t user_read_buf_size);
1304 mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename,
1305                                                    void *pBuf, size_t buf_size, mz_uint flags,
1306                                                    void *pUser_read_buf, size_t user_read_buf_size);
1307 
1308 /* Extracts a archive file to a memory buffer. */
1309 mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf,
1310                                      size_t buf_size, mz_uint flags);
1311 mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf,
1312                                           size_t buf_size, mz_uint flags);
1313 
1314 /* Extracts a archive file to a dynamically allocated heap buffer. */
1315 /* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */
1316 /* Returns NULL and sets the last error on failure. */
1317 void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize,
1318                                     mz_uint flags);
1319 void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize,
1320                                          mz_uint flags);
1321 
1322 /* Extracts a archive file using a callback function to output the file's data. */
1323 mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index,
1324                                           mz_file_write_func pCallback, void *pOpaque,
1325                                           mz_uint flags);
1326 mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename,
1327                                                mz_file_write_func pCallback, void *pOpaque,
1328                                                mz_uint flags);
1329 
1330 /* Extract a file iteratively */
1331 mz_zip_reader_extract_iter_state *mz_zip_reader_extract_iter_new(mz_zip_archive *pZip,
1332                                                                  mz_uint file_index, mz_uint flags);
1333 mz_zip_reader_extract_iter_state *mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip,
1334                                                                       const char *pFilename,
1335                                                                       mz_uint flags);
1336 size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state *pState, void *pvBuf,
1337                                        size_t buf_size);
1338 mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state *pState);
1339 
1340 #ifndef MINIZ_NO_STDIO
1341 /* Extracts a archive file to a disk file and sets its last accessed and modified times. */
1342 /* This function only extracts files, not archive directory records. */
1343 mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
1344                                       const char *pDst_filename, mz_uint flags);
1345 mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename,
1346                                            const char *pDst_filename, mz_uint flags);
1347 
1348 /* Extracts a archive file starting at the current position in the destination FILE stream. */
1349 mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File,
1350                                        mz_uint flags);
1351 mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename,
1352                                             MZ_FILE *pFile, mz_uint flags);
1353 #endif
1354 
1355 #if 0
1356 /* TODO */
1357 	typedef void *mz_zip_streaming_extract_state_ptr;
1358 	mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags);
1359 	uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
1360 	uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
1361 	mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs);
1362 	size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size);
1363 	mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
1364 #endif
1365 
1366 /* This function compares the archive's local headers, the optional local zip64 extended information
1367  * block, and the optional descriptor following the compressed data vs. the data in the central
1368  * directory. */
1369 /* It also validates that each file can be successfully uncompressed unless the
1370  * MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */
1371 mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags);
1372 
1373 /* Validates an entire archive by calling mz_zip_validate_file() on each file. */
1374 mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags);
1375 
1376 /* Misc utils/helpers, valid for ZIP reading or writing */
1377 mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags,
1378                                     mz_zip_error *pErr);
1379 mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr);
1380 
1381 /* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */
1382 mz_bool mz_zip_end(mz_zip_archive *pZip);
1383 
1384 /* -------- ZIP writing */
1385 
1386 #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
1387 
1388 /* Inits a ZIP archive writer. */
1389 /*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or
1390  * mz_zip_writer_init_v2*/
1391 /*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/
1392 mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
1393 mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags);
1394 
1395 mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning,
1396                                 size_t initial_allocation_size);
1397 mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning,
1398                                    size_t initial_allocation_size, mz_uint flags);
1399 
1400 #ifndef MINIZ_NO_STDIO
1401 mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
1402                                 mz_uint64 size_to_reserve_at_beginning);
1403 mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename,
1404                                    mz_uint64 size_to_reserve_at_beginning, mz_uint flags);
1405 mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags);
1406 #endif
1407 
1408 /* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file
1409  * appends to occur on an existing archive. */
1410 /* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it
1411  * can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called.
1412  */
1413 /* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the
1414  * realloc callback (which defaults to realloc unless you've overridden it). */
1415 /* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided
1416  * m_pWrite function cannot be NULL. */
1417 /* Note: In-place archive modification is not recommended unless you know what you're doing, because
1418  * if execution stops or something goes wrong before */
1419 /* the archive is finalized the file's central directory will be hosed. */
1420 mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename);
1421 mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename,
1422                                           mz_uint flags);
1423 
1424 /* Adds the contents of a memory buffer to an archive. These functions record the current local time
1425  * into the archive. */
1426 /* To add a directory entry, call this method with an archive name ending in a forwardslash with an
1427  * empty buffer. */
1428 /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.)
1429  * logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */
1430 mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf,
1431                               size_t buf_size, mz_uint level_and_flags);
1432 
1433 /* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply
1434  * the function with already compressed data. */
1435 /* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */
1436 mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf,
1437                                  size_t buf_size, const void *pComment, mz_uint16 comment_size,
1438                                  mz_uint level_and_flags, mz_uint64 uncomp_size,
1439                                  mz_uint32 uncomp_crc32);
1440 
1441 mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name,
1442                                     const void *pBuf, size_t buf_size, const void *pComment,
1443                                     mz_uint16 comment_size, mz_uint level_and_flags,
1444                                     mz_uint64 uncomp_size, mz_uint32 uncomp_crc32,
1445                                     MZ_TIME_T *last_modified, const char *user_extra_data_local,
1446                                     mz_uint user_extra_data_local_len,
1447                                     const char *user_extra_data_central,
1448                                     mz_uint user_extra_data_central_len);
1449 
1450 #ifndef MINIZ_NO_STDIO
1451 /* Adds the contents of a disk file to an archive. This function also records the disk file's
1452  * modified time into the archive. */
1453 /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.)
1454  * logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */
1455 mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
1456                                const char *pSrc_filename, const void *pComment,
1457                                mz_uint16 comment_size, mz_uint level_and_flags);
1458 
1459 /* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */
1460 mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file,
1461                                 mz_uint64 size_to_add, const MZ_TIME_T *pFile_time,
1462                                 const void *pComment, mz_uint16 comment_size,
1463                                 mz_uint level_and_flags, const char *user_extra_data_local,
1464                                 mz_uint user_extra_data_local_len,
1465                                 const char *user_extra_data_central,
1466                                 mz_uint user_extra_data_central_len);
1467 #endif
1468 
1469 /* Adds a file to an archive by fully cloning the data from another archive. */
1470 /* This function fully clones the source file's compressed data (no recompression), along with its
1471  * full filename, extra data (it may add or modify the zip64 local header extra data field), and the
1472  * optional descriptor following the compressed data. */
1473 mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip,
1474                                           mz_uint src_file_index);
1475 
1476 /* Finalizes the archive by writing the central directory records followed by the end of central
1477  * directory record. */
1478 /* After an archive is finalized, the only valid call on the mz_zip_archive struct is
1479  * mz_zip_writer_end(). */
1480 /* An archive must be manually finalized by calling this function for it to be valid. */
1481 mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
1482 
1483 /* Finalizes a heap archive, returning a poiner to the heap block and its size. */
1484 /* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */
1485 mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize);
1486 
1487 /* Ends archive writing, freeing all allocations, and closing the output file if
1488  * mz_zip_writer_init_file() was used. */
1489 /* Note for the archive to be valid, it *must* have been finalized before ending (this function will
1490  * not do it for you). */
1491 mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
1492 
1493 /* -------- Misc. high-level helper functions: */
1494 
1495 /* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob
1496  * to a ZIP archive. */
1497 /* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be
1498  * left in a screwed up state (without a central directory). */
1499 /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.)
1500  * logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */
1501 /* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We
1502  * could then truncate the file (so the old central dir would be at the end) if something goes
1503  * wrong. */
1504 mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
1505                                                 const char *pArchive_name, const void *pBuf,
1506                                                 size_t buf_size, const void *pComment,
1507                                                 mz_uint16 comment_size, mz_uint level_and_flags);
1508 mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename,
1509                                                    const char *pArchive_name, const void *pBuf,
1510                                                    size_t buf_size, const void *pComment,
1511                                                    mz_uint16 comment_size, mz_uint level_and_flags,
1512                                                    mz_zip_error *pErr);
1513 
1514 /* Reads a single file from an archive into a heap block. */
1515 /* If pComment is not NULL, only the file with the specified comment will be extracted. */
1516 /* Returns NULL on failure. */
1517 void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name,
1518                                           size_t *pSize, mz_uint flags);
1519 void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name,
1520                                              const char *pComment, size_t *pSize, mz_uint flags,
1521                                              mz_zip_error *pErr);
1522 
1523 #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */
1524 
1525 #ifdef __cplusplus
1526 }
1527 #endif
1528 
1529 #endif /* MINIZ_NO_ARCHIVE_APIS */
1530