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