]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/common/miniz.h
Merge commit 'dfce2da577f1e56886ad26e58e37d9eda2d7c8a3' into garux-merge
[xonotic/netradiant.git] / tools / quake3 / common / miniz.h
1 /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing
2    See "unlicense" statement at the end of this file.
3    Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
4    Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
5
6    Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define
7    MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).
8
9    * Change History
10      10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!):
11        - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug
12         would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place()
13         (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag).
14        - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size
15        - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries.
16          Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice).
17        - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes
18        - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
19        - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6.
20        - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
21        - Merged MZ_FORCEINLINE fix from hdeanclark
22        - Fix <time.h> include before config #ifdef, thanks emil.brink
23        - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can
24         set it to 1 for real-time compression).
25        - Merged in some compiler fixes from paulharris's github repro.
26        - Retested this build under Windows (VS 2010, including static analysis), tcc  0.9.26, gcc v4.6 and clang v3.3.
27        - Added example6.c, which dumps an image of the mandelbrot set to a PNG file.
28        - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
29        - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled
30        - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch
31      5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect).
32      5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
33        - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files.
34        - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
35        - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly
36         "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning).
37        - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64.
38        - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test.
39        - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives.
40        - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.)
41        - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself).
42      4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's.
43       level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report.
44      5/28/11 v1.11 - Added statement from unlicense.org
45      5/27/11 v1.10 - Substantial compressor optimizations:
46       - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a
47       - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86).
48       - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types.
49       - Refactored the compression code for better readability and maintainability.
50       - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large
51        drop in throughput on some files).
52      5/15/11 v1.09 - Initial stable release.
53
54    * Low-level Deflate/Inflate implementation notes:
55
56      Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or
57      greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses
58      approximately as well as zlib.
59
60      Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function
61      coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory
62      block large enough to hold the entire file.
63
64      The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation.
65
66    * zlib-style API notes:
67
68      miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in
69      zlib replacement in many apps:
70         The z_stream struct, optional memory allocation callbacks
71         deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
72         inflateInit/inflateInit2/inflate/inflateEnd
73         compress, compress2, compressBound, uncompress
74         CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines.
75         Supports raw deflate streams or standard zlib streams with adler-32 checking.
76
77      Limitations:
78       The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries.
79       I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but
80       there are no guarantees that miniz.c pulls this off perfectly.
81
82    * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by
83      Alex Evans. Supports 1-4 bytes/pixel images.
84
85    * ZIP archive API notes:
86
87      The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to
88      get the job done with minimal fuss. There are simple API's to retrieve file information, read files from
89      existing archives, create new archives, append new files to existing archives, or clone archive data from
90      one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h),
91      or you can specify custom file read/write callbacks.
92
93      - Archive reading: Just call this function to read a single file from a disk archive:
94
95       void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name,
96         size_t *pSize, mz_uint zip_flags);
97
98      For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central
99      directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files.
100
101      - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file:
102
103      int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
104
105      The locate operation can optionally check file comments too, which (as one example) can be used to identify
106      multiple versions of the same file in an archive. This function uses a simple linear search through the central
107      directory, so it's not very fast.
108
109      Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and
110      retrieve detailed info on each file by calling mz_zip_reader_file_stat().
111
112      - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data
113      to disk and builds an exact image of the central directory in memory. The central directory image is written
114      all at once at the end of the archive file when the archive is finalized.
115
116      The archive writer can optionally align each file's local header and file data to any power of 2 alignment,
117      which can be useful when the archive will be read from optical media. Also, the writer supports placing
118      arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still
119      readable by any ZIP tool.
120
121      - Archive appending: The simple way to add a single file to an archive is to call this function:
122
123       mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name,
124         const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
125
126      The archive will be created if it doesn't already exist, otherwise it'll be appended to.
127      Note the appending is done in-place and is not an atomic operation, so if something goes wrong
128      during the operation it's possible the archive could be left without a central directory (although the local
129      file headers and file data will be fine, so the archive will be recoverable).
130
131      For more complex archive modification scenarios:
132      1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to
133      preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the
134      compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and
135      you're done. This is safe but requires a bunch of temporary disk space or heap memory.
136
137      2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(),
138      append new files as needed, then finalize the archive which will write an updated central directory to the
139      original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a
140      possibility that the archive's central directory could be lost with this method if anything goes wrong, though.
141
142      - ZIP archive support limitations:
143      No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files.
144      Requires streams capable of seeking.
145
146    * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the
147      below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.
148
149    * Important: For best perf. be sure to customize the below macros for your target platform:
150      #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
151      #define MINIZ_LITTLE_ENDIAN 1
152      #define MINIZ_HAS_64BIT_REGISTERS 1
153
154    * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz
155      uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files
156      (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
157 */
158
159 #ifndef MINIZ_HEADER_INCLUDED
160 #define MINIZ_HEADER_INCLUDED
161
162 #include <stdlib.h>
163
164 // Defines to completely disable specific portions of miniz.c:
165 // If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl.
166
167 // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O.
168 //#define MINIZ_NO_STDIO
169
170 // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or
171 // get/set file times, and the C run-time funcs that get/set times won't be called.
172 // The current downside is the times written to your archives will be from 1979.
173 //#define MINIZ_NO_TIME
174
175 // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
176 //#define MINIZ_NO_ARCHIVE_APIS
177
178 // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's.
179 //#define MINIZ_NO_ARCHIVE_WRITING_APIS
180
181 // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's.
182 //#define MINIZ_NO_ZLIB_APIS
183
184 // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib.
185 //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
186
187 // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
188 // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc
189 // callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user
190 // functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
191 //#define MINIZ_NO_MALLOC
192
193 #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) || defined(__ia64__) || defined(__x86_64__)
203 // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
204 #define MINIZ_X86_OR_X64_CPU 1
205 #endif
206
207 #if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
208 // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
209 #define MINIZ_LITTLE_ENDIAN 1
210 #endif
211
212 #if MINIZ_X86_OR_X64_CPU
213 // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
214 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
215 #endif
216
217 #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
218 // 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).
219 #define MINIZ_HAS_64BIT_REGISTERS 1
220 #endif
221
222 #ifdef __cplusplus
223 extern "C" {
224 #endif
225
226 // ------------------- zlib-style API Definitions.
227
228 // 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!
229 typedef unsigned long mz_ulong;
230
231 // 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.
232 void mz_free(void *p);
233
234 #define MZ_ADLER32_INIT (1)
235 // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
236 mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
237
238 #define MZ_CRC32_INIT (0)
239 // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
240 mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
241
242 // Compression strategies.
243 enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
244
245 // Method
246 #define MZ_DEFLATED 8
247
248 #ifndef MINIZ_NO_ZLIB_APIS
249
250 // Heap allocation callbacks.
251 // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
252 typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
253 typedef void (*mz_free_func)(void *opaque, void *address);
254 typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
255
256 #define MZ_VERSION          "9.1.15"
257 #define MZ_VERNUM           0x91F0
258 #define MZ_VER_MAJOR        9
259 #define MZ_VER_MINOR        1
260 #define MZ_VER_REVISION     15
261 #define MZ_VER_SUBREVISION  0
262
263 // 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).
264 enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 };
265
266 // Return status codes. MZ_PARAM_ERROR is non-standard.
267 enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 };
268
269 // 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.
270 enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 };
271
272 // Window bits
273 #define MZ_DEFAULT_WINDOW_BITS 15
274
275 struct mz_internal_state;
276
277 // Compression/decompression stream struct.
278 typedef struct mz_stream_s
279 {
280   const unsigned char *next_in;     // pointer to next byte to read
281   unsigned int avail_in;            // number of bytes available at next_in
282   mz_ulong total_in;                // total number of bytes consumed so far
283
284   unsigned char *next_out;          // pointer to next byte to write
285   unsigned int avail_out;           // number of bytes that can be written to next_out
286   mz_ulong total_out;               // total number of bytes produced so far
287
288   char *msg;                        // error msg (unused)
289   struct mz_internal_state *state;  // internal state, allocated by zalloc/zfree
290
291   mz_alloc_func zalloc;             // optional heap allocation function (defaults to malloc)
292   mz_free_func zfree;               // optional heap free function (defaults to free)
293   void *opaque;                     // heap alloc function user pointer
294
295   int data_type;                    // data_type (unused)
296   mz_ulong adler;                   // adler32 of the source or uncompressed data
297   mz_ulong reserved;                // not used
298 } mz_stream;
299
300 typedef mz_stream *mz_streamp;
301
302 // Returns the version string of miniz.c.
303 const char *mz_version(void);
304
305 // mz_deflateInit() initializes a compressor with default options:
306 // Parameters:
307 //  pStream must point to an initialized mz_stream struct.
308 //  level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
309 //  level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
310 //  (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
311 // Return values:
312 //  MZ_OK on success.
313 //  MZ_STREAM_ERROR if the stream is bogus.
314 //  MZ_PARAM_ERROR if the input parameters are bogus.
315 //  MZ_MEM_ERROR on out of memory.
316 int mz_deflateInit(mz_streamp pStream, int level);
317
318 // mz_deflateInit2() is like mz_deflate(), except with more control:
319 // Additional parameters:
320 //   method must be MZ_DEFLATED
321 //   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)
322 //   mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
323 int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);
324
325 // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
326 int mz_deflateReset(mz_streamp pStream);
327
328 // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
329 // Parameters:
330 //   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.
331 //   flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
332 // Return values:
333 //   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).
334 //   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.
335 //   MZ_STREAM_ERROR if the stream is bogus.
336 //   MZ_PARAM_ERROR if one of the parameters is invalid.
337 //   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.)
338 int mz_deflate(mz_streamp pStream, int flush);
339
340 // mz_deflateEnd() deinitializes a compressor:
341 // Return values:
342 //  MZ_OK on success.
343 //  MZ_STREAM_ERROR if the stream is bogus.
344 int mz_deflateEnd(mz_streamp pStream);
345
346 // 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.
347 mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
348
349 // Single-call compression functions mz_compress() and mz_compress2():
350 // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
351 int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
352 int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);
353
354 // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
355 mz_ulong mz_compressBound(mz_ulong source_len);
356
357 // Initializes a decompressor.
358 int mz_inflateInit(mz_streamp pStream);
359
360 // 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:
361 // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
362 int mz_inflateInit2(mz_streamp pStream, int window_bits);
363
364 // 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.
365 // Parameters:
366 //   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.
367 //   flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
368 //   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).
369 //   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.
370 // Return values:
371 //   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.
372 //   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.
373 //   MZ_STREAM_ERROR if the stream is bogus.
374 //   MZ_DATA_ERROR if the deflate stream is invalid.
375 //   MZ_PARAM_ERROR if one of the parameters is invalid.
376 //   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
377 //   with more input data, or with more room in the output buffer (except when using single call decompression, described above).
378 int mz_inflate(mz_streamp pStream, int flush);
379
380 // Deinitializes a decompressor.
381 int mz_inflateEnd(mz_streamp pStream);
382
383 // Single-call decompression.
384 // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
385 int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
386
387 // Returns a string description of the specified error code, or NULL if the error code is invalid.
388 const char *mz_error(int err);
389
390 // 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.
391 // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
392 #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
393   typedef unsigned char Byte;
394   typedef unsigned int uInt;
395   typedef mz_ulong uLong;
396   typedef Byte Bytef;
397   typedef uInt uIntf;
398   typedef char charf;
399   typedef int intf;
400   typedef void *voidpf;
401   typedef uLong uLongf;
402   typedef void *voidp;
403   typedef void *const voidpc;
404   #define Z_NULL                0
405   #define Z_NO_FLUSH            MZ_NO_FLUSH
406   #define Z_PARTIAL_FLUSH       MZ_PARTIAL_FLUSH
407   #define Z_SYNC_FLUSH          MZ_SYNC_FLUSH
408   #define Z_FULL_FLUSH          MZ_FULL_FLUSH
409   #define Z_FINISH              MZ_FINISH
410   #define Z_BLOCK               MZ_BLOCK
411   #define Z_OK                  MZ_OK
412   #define Z_STREAM_END          MZ_STREAM_END
413   #define Z_NEED_DICT           MZ_NEED_DICT
414   #define Z_ERRNO               MZ_ERRNO
415   #define Z_STREAM_ERROR        MZ_STREAM_ERROR
416   #define Z_DATA_ERROR          MZ_DATA_ERROR
417   #define Z_MEM_ERROR           MZ_MEM_ERROR
418   #define Z_BUF_ERROR           MZ_BUF_ERROR
419   #define Z_VERSION_ERROR       MZ_VERSION_ERROR
420   #define Z_PARAM_ERROR         MZ_PARAM_ERROR
421   #define Z_NO_COMPRESSION      MZ_NO_COMPRESSION
422   #define Z_BEST_SPEED          MZ_BEST_SPEED
423   #define Z_BEST_COMPRESSION    MZ_BEST_COMPRESSION
424   #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
425   #define Z_DEFAULT_STRATEGY    MZ_DEFAULT_STRATEGY
426   #define Z_FILTERED            MZ_FILTERED
427   #define Z_HUFFMAN_ONLY        MZ_HUFFMAN_ONLY
428   #define Z_RLE                 MZ_RLE
429   #define Z_FIXED               MZ_FIXED
430   #define Z_DEFLATED            MZ_DEFLATED
431   #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
432   #define alloc_func            mz_alloc_func
433   #define free_func             mz_free_func
434   #define internal_state        mz_internal_state
435   #define z_stream              mz_stream
436   #define deflateInit           mz_deflateInit
437   #define deflateInit2          mz_deflateInit2
438   #define deflateReset          mz_deflateReset
439   #define deflate               mz_deflate
440   #define deflateEnd            mz_deflateEnd
441   #define deflateBound          mz_deflateBound
442   #define compress              mz_compress
443   #define compress2             mz_compress2
444   #define compressBound         mz_compressBound
445   #define inflateInit           mz_inflateInit
446   #define inflateInit2          mz_inflateInit2
447   #define inflate               mz_inflate
448   #define inflateEnd            mz_inflateEnd
449   #define uncompress            mz_uncompress
450   #define crc32                 mz_crc32
451   #define adler32               mz_adler32
452   #define MAX_WBITS             15
453   #define MAX_MEM_LEVEL         9
454   #define zError                mz_error
455   #define ZLIB_VERSION          MZ_VERSION
456   #define ZLIB_VERNUM           MZ_VERNUM
457   #define ZLIB_VER_MAJOR        MZ_VER_MAJOR
458   #define ZLIB_VER_MINOR        MZ_VER_MINOR
459   #define ZLIB_VER_REVISION     MZ_VER_REVISION
460   #define ZLIB_VER_SUBREVISION  MZ_VER_SUBREVISION
461   #define zlibVersion           mz_version
462   #define zlib_version          mz_version()
463 #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
464
465 #endif // MINIZ_NO_ZLIB_APIS
466
467 // ------------------- Types and macros
468
469 typedef unsigned char mz_uint8;
470 typedef signed short mz_int16;
471 typedef unsigned short mz_uint16;
472 typedef unsigned int mz_uint32;
473 typedef unsigned int mz_uint;
474 typedef long long mz_int64;
475 typedef unsigned long long mz_uint64;
476 typedef int mz_bool;
477
478 #define MZ_FALSE (0)
479 #define MZ_TRUE (1)
480
481 // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message.
482 #ifdef _MSC_VER
483    #define MZ_MACRO_END while (0, 0)
484 #else
485    #define MZ_MACRO_END while (0)
486 #endif
487
488 // ------------------- ZIP archive reading/writing
489
490 #ifndef MINIZ_NO_ARCHIVE_APIS
491
492 enum
493 {
494   MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024,
495   MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
496   MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
497 };
498
499 typedef struct
500 {
501   mz_uint32 m_file_index;
502   mz_uint32 m_central_dir_ofs;
503   mz_uint16 m_version_made_by;
504   mz_uint16 m_version_needed;
505   mz_uint16 m_bit_flag;
506   mz_uint16 m_method;
507 #ifndef MINIZ_NO_TIME
508   time_t m_time;
509 #endif
510   mz_uint32 m_crc32;
511   mz_uint64 m_comp_size;
512   mz_uint64 m_uncomp_size;
513   mz_uint16 m_internal_attr;
514   mz_uint32 m_external_attr;
515   mz_uint64 m_local_header_ofs;
516   mz_uint32 m_comment_size;
517   char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
518   char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
519 } mz_zip_archive_file_stat;
520
521 typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n);
522 typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n);
523
524 struct mz_zip_internal_state_tag;
525 typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
526
527 typedef enum
528 {
529   MZ_ZIP_MODE_INVALID = 0,
530   MZ_ZIP_MODE_READING = 1,
531   MZ_ZIP_MODE_WRITING = 2,
532   MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
533 } mz_zip_mode;
534
535 typedef struct mz_zip_archive_tag
536 {
537   mz_uint64 m_archive_size;
538   mz_uint64 m_central_directory_file_ofs;
539   mz_uint m_total_files;
540   mz_zip_mode m_zip_mode;
541
542   mz_uint m_file_offset_alignment;
543
544   mz_alloc_func m_pAlloc;
545   mz_free_func m_pFree;
546   mz_realloc_func m_pRealloc;
547   void *m_pAlloc_opaque;
548
549   mz_file_read_func m_pRead;
550   mz_file_write_func m_pWrite;
551   void *m_pIO_opaque;
552
553   mz_zip_internal_state *m_pState;
554
555 } mz_zip_archive;
556
557 typedef enum
558 {
559   MZ_ZIP_FLAG_CASE_SENSITIVE                = 0x0100,
560   MZ_ZIP_FLAG_IGNORE_PATH                   = 0x0200,
561   MZ_ZIP_FLAG_COMPRESSED_DATA               = 0x0400,
562   MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
563 } mz_zip_flags;
564
565 // ZIP archive reading
566
567 // Inits a ZIP archive reader.
568 // These functions read and validate the archive's central directory.
569 mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags);
570 mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags);
571
572 #ifndef MINIZ_NO_STDIO
573 mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags);
574 #endif
575
576 // Returns the total number of files in the archive.
577 mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
578
579 // Returns detailed information about an archive file entry.
580 mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat);
581
582 // Determines if an archive file entry is a directory entry.
583 mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index);
584 mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index);
585
586 // Retrieves the filename of an archive file entry.
587 // 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.
588 mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size);
589
590 // Attempts to locates a file in the archive's central directory.
591 // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
592 // Returns -1 if the file cannot be found.
593 int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
594
595 // Extracts a archive file to a memory buffer using no memory allocation.
596 mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
597 mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
598
599 // Extracts a archive file to a memory buffer.
600 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);
601 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);
602
603 // Extracts a archive file to a dynamically allocated heap buffer.
604 void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags);
605 void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags);
606
607 // Extracts a archive file using a callback function to output the file's data.
608 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);
609 mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
610
611 #ifndef MINIZ_NO_STDIO
612 // Extracts a archive file to a disk file and sets its last accessed and modified times.
613 // This function only extracts files, not archive directory records.
614 mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags);
615 mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags);
616 #endif
617
618 // Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used.
619 mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
620
621 // ZIP archive writing
622
623 #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
624
625 // Inits a ZIP archive writer.
626 mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
627 mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size);
628
629 #ifndef MINIZ_NO_STDIO
630 mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning);
631 #endif
632
633 // Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive.
634 // 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.
635 // 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).
636 // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL.
637 // Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before
638 // the archive is finalized the file's central directory will be hosed.
639 mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename);
640
641 // Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive.
642 // To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer.
643 // 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.
644 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);
645 mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32);
646
647 #ifndef MINIZ_NO_STDIO
648 // Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive.
649 // 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.
650 mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
651 #endif
652
653 // Adds a file to an archive by fully cloning the data from another archive.
654 // This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields.
655 mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index);
656
657 // Finalizes the archive by writing the central directory records followed by the end of central directory record.
658 // After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end().
659 // An archive must be manually finalized by calling this function for it to be valid.
660 mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
661 mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize);
662
663 // Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used.
664 // Note for the archive to be valid, it must have been finalized before ending.
665 mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
666
667 // Misc. high-level helper functions:
668
669 // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive.
670 // 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.
671 mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
672 mz_bool mz_zip_add_mem_to_archive_file_in_place_with_time(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint16 dos_time, mz_uint16 dos_date);
673
674 // Reads a single file from an archive into a heap block.
675 // Returns NULL on failure.
676 void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags);
677
678 #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
679
680 #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
681
682 // ------------------- Low-level Decompression API Definitions
683
684 // Decompression flags used by tinfl_decompress().
685 // 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.
686 // 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.
687 // 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).
688 // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
689 enum
690 {
691   TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
692   TINFL_FLAG_HAS_MORE_INPUT = 2,
693   TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
694   TINFL_FLAG_COMPUTE_ADLER32 = 8
695 };
696
697 // High level decompression functions:
698 // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
699 // On entry:
700 //  pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
701 // On return:
702 //  Function returns a pointer to the decompressed data, or NULL on failure.
703 //  *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
704 //  The caller must call mz_free() on the returned block when it's no longer needed.
705 void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
706
707 // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
708 // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
709 #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
710 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);
711
712 // 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.
713 // Returns 1 on success or 0 on failure.
714 typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
715 int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
716
717 struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
718
719 // Max size of LZ dictionary.
720 #define TINFL_LZ_DICT_SIZE 32768
721
722 // Return status.
723 typedef enum
724 {
725   TINFL_STATUS_BAD_PARAM = -3,
726   TINFL_STATUS_ADLER32_MISMATCH = -2,
727   TINFL_STATUS_FAILED = -1,
728   TINFL_STATUS_DONE = 0,
729   TINFL_STATUS_NEEDS_MORE_INPUT = 1,
730   TINFL_STATUS_HAS_MORE_OUTPUT = 2
731 } tinfl_status;
732
733 // Initializes the decompressor to its initial state.
734 #define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
735 #define tinfl_get_adler32(r) (r)->m_check_adler32
736
737 // 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.
738 // 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.
739 tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
740
741 // Internal/private bits follow.
742 enum
743 {
744   TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
745   TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
746 };
747
748 typedef struct
749 {
750   mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
751   mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
752 } tinfl_huff_table;
753
754 #if MINIZ_HAS_64BIT_REGISTERS
755   #define TINFL_USE_64BIT_BITBUF 1
756 #endif
757
758 #if TINFL_USE_64BIT_BITBUF
759   typedef mz_uint64 tinfl_bit_buf_t;
760   #define TINFL_BITBUF_SIZE (64)
761 #else
762   typedef mz_uint32 tinfl_bit_buf_t;
763   #define TINFL_BITBUF_SIZE (32)
764 #endif
765
766 struct tinfl_decompressor_tag
767 {
768   mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
769   tinfl_bit_buf_t m_bit_buf;
770   size_t m_dist_from_out_buf_start;
771   tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
772   mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
773 };
774
775 // ------------------- Low-level Compression API Definitions
776
777 // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
778 #define TDEFL_LESS_MEMORY 0
779
780 // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
781 // 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).
782 enum
783 {
784   TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF
785 };
786
787 // 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.
788 // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
789 // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
790 // 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).
791 // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
792 // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
793 // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
794 // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
795 // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
796 enum
797 {
798   TDEFL_WRITE_ZLIB_HEADER             = 0x01000,
799   TDEFL_COMPUTE_ADLER32               = 0x02000,
800   TDEFL_GREEDY_PARSING_FLAG           = 0x04000,
801   TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
802   TDEFL_RLE_MATCHES                   = 0x10000,
803   TDEFL_FILTER_MATCHES                = 0x20000,
804   TDEFL_FORCE_ALL_STATIC_BLOCKS       = 0x40000,
805   TDEFL_FORCE_ALL_RAW_BLOCKS          = 0x80000
806 };
807
808 // High level compression functions:
809 // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
810 // On entry:
811 //  pSrc_buf, src_buf_len: Pointer and size of source block to compress.
812 //  flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
813 // On return:
814 //  Function returns a pointer to the compressed data, or NULL on failure.
815 //  *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
816 //  The caller must free() the returned block when it's no longer needed.
817 void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
818
819 // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
820 // Returns 0 on failure.
821 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);
822
823 // Compresses an image to a compressed PNG file in memory.
824 // On entry:
825 //  pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
826 //  The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
827 //  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
828 //  If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
829 // On return:
830 //  Function returns a pointer to the compressed data, or NULL on failure.
831 //  *pLen_out will be set to the size of the PNG image file.
832 //  The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
833 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);
834 void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out);
835
836 // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
837 typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
838
839 // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
840 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);
841
842 enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 };
843
844 // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
845 #if TDEFL_LESS_MEMORY
846 enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
847 #else
848 enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
849 #endif
850
851 // 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.
852 typedef enum
853 {
854   TDEFL_STATUS_BAD_PARAM = -2,
855   TDEFL_STATUS_PUT_BUF_FAILED = -1,
856   TDEFL_STATUS_OKAY = 0,
857   TDEFL_STATUS_DONE = 1,
858 } tdefl_status;
859
860 // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
861 typedef enum
862 {
863   TDEFL_NO_FLUSH = 0,
864   TDEFL_SYNC_FLUSH = 2,
865   TDEFL_FULL_FLUSH = 3,
866   TDEFL_FINISH = 4
867 } tdefl_flush;
868
869 // tdefl's compression state structure.
870 typedef struct
871 {
872   tdefl_put_buf_func_ptr m_pPut_buf_func;
873   void *m_pPut_buf_user;
874   mz_uint m_flags, m_max_probes[2];
875   int m_greedy_parsing;
876   mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
877   mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
878   mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
879   mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;
880   tdefl_status m_prev_return_status;
881   const void *m_pIn_buf;
882   void *m_pOut_buf;
883   size_t *m_pIn_buf_size, *m_pOut_buf_size;
884   tdefl_flush m_flush;
885   const mz_uint8 *m_pSrc;
886   size_t m_src_buf_left, m_out_buf_ofs;
887   mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
888   mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
889   mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
890   mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
891   mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
892   mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
893   mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
894   mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
895 } tdefl_compressor;
896
897 // Initializes the compressor.
898 // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
899 // 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.
900 // If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
901 // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
902 tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
903
904 // 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.
905 tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
906
907 // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
908 // tdefl_compress_buffer() always consumes the entire input buffer.
909 tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
910
911 tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
912 mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
913
914 // 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.
915 #ifndef MINIZ_NO_ZLIB_APIS
916 // Create tdefl_compress() flags given zlib-style compression parameters.
917 // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
918 // window_bits may be -15 (raw deflate) or 15 (zlib)
919 // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
920 mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
921 #endif // #ifndef MINIZ_NO_ZLIB_APIS
922
923 #ifdef __cplusplus
924 }
925 #endif
926
927 #endif // MINIZ_HEADER_INCLUDED
928
929 // ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.)