source: trunk/src/image/miniz.cc @ 520

Last change on this file since 520 was 520, checked in by epyon, 9 years ago
  • ecs updates
  • animation updates
  • ragdoll manager
  • lua has own random engine
  • several minor fixes
  • particle engine/particle group
  • shitload of other stuff
  • bullet world
File size: 130.8 KB
RevLine 
[484]1#include "nv/image/miniz.hh"
2#include "nv/core/profiler.hh"
3
4using namespace nv;
5
[487]6#define MINIZ_NO_TIME
7#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
8
9#define MINIZ_HAS_64BIT_REGISTERS 0
10#define TINFL_USE_64BIT_BITBUF 0
11
12#if NV_COMPILER == NV_CLANG
13#pragma clang diagnostic ignored "-Wunused-macros"
14#pragma clang diagnostic ignored "-Wold-style-cast"
15#pragma clang diagnostic ignored "-Wsign-conversion"
16#endif
17
[484]18#if defined( _M_IX86 ) || defined( _M_X64 ) || defined( __i386__ ) || defined( __i386 ) || defined( __i486__ ) || defined( __i486 ) || defined( i386 ) || defined( __ia64__ ) || defined( __x86_64__ )
19// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
20#define MINIZ_X86_OR_X64_CPU 1
21#endif
22
23#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
24// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
25#define MINIZ_LITTLE_ENDIAN 1
26#endif
27
28#if MINIZ_X86_OR_X64_CPU
29// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
30#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
31#endif
32
33#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
34// 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).
35#define MINIZ_HAS_64BIT_REGISTERS 1
36#endif
37
38#ifdef __cplusplus
39extern "C" {
40#endif
41
42        // ------------------- zlib-style API Definitions.
43
44        // 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!
45        typedef unsigned long mz_ulong;
46
47        // 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.
48        void mz_free( void *p );
49
50#define MZ_ADLER32_INIT (1)
51        // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
52        mz_ulong mz_adler32( mz_ulong adler, const unsigned char *ptr, size_t buf_len );
53
54#define MZ_CRC32_INIT (0)
55        // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
56        mz_ulong mz_crc32( mz_ulong crc, const unsigned char *ptr, size_t buf_len );
57
58        // Compression strategies.
59        enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
60
61        // Method
62#define MZ_DEFLATED 8
63
64#ifndef MINIZ_NO_ZLIB_APIS
65
66        // Heap allocation callbacks.
67        // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
68        typedef void *( *mz_alloc_func )( void *opaque, size_t items, size_t size );
69        typedef void( *mz_free_func )( void *opaque, void *address );
70        typedef void *( *mz_realloc_func )( void *opaque, void *address, size_t items, size_t size );
71
72#define MZ_VERSION          "9.1.15"
73#define MZ_VERNUM           0x91F0
74#define MZ_VER_MAJOR        9
75#define MZ_VER_MINOR        1
76#define MZ_VER_REVISION     15
77#define MZ_VER_SUBREVISION  0
78
79        // 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).
80        enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 };
81
82        // Return status codes. MZ_PARAM_ERROR is non-standard.
83        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 };
84
85        // 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.
86        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 };
87
88        // Window bits
89#define MZ_DEFAULT_WINDOW_BITS 15
90
91        struct mz_internal_state;
92
93        // Compression/decompression stream struct.
94        typedef struct mz_stream_s
95        {
96                const unsigned char *next_in;     // pointer to next byte to read
97                unsigned int avail_in;            // number of bytes available at next_in
98                mz_ulong total_in;                // total number of bytes consumed so far
99
100                unsigned char *next_out;          // pointer to next byte to write
101                unsigned int avail_out;           // number of bytes that can be written to next_out
102                mz_ulong total_out;               // total number of bytes produced so far
103
104                char *msg;                        // error msg (unused)
105                struct mz_internal_state *state;  // internal state, allocated by zalloc/zfree
106
107                mz_alloc_func zalloc;             // optional heap allocation function (defaults to malloc)
108                mz_free_func zfree;               // optional heap free function (defaults to free)
109                void *opaque;                     // heap alloc function user pointer
110
111                int data_type;                    // data_type (unused)
112                mz_ulong adler;                   // adler32 of the source or uncompressed data
113                mz_ulong reserved;                // not used
114        } mz_stream;
115
116        typedef mz_stream *mz_streamp;
117
118        // Returns the version string of miniz.c.
119        const char *mz_version( void );
120
121        // mz_deflateInit() initializes a compressor with default options:
122        // Parameters:
123        //  pStream must point to an initialized mz_stream struct.
124        //  level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
125        //  level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
126        //  (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
127        // Return values:
128        //  MZ_OK on success.
129        //  MZ_STREAM_ERROR if the stream is bogus.
130        //  MZ_PARAM_ERROR if the input parameters are bogus.
131        //  MZ_MEM_ERROR on out of memory.
132        int mz_deflateInit( mz_streamp pStream, int level );
133
134        // mz_deflateInit2() is like mz_deflate(), except with more control:
135        // Additional parameters:
136        //   method must be MZ_DEFLATED
137        //   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)
138        //   mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
139        int mz_deflateInit2( mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy );
140
141        // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
142        int mz_deflateReset( mz_streamp pStream );
143
144        // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
145        // Parameters:
146        //   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.
147        //   flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
148        // Return values:
149        //   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).
150        //   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.
151        //   MZ_STREAM_ERROR if the stream is bogus.
152        //   MZ_PARAM_ERROR if one of the parameters is invalid.
153        //   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.)
154        int mz_deflate( mz_streamp pStream, int flush );
155
156        // mz_deflateEnd() deinitializes a compressor:
157        // Return values:
158        //  MZ_OK on success.
159        //  MZ_STREAM_ERROR if the stream is bogus.
160        int mz_deflateEnd( mz_streamp pStream );
161
162        // 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.
163        mz_ulong mz_deflateBound( mz_streamp pStream, mz_ulong source_len );
164
165        // Single-call compression functions mz_compress() and mz_compress2():
166        // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
167        int mz_compress( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len );
168        int mz_compress2( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level );
169
170        // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
171        mz_ulong mz_compressBound( mz_ulong source_len );
172
173        // Initializes a decompressor.
174        int mz_inflateInit( mz_streamp pStream );
175
176        // 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:
177        // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
178        int mz_inflateInit2( mz_streamp pStream, int window_bits );
179
180        // 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.
181        // Parameters:
182        //   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.
183        //   flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
184        //   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).
185        //   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.
186        // Return values:
187        //   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.
188        //   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.
189        //   MZ_STREAM_ERROR if the stream is bogus.
190        //   MZ_DATA_ERROR if the deflate stream is invalid.
191        //   MZ_PARAM_ERROR if one of the parameters is invalid.
192        //   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
193        //   with more input data, or with more room in the output buffer (except when using single call decompression, described above).
194        int mz_inflate( mz_streamp pStream, int flush );
195
196        // Deinitializes a decompressor.
197        int mz_inflateEnd( mz_streamp pStream );
198
199        // Single-call decompression.
200        // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
201        int mz_uncompress( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len );
202
203        // Returns a string description of the specified error code, or NULL if the error code is invalid.
204        const char *mz_error( int err );
205
206        // 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.
207        // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
208#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
209        typedef unsigned char Byte;
210        typedef unsigned int uInt;
211        typedef mz_ulong uLong;
212        typedef Byte Bytef;
213        typedef uInt uIntf;
214        typedef char charf;
215        typedef int intf;
216        typedef void *voidpf;
217        typedef uLong uLongf;
218        typedef void *voidp;
219        typedef void *const voidpc;
220#define Z_NULL                0
221#define Z_NO_FLUSH            MZ_NO_FLUSH
222#define Z_PARTIAL_FLUSH       MZ_PARTIAL_FLUSH
223#define Z_SYNC_FLUSH          MZ_SYNC_FLUSH
224#define Z_FULL_FLUSH          MZ_FULL_FLUSH
225#define Z_FINISH              MZ_FINISH
226#define Z_BLOCK               MZ_BLOCK
227#define Z_OK                  MZ_OK
228#define Z_STREAM_END          MZ_STREAM_END
229#define Z_NEED_DICT           MZ_NEED_DICT
230#define Z_ERRNO               MZ_ERRNO
231#define Z_STREAM_ERROR        MZ_STREAM_ERROR
232#define Z_DATA_ERROR          MZ_DATA_ERROR
233#define Z_MEM_ERROR           MZ_MEM_ERROR
234#define Z_BUF_ERROR           MZ_BUF_ERROR
235#define Z_VERSION_ERROR       MZ_VERSION_ERROR
236#define Z_PARAM_ERROR         MZ_PARAM_ERROR
237#define Z_NO_COMPRESSION      MZ_NO_COMPRESSION
238#define Z_BEST_SPEED          MZ_BEST_SPEED
239#define Z_BEST_COMPRESSION    MZ_BEST_COMPRESSION
240#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
241#define Z_DEFAULT_STRATEGY    MZ_DEFAULT_STRATEGY
242#define Z_FILTERED            MZ_FILTERED
243#define Z_HUFFMAN_ONLY        MZ_HUFFMAN_ONLY
244#define Z_RLE                 MZ_RLE
245#define Z_FIXED               MZ_FIXED
246#define Z_DEFLATED            MZ_DEFLATED
247#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
248#define alloc_func            mz_alloc_func
249#define free_func             mz_free_func
250#define internal_state        mz_internal_state
251#define z_stream              mz_stream
252#define deflateInit           mz_deflateInit
253#define deflateInit2          mz_deflateInit2
254#define deflateReset          mz_deflateReset
255#define deflate               mz_deflate
256#define deflateEnd            mz_deflateEnd
257#define deflateBound          mz_deflateBound
258#define compress              mz_compress
259#define compress2             mz_compress2
260#define compressBound         mz_compressBound
261#define inflateInit           mz_inflateInit
262#define inflateInit2          mz_inflateInit2
263#define inflate               mz_inflate
264#define inflateEnd            mz_inflateEnd
265#define uncompress            mz_uncompress
266#define crc32                 mz_crc32
267#define adler32               mz_adler32
268#define MAX_WBITS             15
269#define MAX_MEM_LEVEL         9
270#define zError                mz_error
271#define ZLIB_VERSION          MZ_VERSION
272#define ZLIB_VERNUM           MZ_VERNUM
273#define ZLIB_VER_MAJOR        MZ_VER_MAJOR
274#define ZLIB_VER_MINOR        MZ_VER_MINOR
275#define ZLIB_VER_REVISION     MZ_VER_REVISION
276#define ZLIB_VER_SUBREVISION  MZ_VER_SUBREVISION
277#define zlibVersion           mz_version
278#define zlib_version          mz_version()
279#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
280
281#endif // MINIZ_NO_ZLIB_APIS
282
283        // ------------------- Types and macros
284
285        typedef unsigned char mz_uint8;
286        typedef signed short mz_int16;
287        typedef unsigned short mz_uint16;
288        typedef unsigned int mz_uint32;
289        typedef unsigned int mz_uint;
290        typedef long long mz_int64;
291        typedef unsigned long long mz_uint64;
292        typedef int mz_bool;
293
294#define MZ_FALSE (0)
295#define MZ_TRUE (1)
296
297        // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message.
298#ifdef _MSC_VER
299#define MZ_MACRO_END while (0, 0)
300#else
301#define MZ_MACRO_END while (0)
302#endif
303
304        // ------------------- ZIP archive reading/writing
305
306#ifndef MINIZ_NO_ARCHIVE_APIS
307
308        enum
309        {
310                MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
311                MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
312                MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
313        };
314
315        typedef struct
316        {
317                mz_uint32 m_file_index;
318                mz_uint32 m_central_dir_ofs;
319                mz_uint16 m_version_made_by;
320                mz_uint16 m_version_needed;
321                mz_uint16 m_bit_flag;
322                mz_uint16 m_method;
323#ifndef MINIZ_NO_TIME
324                time_t m_time;
325#endif
326                mz_uint32 m_crc32;
327                mz_uint64 m_comp_size;
328                mz_uint64 m_uncomp_size;
329                mz_uint16 m_internal_attr;
330                mz_uint32 m_external_attr;
331                mz_uint64 m_local_header_ofs;
332                mz_uint32 m_comment_size;
333                char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
334                char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
335        } mz_zip_archive_file_stat;
336
337        typedef size_t( *mz_file_read_func )( void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n );
338        typedef size_t( *mz_file_write_func )( void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n );
339
340        struct mz_zip_internal_state_tag;
341        typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
342
343        typedef enum
344        {
345                MZ_ZIP_MODE_INVALID = 0,
346                MZ_ZIP_MODE_READING = 1,
347                MZ_ZIP_MODE_WRITING = 2,
348                MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
349        } mz_zip_mode;
350
351        typedef struct mz_zip_archive_tag
352        {
353                mz_uint64 m_archive_size;
354                mz_uint64 m_central_directory_file_ofs;
355                mz_uint m_total_files;
356                mz_zip_mode m_zip_mode;
357
358                mz_uint m_file_offset_alignment;
359
360                mz_alloc_func m_pAlloc;
361                mz_free_func m_pFree;
362                mz_realloc_func m_pRealloc;
363                void *m_pAlloc_opaque;
364
365                mz_file_read_func m_pRead;
366                mz_file_write_func m_pWrite;
367                void *m_pIO_opaque;
368
369                mz_zip_internal_state *m_pState;
370
371        } mz_zip_archive;
372
373        typedef enum
374        {
375                MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
376                MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
377                MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
378                MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
379        } mz_zip_flags;
380
381        // ZIP archive reading
382
383        // Inits a ZIP archive reader.
384        // These functions read and validate the archive's central directory.
385        mz_bool mz_zip_reader_init( mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags );
386        mz_bool mz_zip_reader_init_mem( mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags );
387
388#ifndef MINIZ_NO_STDIO
389        mz_bool mz_zip_reader_init_file( mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags );
390#endif
391
392        // Returns the total number of files in the archive.
393        mz_uint mz_zip_reader_get_num_files( mz_zip_archive *pZip );
394
395        // Returns detailed information about an archive file entry.
396        mz_bool mz_zip_reader_file_stat( mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat );
397
398        // Determines if an archive file entry is a directory entry.
399        mz_bool mz_zip_reader_is_file_a_directory( mz_zip_archive *pZip, mz_uint file_index );
400        mz_bool mz_zip_reader_is_file_encrypted( mz_zip_archive *pZip, mz_uint file_index );
401
402        // Retrieves the filename of an archive file entry.
403        // 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.
404        mz_uint mz_zip_reader_get_filename( mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size );
405
406        // Attempts to locates a file in the archive's central directory.
407        // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
408        // Returns -1 if the file cannot be found.
409        int mz_zip_reader_locate_file( mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags );
410
411        // Extracts a archive file to a memory buffer using no memory allocation.
412        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 );
413        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 );
414
415        // Extracts a archive file to a memory buffer.
416        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 );
417        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 );
418
419        // Extracts a archive file to a dynamically allocated heap buffer.
420        void *mz_zip_reader_extract_to_heap( mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags );
421        void *mz_zip_reader_extract_file_to_heap( mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags );
422
423        // Extracts a archive file using a callback function to output the file's data.
424        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 );
425        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 );
426
427#ifndef MINIZ_NO_STDIO
428        // Extracts a archive file to a disk file and sets its last accessed and modified times.
429        // This function only extracts files, not archive directory records.
430        mz_bool mz_zip_reader_extract_to_file( mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags );
431        mz_bool mz_zip_reader_extract_file_to_file( mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags );
432#endif
433
434        // Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used.
435        mz_bool mz_zip_reader_end( mz_zip_archive *pZip );
436
437        // ZIP archive writing
438
439#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
440
441        // Inits a ZIP archive writer.
442        mz_bool mz_zip_writer_init( mz_zip_archive *pZip, mz_uint64 existing_size );
443        mz_bool mz_zip_writer_init_heap( mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size );
444
445#ifndef MINIZ_NO_STDIO
446        mz_bool mz_zip_writer_init_file( mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning );
447#endif
448
449        // Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive.
450        // 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.
451        // 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).
452        // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL.
453        // Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before
454        // the archive is finalized the file's central directory will be hosed.
455        mz_bool mz_zip_writer_init_from_reader( mz_zip_archive *pZip, const char *pFilename );
456
457        // Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive.
458        // To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer.
459        // 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.
460        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 );
461        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 );
462
463#ifndef MINIZ_NO_STDIO
464        // Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive.
465        // 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.
466        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 );
467#endif
468
469        // Adds a file to an archive by fully cloning the data from another archive.
470        // This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields.
471        mz_bool mz_zip_writer_add_from_zip_reader( mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index );
472
473        // Finalizes the archive by writing the central directory records followed by the end of central directory record.
474        // After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end().
475        // An archive must be manually finalized by calling this function for it to be valid.
476        mz_bool mz_zip_writer_finalize_archive( mz_zip_archive *pZip );
477        mz_bool mz_zip_writer_finalize_heap_archive( mz_zip_archive *pZip, void **pBuf, size_t *pSize );
478
479        // Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used.
480        // Note for the archive to be valid, it must have been finalized before ending.
481        mz_bool mz_zip_writer_end( mz_zip_archive *pZip );
482
483        // Misc. high-level helper functions:
484
485        // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive.
486        // 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.
487        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 );
488
489        // Reads a single file from an archive into a heap block.
490        // Returns NULL on failure.
491        void *mz_zip_extract_archive_file_to_heap( const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags );
492
493#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
494
495#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
496
497        // ------------------- Low-level Decompression API Definitions
498
499        // Decompression flags used by tinfl_decompress().
500        // 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.
501        // 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.
502        // 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).
503        // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
504        enum
505        {
506                TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
507                TINFL_FLAG_HAS_MORE_INPUT = 2,
508                TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
509                TINFL_FLAG_COMPUTE_ADLER32 = 8
510        };
511
512        // High level decompression functions:
513        // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
514        // On entry:
515        //  pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
516        // On return:
517        //  Function returns a pointer to the decompressed data, or NULL on failure.
518        //  *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
519        //  The caller must call mz_free() on the returned block when it's no longer needed.
520        void *tinfl_decompress_mem_to_heap( const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags );
521
522        // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
523        // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
524#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
525        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 );
526
527        // 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.
528        // Returns 1 on success or 0 on failure.
529        typedef int( *tinfl_put_buf_func_ptr )( const void* pBuf, int len, void *pUser );
530        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 );
531
532        struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
533
534        // Max size of LZ dictionary.
535#define TINFL_LZ_DICT_SIZE 32768
536
537        // Return status.
538        typedef enum
539        {
540                TINFL_STATUS_BAD_PARAM = -3,
541                TINFL_STATUS_ADLER32_MISMATCH = -2,
542                TINFL_STATUS_FAILED = -1,
543                TINFL_STATUS_DONE = 0,
544                TINFL_STATUS_NEEDS_MORE_INPUT = 1,
545                TINFL_STATUS_HAS_MORE_OUTPUT = 2
546        } tinfl_status;
547
548        // Initializes the decompressor to its initial state.
549#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
550#define tinfl_get_adler32(r) (r)->m_check_adler32
551
552        // 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.
553        // 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.
554        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 );
555
556        // Internal/private bits follow.
557        enum
558        {
559                TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
560                TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
561        };
562
563        typedef struct
564        {
565                mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
566                mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
567        } tinfl_huff_table;
568
569#if MINIZ_HAS_64BIT_REGISTERS
570#define TINFL_USE_64BIT_BITBUF 1
571#endif
572
573#if TINFL_USE_64BIT_BITBUF
574        typedef mz_uint64 tinfl_bit_buf_t;
575#define TINFL_BITBUF_SIZE (64)
576#else
577        typedef mz_uint32 tinfl_bit_buf_t;
578#define TINFL_BITBUF_SIZE (32)
579#endif
580
581        struct tinfl_decompressor_tag
582        {
583                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];
584                tinfl_bit_buf_t m_bit_buf;
585                size_t m_dist_from_out_buf_start;
586                tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
587                mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
588        };
589
590        // ------------------- Low-level Compression API Definitions
591
592        // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
593#define TDEFL_LESS_MEMORY 0
594
595        // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
596        // 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).
597        enum
598        {
599                TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF
600        };
601
602        // 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.
603        // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
604        // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
605        // 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).
606        // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
607        // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
608        // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
609        // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
610        // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
611        enum
612        {
613                TDEFL_WRITE_ZLIB_HEADER = 0x01000,
614                TDEFL_COMPUTE_ADLER32 = 0x02000,
615                TDEFL_GREEDY_PARSING_FLAG = 0x04000,
616                TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
617                TDEFL_RLE_MATCHES = 0x10000,
618                TDEFL_FILTER_MATCHES = 0x20000,
619                TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
620                TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
621        };
622
623        // High level compression functions:
624        // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
625        // On entry:
626        //  pSrc_buf, src_buf_len: Pointer and size of source block to compress.
627        //  flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
628        // On return:
629        //  Function returns a pointer to the compressed data, or NULL on failure.
630        //  *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
631        //  The caller must free() the returned block when it's no longer needed.
632        void *tdefl_compress_mem_to_heap( const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags );
633
634        // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
635        // Returns 0 on failure.
636        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 );
637
638        // Compresses an image to a compressed PNG file in memory.
639        // On entry:
640        //  pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
641        //  The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
642        //  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
643        //  If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
644        // On return:
645        //  Function returns a pointer to the compressed data, or NULL on failure.
646        //  *pLen_out will be set to the size of the PNG image file.
647        //  The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
648        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 );
649        void *tdefl_write_image_to_png_file_in_memory( const void *pImage, int w, int h, int num_chans, size_t *pLen_out );
650
651        // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
652        typedef mz_bool( *tdefl_put_buf_func_ptr )( const void* pBuf, int len, void *pUser );
653
654        // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
655        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 );
656
657        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 };
658
659        // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
660#if TDEFL_LESS_MEMORY
661        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 };
662#else
663        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 };
664#endif
665
666        // 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.
667        typedef enum
668        {
669                TDEFL_STATUS_BAD_PARAM = -2,
670                TDEFL_STATUS_PUT_BUF_FAILED = -1,
671                TDEFL_STATUS_OKAY = 0,
672                TDEFL_STATUS_DONE = 1,
673        } tdefl_status;
674
675        // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
676        typedef enum
677        {
678                TDEFL_NO_FLUSH = 0,
679                TDEFL_SYNC_FLUSH = 2,
680                TDEFL_FULL_FLUSH = 3,
681                TDEFL_FINISH = 4
682        } tdefl_flush;
683
684        // tdefl's compression state structure.
685        typedef struct
686        {
687                tdefl_put_buf_func_ptr m_pPut_buf_func;
688                void *m_pPut_buf_user;
689                mz_uint m_flags, m_max_probes[2];
690                int m_greedy_parsing;
691                mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
692                mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
693                mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
694                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;
695                tdefl_status m_prev_return_status;
696                const void *m_pIn_buf;
697                void *m_pOut_buf;
698                size_t *m_pIn_buf_size, *m_pOut_buf_size;
699                tdefl_flush m_flush;
700                const mz_uint8 *m_pSrc;
701                size_t m_src_buf_left, m_out_buf_ofs;
702                mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
703                mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
704                mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
705                mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
706                mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
707                mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
708                mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
709                mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
710        } tdefl_compressor;
711
712        // Initializes the compressor.
713        // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
714        // 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.
715        // If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
716        // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
717        tdefl_status tdefl_init( tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags );
718
719        // 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.
720        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 );
721
722        // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
723        // tdefl_compress_buffer() always consumes the entire input buffer.
724        tdefl_status tdefl_compress_buffer( tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush );
725
726        tdefl_status tdefl_get_prev_return_status( tdefl_compressor *d );
727        mz_uint32 tdefl_get_adler32( tdefl_compressor *d );
728
729        // 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.
730#ifndef MINIZ_NO_ZLIB_APIS
731        // Create tdefl_compress() flags given zlib-style compression parameters.
732        // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
733        // window_bits may be -15 (raw deflate) or 15 (zlib)
734        // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
735        mz_uint tdefl_create_comp_flags_from_zip_params( int level, int window_bits, int strategy );
736#endif // #ifndef MINIZ_NO_ZLIB_APIS
737
738#ifdef __cplusplus
739}
740#endif
741
742
743// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.)
744
745typedef unsigned char mz_validate_uint16[sizeof( mz_uint16 ) == 2 ? 1 : -1];
746typedef unsigned char mz_validate_uint32[sizeof( mz_uint32 ) == 4 ? 1 : -1];
747typedef unsigned char mz_validate_uint64[sizeof( mz_uint64 ) == 8 ? 1 : -1];
748
749#include <string.h>
750#include <assert.h>
751
752#define MZ_ASSERT(x) assert(x)
753
754#ifdef MINIZ_NO_MALLOC
755#define MZ_MALLOC(x) NULL
756#define MZ_FREE(x) (void)x, ((void)0)
757#define MZ_REALLOC(p, x) NULL
758#else
759#define MZ_MALLOC(x) nvmalloc(x)
760#define MZ_FREE(x) nvfree(x)
761#define MZ_REALLOC(p, x) nvrealloc(p, x)
762#endif
763
764#define MZ_MAX(a,b) (((a)>(b))?(a):(b))
765#define MZ_MIN(a,b) (((a)<(b))?(a):(b))
766#define MZ_CLEAR_OBJ(obj) nvmemset(&(obj), 0, sizeof(obj))
767
768#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
769#define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
770#define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
771#else
772#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
773#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
774#endif
775
776#ifdef _MSC_VER
777#define MZ_FORCEINLINE __forceinline
778#elif defined(__GNUC__)
779#define MZ_FORCEINLINE inline __attribute__((__always_inline__))
780#else
781#define MZ_FORCEINLINE inline
782#endif
783
784#ifdef __cplusplus
785extern "C" {
786#endif
787
788        // ------------------- zlib-style API's
789
790        mz_ulong mz_adler32( mz_ulong adler, const unsigned char *ptr, size_t buf_len )
791        {
792                mz_uint32 i, s1 = (mz_uint32)( adler & 0xffff ), s2 = (mz_uint32)( adler >> 16 ); size_t block_len = buf_len % 5552;
793                if ( !ptr ) return MZ_ADLER32_INIT;
794                while ( buf_len )
795                {
796                        for ( i = 0; i + 7 < block_len; i += 8, ptr += 8 )
797                        {
798                                s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
799                                s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
800                        }
801                        for ( ; i < block_len; ++i ) s1 += *ptr++, s2 += s1;
802                        s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
803                }
804                return ( s2 << 16 ) + s1;
805        }
806
807        // 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/
808        mz_ulong mz_crc32( mz_ulong crc, const mz_uint8 *ptr, size_t buf_len )
809        {
810                static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
811                        0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
812                mz_uint32 crcu32 = (mz_uint32)crc;
813                if ( !ptr ) return MZ_CRC32_INIT;
814                crcu32 = ~crcu32; while ( buf_len-- ) { mz_uint8 b = *ptr++; crcu32 = ( crcu32 >> 4 ) ^ s_crc32[( crcu32 & 0xF ) ^ ( b & 0xF )]; crcu32 = ( crcu32 >> 4 ) ^ s_crc32[( crcu32 & 0xF ) ^ ( b >> 4 )]; }
815                return ~crcu32;
816        }
817
818        void mz_free( void *p )
819        {
820                MZ_FREE( p );
821        }
822
823#ifndef MINIZ_NO_ZLIB_APIS
824
825        static void *def_alloc_func( void *opaque, size_t items, size_t size ) { (void)opaque, (void)items, (void)size; return MZ_MALLOC( items * size ); }
826        static void def_free_func( void *opaque, void *address ) { (void)opaque, (void)address; MZ_FREE( address ); }
[486]827//      static void *def_realloc_func( void *opaque, void *address, size_t items, size_t size ) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC( address, items * size ); }
[484]828
829        const char *mz_version( void )
830        {
831                return MZ_VERSION;
832        }
833
834        int mz_deflateInit( mz_streamp pStream, int level )
835        {
836                return mz_deflateInit2( pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY );
837        }
838
839        int mz_deflateInit2( mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy )
840        {
841                tdefl_compressor *pComp;
842                mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params( level, window_bits, strategy );
843
844                if ( !pStream ) return MZ_STREAM_ERROR;
845                if ( ( method != MZ_DEFLATED ) || ( ( mem_level < 1 ) || ( mem_level > 9 ) ) || ( ( window_bits != MZ_DEFAULT_WINDOW_BITS ) && ( -window_bits != MZ_DEFAULT_WINDOW_BITS ) ) ) return MZ_PARAM_ERROR;
846
847                pStream->data_type = 0;
848                pStream->adler = MZ_ADLER32_INIT;
849                pStream->msg = NULL;
850                pStream->reserved = 0;
851                pStream->total_in = 0;
852                pStream->total_out = 0;
853                if ( !pStream->zalloc ) pStream->zalloc = def_alloc_func;
854                if ( !pStream->zfree ) pStream->zfree = def_free_func;
855
856                pComp = (tdefl_compressor *)pStream->zalloc( pStream->opaque, 1, sizeof( tdefl_compressor ) );
857                if ( !pComp )
858                        return MZ_MEM_ERROR;
859
860                pStream->state = ( struct mz_internal_state * )pComp;
861
862                if ( tdefl_init( pComp, NULL, NULL, comp_flags ) != TDEFL_STATUS_OKAY )
863                {
864                        mz_deflateEnd( pStream );
865                        return MZ_PARAM_ERROR;
866                }
867
868                return MZ_OK;
869        }
870
871        int mz_deflateReset( mz_streamp pStream )
872        {
873                if ( ( !pStream ) || ( !pStream->state ) || ( !pStream->zalloc ) || ( !pStream->zfree ) ) return MZ_STREAM_ERROR;
874                pStream->total_in = pStream->total_out = 0;
875                tdefl_init( (tdefl_compressor*)pStream->state, NULL, NULL, ( (tdefl_compressor*)pStream->state )->m_flags );
876                return MZ_OK;
877        }
878
879        int mz_deflate( mz_streamp pStream, int flush )
880        {
881                size_t in_bytes, out_bytes;
882                mz_ulong orig_total_in, orig_total_out;
883                int mz_status = MZ_OK;
884
885                if ( ( !pStream ) || ( !pStream->state ) || ( flush < 0 ) || ( flush > MZ_FINISH ) || ( !pStream->next_out ) ) return MZ_STREAM_ERROR;
886                if ( !pStream->avail_out ) return MZ_BUF_ERROR;
887
888                if ( flush == MZ_PARTIAL_FLUSH ) flush = MZ_SYNC_FLUSH;
889
890                if ( ( (tdefl_compressor*)pStream->state )->m_prev_return_status == TDEFL_STATUS_DONE )
891                        return ( flush == MZ_FINISH ) ? MZ_STREAM_END : MZ_BUF_ERROR;
892
893                orig_total_in = pStream->total_in; orig_total_out = pStream->total_out;
894                for ( ; ; )
895                {
896                        tdefl_status defl_status;
897                        in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
898
899                        defl_status = tdefl_compress( (tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush );
900                        pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
901                        pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32( (tdefl_compressor*)pStream->state );
902
903                        pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes;
904                        pStream->total_out += (mz_uint)out_bytes;
905
906                        if ( defl_status < 0 )
907                        {
908                                mz_status = MZ_STREAM_ERROR;
909                                break;
910                        }
911                        else if ( defl_status == TDEFL_STATUS_DONE )
912                        {
913                                mz_status = MZ_STREAM_END;
914                                break;
915                        }
916                        else if ( !pStream->avail_out )
917                                break;
918                        else if ( ( !pStream->avail_in ) && ( flush != MZ_FINISH ) )
919                        {
920                                if ( ( flush ) || ( pStream->total_in != orig_total_in ) || ( pStream->total_out != orig_total_out ) )
921                                        break;
922                                return MZ_BUF_ERROR; // Can't make forward progress without some input.
923                        }
924                }
925                return mz_status;
926        }
927
928        int mz_deflateEnd( mz_streamp pStream )
929        {
930                if ( !pStream ) return MZ_STREAM_ERROR;
931                if ( pStream->state )
932                {
933                        pStream->zfree( pStream->opaque, pStream->state );
934                        pStream->state = NULL;
935                }
936                return MZ_OK;
937        }
938
939        mz_ulong mz_deflateBound( mz_streamp pStream, mz_ulong source_len )
940        {
941                (void)pStream;
942                // 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.)
943                return MZ_MAX( 128 + ( source_len * 110 ) / 100, 128 + source_len + ( ( source_len / ( 31 * 1024 ) ) + 1 ) * 5 );
944        }
945
946        int mz_compress2( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level )
947        {
948                int status;
949                mz_stream stream;
950                memset( &stream, 0, sizeof( stream ) );
951
952                // In case mz_ulong is 64-bits (argh I hate longs).
953                if ( ( source_len | *pDest_len ) > 0xFFFFFFFFU ) return MZ_PARAM_ERROR;
954
955                stream.next_in = pSource;
956                stream.avail_in = (mz_uint32)source_len;
957                stream.next_out = pDest;
958                stream.avail_out = (mz_uint32)*pDest_len;
959
960                status = mz_deflateInit( &stream, level );
961                if ( status != MZ_OK ) return status;
962
963                status = mz_deflate( &stream, MZ_FINISH );
964                if ( status != MZ_STREAM_END )
965                {
966                        mz_deflateEnd( &stream );
967                        return ( status == MZ_OK ) ? MZ_BUF_ERROR : status;
968                }
969
970                *pDest_len = stream.total_out;
971                return mz_deflateEnd( &stream );
972        }
973
974        int mz_compress( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len )
975        {
976                return mz_compress2( pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION );
977        }
978
979        mz_ulong mz_compressBound( mz_ulong source_len )
980        {
981                return mz_deflateBound( NULL, source_len );
982        }
983
984        typedef struct
985        {
986                tinfl_decompressor m_decomp;
987                mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits;
988                mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
989                tinfl_status m_last_status;
990        } inflate_state;
991
992        int mz_inflateInit2( mz_streamp pStream, int window_bits )
993        {
994                inflate_state *pDecomp;
995                if ( !pStream ) return MZ_STREAM_ERROR;
996                if ( ( window_bits != MZ_DEFAULT_WINDOW_BITS ) && ( -window_bits != MZ_DEFAULT_WINDOW_BITS ) ) return MZ_PARAM_ERROR;
997
998                pStream->data_type = 0;
999                pStream->adler = 0;
1000                pStream->msg = NULL;
1001                pStream->total_in = 0;
1002                pStream->total_out = 0;
1003                pStream->reserved = 0;
1004                if ( !pStream->zalloc ) pStream->zalloc = def_alloc_func;
1005                if ( !pStream->zfree ) pStream->zfree = def_free_func;
1006
1007                pDecomp = (inflate_state*)pStream->zalloc( pStream->opaque, 1, sizeof( inflate_state ) );
1008                if ( !pDecomp ) return MZ_MEM_ERROR;
1009
1010                pStream->state = ( struct mz_internal_state * )pDecomp;
1011
1012                tinfl_init( &pDecomp->m_decomp );
1013                pDecomp->m_dict_ofs = 0;
1014                pDecomp->m_dict_avail = 0;
1015                pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
1016                pDecomp->m_first_call = 1;
1017                pDecomp->m_has_flushed = 0;
1018                pDecomp->m_window_bits = window_bits;
1019
1020                return MZ_OK;
1021        }
1022
1023        int mz_inflateInit( mz_streamp pStream )
1024        {
1025                return mz_inflateInit2( pStream, MZ_DEFAULT_WINDOW_BITS );
1026        }
1027
1028        int mz_inflate( mz_streamp pStream, int flush )
1029        {
1030                inflate_state* pState;
1031                mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
1032                size_t in_bytes, out_bytes, orig_avail_in;
1033                tinfl_status status;
1034
1035                if ( ( !pStream ) || ( !pStream->state ) ) return MZ_STREAM_ERROR;
1036                if ( flush == MZ_PARTIAL_FLUSH ) flush = MZ_SYNC_FLUSH;
1037                if ( ( flush ) && ( flush != MZ_SYNC_FLUSH ) && ( flush != MZ_FINISH ) ) return MZ_STREAM_ERROR;
1038
1039                pState = (inflate_state*)pStream->state;
1040                if ( pState->m_window_bits > 0 ) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
1041                orig_avail_in = pStream->avail_in;
1042
1043                first_call = pState->m_first_call; pState->m_first_call = 0;
1044                if ( pState->m_last_status < 0 ) return MZ_DATA_ERROR;
1045
1046                if ( pState->m_has_flushed && ( flush != MZ_FINISH ) ) return MZ_STREAM_ERROR;
1047                pState->m_has_flushed |= ( flush == MZ_FINISH );
1048
1049                if ( ( flush == MZ_FINISH ) && ( first_call ) )
1050                {
1051                        // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file.
1052                        decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
1053                        in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
1054                        status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags );
1055                        pState->m_last_status = status;
1056                        pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes;
1057                        pStream->adler = tinfl_get_adler32( &pState->m_decomp );
1058                        pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes;
1059
1060                        if ( status < 0 )
1061                                return MZ_DATA_ERROR;
1062                        else if ( status != TINFL_STATUS_DONE )
1063                        {
1064                                pState->m_last_status = TINFL_STATUS_FAILED;
1065                                return MZ_BUF_ERROR;
1066                        }
1067                        return MZ_STREAM_END;
1068                }
1069                // flush != MZ_FINISH then we must assume there's more input.
1070                if ( flush != MZ_FINISH ) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
1071
1072                if ( pState->m_dict_avail )
1073                {
1074                        n = MZ_MIN( pState->m_dict_avail, pStream->avail_out );
1075                        memcpy( pStream->next_out, pState->m_dict + pState->m_dict_ofs, n );
1076                        pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
1077                        pState->m_dict_avail -= n; pState->m_dict_ofs = ( pState->m_dict_ofs + n ) & ( TINFL_LZ_DICT_SIZE - 1 );
1078                        return ( ( pState->m_last_status == TINFL_STATUS_DONE ) && ( !pState->m_dict_avail ) ) ? MZ_STREAM_END : MZ_OK;
1079                }
1080
1081                for ( ; ; )
1082                {
1083                        in_bytes = pStream->avail_in;
1084                        out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
1085
1086                        status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags );
1087                        pState->m_last_status = status;
1088
1089                        pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
1090                        pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32( &pState->m_decomp );
1091
1092                        pState->m_dict_avail = (mz_uint)out_bytes;
1093
1094                        n = MZ_MIN( pState->m_dict_avail, pStream->avail_out );
1095                        memcpy( pStream->next_out, pState->m_dict + pState->m_dict_ofs, n );
1096                        pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
1097                        pState->m_dict_avail -= n; pState->m_dict_ofs = ( pState->m_dict_ofs + n ) & ( TINFL_LZ_DICT_SIZE - 1 );
1098
1099                        if ( status < 0 )
1100                                return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well).
1101                        else if ( ( status == TINFL_STATUS_NEEDS_MORE_INPUT ) && ( !orig_avail_in ) )
1102                                return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH.
1103                        else if ( flush == MZ_FINISH )
1104                        {
1105                                // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH.
1106                                if ( status == TINFL_STATUS_DONE )
1107                                        return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
1108                                // 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.
1109                                else if ( !pStream->avail_out )
1110                                        return MZ_BUF_ERROR;
1111                        }
1112                        else if ( ( status == TINFL_STATUS_DONE ) || ( !pStream->avail_in ) || ( !pStream->avail_out ) || ( pState->m_dict_avail ) )
1113                                break;
1114                }
1115
1116                return ( ( status == TINFL_STATUS_DONE ) && ( !pState->m_dict_avail ) ) ? MZ_STREAM_END : MZ_OK;
1117        }
1118
1119        int mz_inflateEnd( mz_streamp pStream )
1120        {
1121                if ( !pStream )
1122                        return MZ_STREAM_ERROR;
1123                if ( pStream->state )
1124                {
1125                        pStream->zfree( pStream->opaque, pStream->state );
1126                        pStream->state = NULL;
1127                }
1128                return MZ_OK;
1129        }
1130
1131        int mz_uncompress( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len )
1132        {
1133                mz_stream stream;
1134                int status;
1135                memset( &stream, 0, sizeof( stream ) );
1136
1137                // In case mz_ulong is 64-bits (argh I hate longs).
1138                if ( ( source_len | *pDest_len ) > 0xFFFFFFFFU ) return MZ_PARAM_ERROR;
1139
1140                stream.next_in = pSource;
1141                stream.avail_in = (mz_uint32)source_len;
1142                stream.next_out = pDest;
1143                stream.avail_out = (mz_uint32)*pDest_len;
1144
1145                status = mz_inflateInit( &stream );
1146                if ( status != MZ_OK )
1147                        return status;
1148
1149                status = mz_inflate( &stream, MZ_FINISH );
1150                if ( status != MZ_STREAM_END )
1151                {
1152                        mz_inflateEnd( &stream );
1153                        return ( ( status == MZ_BUF_ERROR ) && ( !stream.avail_in ) ) ? MZ_DATA_ERROR : status;
1154                }
1155                *pDest_len = stream.total_out;
1156
1157                return mz_inflateEnd( &stream );
1158        }
1159
1160        const char *mz_error( int err )
1161        {
1162                static struct { int m_err; const char *m_pDesc; } s_error_descs[] =
1163                {
1164                        { MZ_OK, "" },{ MZ_STREAM_END, "stream end" },{ MZ_NEED_DICT, "need dictionary" },{ MZ_ERRNO, "file error" },{ MZ_STREAM_ERROR, "stream error" },
1165                        { MZ_DATA_ERROR, "data error" },{ MZ_MEM_ERROR, "out of memory" },{ MZ_BUF_ERROR, "buf error" },{ MZ_VERSION_ERROR, "version error" },{ MZ_PARAM_ERROR, "parameter error" }
1166                };
1167                mz_uint i; for ( i = 0; i < sizeof( s_error_descs ) / sizeof( s_error_descs[0] ); ++i ) if ( s_error_descs[i].m_err == err ) return s_error_descs[i].m_pDesc;
1168                return NULL;
1169        }
1170
1171#endif //MINIZ_NO_ZLIB_APIS
1172
1173        // ------------------- Low-level Decompression (completely independent from all compression API's)
1174
1175#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
1176#define TINFL_MEMSET(p, c, l) memset(p, c, l)
1177
1178#define TINFL_CR_BEGIN switch(r->m_state) { case 0:
1179#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END
1180#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END
1181#define TINFL_CR_FINISH }
1182
1183        // 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
1184        // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.
1185#define TINFL_GET_BYTE(state_index, c) do { \
1186  if (pIn_buf_cur >= pIn_buf_end) { \
1187    for ( ; ; ) { \
1188      if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
1189        TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
1190        if (pIn_buf_cur < pIn_buf_end) { \
1191          c = *pIn_buf_cur++; \
1192          break; \
1193        } \
1194      } else { \
1195        c = 0; \
1196        break; \
1197      } \
1198    } \
1199  } else c = *pIn_buf_cur++; } MZ_MACRO_END
1200
1201#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n))
1202#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
1203#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
1204
1205        // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.
1206        // 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
1207        // 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
1208        // bit buffer contains >=15 bits (deflate's max. Huffman code size).
1209#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
1210  do { \
1211    temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
1212    if (temp >= 0) { \
1213      code_len = temp >> 9; \
1214      if ((code_len) && (num_bits >= code_len)) \
1215      break; \
1216    } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
1217       code_len = TINFL_FAST_LOOKUP_BITS; \
1218       do { \
1219          temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
1220       } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \
1221    } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \
1222  } while (num_bits < 15);
1223
1224        // 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
1225        // 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
1226        // 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.
1227        // The slow path is only executed at the very end of the input buffer.
1228#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \
1229  int temp; mz_uint code_len, c; \
1230  if (num_bits < 15) { \
1231    if ((pIn_buf_end - pIn_buf_cur) < 2) { \
1232       TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
1233    } else { \
1234       bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \
1235    } \
1236  } \
1237  if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
1238    code_len = temp >> 9, temp &= 511; \
1239  else { \
1240    code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \
1241  } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END
1242
1243        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 )
1244        {
1245                static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 };
1246                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 };
1247                static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0 };
1248                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 };
1249                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 };
1250                static const int s_min_table_sizes[3] = { 257, 1, 4 };
1251
1252                tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf;
1253                const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
1254                mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
1255                size_t out_buf_size_mask = ( decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF ) ? (size_t)-1 : ( ( pOut_buf_next - pOut_buf_start ) + *pOut_buf_size ) - 1, dist_from_out_buf_start;
1256
1257                // 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).
1258                if ( ( ( out_buf_size_mask + 1 ) & out_buf_size_mask ) || ( pOut_buf_next < pOut_buf_start ) ) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; }
1259
1260                num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start;
1261                TINFL_CR_BEGIN
1262
1263                        bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1;
1264                if ( decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER )
1265                {
1266                        TINFL_GET_BYTE( 1, r->m_zhdr0 ); TINFL_GET_BYTE( 2, r->m_zhdr1 );
1267                        counter = ( ( ( r->m_zhdr0 * 256 + r->m_zhdr1 ) % 31 != 0 ) || ( r->m_zhdr1 & 32 ) || ( ( r->m_zhdr0 & 15 ) != 8 ) );
1268                        if ( !( decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF ) ) counter |= ( ( ( 1U << ( 8U + ( r->m_zhdr0 >> 4 ) ) ) > 32768U ) || ( ( out_buf_size_mask + 1 ) < (size_t)( 1U << ( 8U + ( r->m_zhdr0 >> 4 ) ) ) ) );
1269                        if ( counter ) { TINFL_CR_RETURN_FOREVER( 36, TINFL_STATUS_FAILED ); }
1270                }
1271
1272                do
1273                {
1274                        TINFL_GET_BITS( 3, r->m_final, 3 ); r->m_type = r->m_final >> 1;
1275                        if ( r->m_type == 0 )
1276                        {
1277                                TINFL_SKIP_BITS( 5, num_bits & 7 );
1278                                for ( counter = 0; counter < 4; ++counter ) { if ( num_bits ) TINFL_GET_BITS( 6, r->m_raw_header[counter], 8 ); else TINFL_GET_BYTE( 7, r->m_raw_header[counter] ); }
1279                                if ( ( counter = ( r->m_raw_header[0] | ( r->m_raw_header[1] << 8 ) ) ) != (mz_uint)( 0xFFFF ^ ( r->m_raw_header[2] | ( r->m_raw_header[3] << 8 ) ) ) ) { TINFL_CR_RETURN_FOREVER( 39, TINFL_STATUS_FAILED ); }
1280                                while ( ( counter ) && ( num_bits ) )
1281                                {
1282                                        TINFL_GET_BITS( 51, dist, 8 );
1283                                        while ( pOut_buf_cur >= pOut_buf_end ) { TINFL_CR_RETURN( 52, TINFL_STATUS_HAS_MORE_OUTPUT ); }
1284                                        *pOut_buf_cur++ = (mz_uint8)dist;
1285                                        counter--;
1286                                }
1287                                while ( counter )
1288                                {
1289                                        size_t n; while ( pOut_buf_cur >= pOut_buf_end ) { TINFL_CR_RETURN( 9, TINFL_STATUS_HAS_MORE_OUTPUT ); }
1290                                        while ( pIn_buf_cur >= pIn_buf_end )
1291                                        {
1292                                                if ( decomp_flags & TINFL_FLAG_HAS_MORE_INPUT )
1293                                                {
1294                                                        TINFL_CR_RETURN( 38, TINFL_STATUS_NEEDS_MORE_INPUT );
1295                                                }
1296                                                else
1297                                                {
1298                                                        TINFL_CR_RETURN_FOREVER( 40, TINFL_STATUS_FAILED );
1299                                                }
1300                                        }
1301                                        n = MZ_MIN( MZ_MIN( (size_t)( pOut_buf_end - pOut_buf_cur ), (size_t)( pIn_buf_end - pIn_buf_cur ) ), counter );
1302                                        TINFL_MEMCPY( pOut_buf_cur, pIn_buf_cur, n ); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n;
1303                                }
1304                        }
1305                        else if ( r->m_type == 3 )
1306                        {
1307                                TINFL_CR_RETURN_FOREVER( 10, TINFL_STATUS_FAILED );
1308                        }
1309                        else
1310                        {
1311                                if ( r->m_type == 1 )
1312                                {
1313                                        mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i;
1314                                        r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET( r->m_tables[1].m_code_size, 5, 32 );
1315                                        for ( i = 0; i <= 143; ++i ) *p++ = 8; for ( ; i <= 255; ++i ) *p++ = 9; for ( ; i <= 279; ++i ) *p++ = 7; for ( ; i <= 287; ++i ) *p++ = 8;
1316                                }
1317                                else
1318                                {
1319                                        for ( counter = 0; counter < 3; counter++ ) { TINFL_GET_BITS( 11, r->m_table_sizes[counter], "\05\05\04"[counter] ); r->m_table_sizes[counter] += s_min_table_sizes[counter]; }
1320                                        MZ_CLEAR_OBJ( r->m_tables[2].m_code_size ); for ( counter = 0; counter < r->m_table_sizes[2]; counter++ ) { mz_uint s; TINFL_GET_BITS( 14, s, 3 ); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; }
1321                                        r->m_table_sizes[2] = 19;
1322                                }
1323                                for ( ; (int)r->m_type >= 0; r->m_type-- )
1324                                {
1325                                        int tree_next, tree_cur; tinfl_huff_table *pTable;
1326                                        mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ( total_syms ); MZ_CLEAR_OBJ( pTable->m_look_up ); MZ_CLEAR_OBJ( pTable->m_tree );
1327                                        for ( i = 0; i < r->m_table_sizes[r->m_type]; ++i ) total_syms[pTable->m_code_size[i]]++;
1328                                        used_syms = 0, total = 0; next_code[0] = next_code[1] = 0;
1329                                        for ( i = 1; i <= 15; ++i ) { used_syms += total_syms[i]; next_code[i + 1] = ( total = ( ( total + total_syms[i] ) << 1 ) ); }
1330                                        if ( ( 65536 != total ) && ( used_syms > 1 ) )
1331                                        {
1332                                                TINFL_CR_RETURN_FOREVER( 35, TINFL_STATUS_FAILED );
1333                                        }
1334                                        for ( tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index )
1335                                        {
1336                                                mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if ( !code_size ) continue;
1337                                                cur_code = next_code[code_size]++; for ( l = code_size; l > 0; l--, cur_code >>= 1 ) rev_code = ( rev_code << 1 ) | ( cur_code & 1 );
1338                                                if ( code_size <= TINFL_FAST_LOOKUP_BITS ) { mz_int16 k = (mz_int16)( ( code_size << 9 ) | sym_index ); while ( rev_code < TINFL_FAST_LOOKUP_SIZE ) { pTable->m_look_up[rev_code] = k; rev_code += ( 1 << code_size ); } continue; }
1339                                                if ( 0 == ( tree_cur = pTable->m_look_up[rev_code & ( TINFL_FAST_LOOKUP_SIZE - 1 )] ) ) { pTable->m_look_up[rev_code & ( TINFL_FAST_LOOKUP_SIZE - 1 )] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; }
1340                                                rev_code >>= ( TINFL_FAST_LOOKUP_BITS - 1 );
1341                                                for ( j = code_size; j > ( TINFL_FAST_LOOKUP_BITS + 1 ); j-- )
1342                                                {
1343                                                        tree_cur -= ( ( rev_code >>= 1 ) & 1 );
1344                                                        if ( !pTable->m_tree[-tree_cur - 1] ) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; }
1345                                                        else tree_cur = pTable->m_tree[-tree_cur - 1];
1346                                                }
1347                                                tree_cur -= ( ( rev_code >>= 1 ) & 1 ); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
1348                                        }
1349                                        if ( r->m_type == 2 )
1350                                        {
1351                                                for ( counter = 0; counter < ( r->m_table_sizes[0] + r->m_table_sizes[1] ); )
1352                                                {
1353                                                        mz_uint s; TINFL_HUFF_DECODE( 16, dist, &r->m_tables[2] ); if ( dist < 16 ) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; }
1354                                                        if ( ( dist == 16 ) && ( !counter ) )
1355                                                        {
1356                                                                TINFL_CR_RETURN_FOREVER( 17, TINFL_STATUS_FAILED );
1357                                                        }
1358                                                        num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS( 18, s, num_extra ); s += "\03\03\013"[dist - 16];
1359                                                        TINFL_MEMSET( r->m_len_codes + counter, ( dist == 16 ) ? r->m_len_codes[counter - 1] : 0, s ); counter += s;
1360                                                }
1361                                                if ( ( r->m_table_sizes[0] + r->m_table_sizes[1] ) != counter )
1362                                                {
1363                                                        TINFL_CR_RETURN_FOREVER( 21, TINFL_STATUS_FAILED );
1364                                                }
1365                                                TINFL_MEMCPY( r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0] ); TINFL_MEMCPY( r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1] );
1366                                        }
1367                                }
1368                                for ( ; ; )
1369                                {
1370                                        mz_uint8 *pSrc;
1371                                        for ( ; ; )
1372                                        {
1373                                                if ( ( ( pIn_buf_end - pIn_buf_cur ) < 4 ) || ( ( pOut_buf_end - pOut_buf_cur ) < 2 ) )
1374                                                {
1375                                                        TINFL_HUFF_DECODE( 23, counter, &r->m_tables[0] );
1376                                                        if ( counter >= 256 )
1377                                                                break;
1378                                                        while ( pOut_buf_cur >= pOut_buf_end ) { TINFL_CR_RETURN( 24, TINFL_STATUS_HAS_MORE_OUTPUT ); }
1379                                                        *pOut_buf_cur++ = (mz_uint8)counter;
1380                                                }
1381                                                else
1382                                                {
1383                                                        int sym2; mz_uint code_len;
1384#if TINFL_USE_64BIT_BITBUF
1385                                                        if ( num_bits < 30 ) { bit_buf |= ( ( (tinfl_bit_buf_t)MZ_READ_LE32( pIn_buf_cur ) ) << num_bits ); pIn_buf_cur += 4; num_bits += 32; }
1386#else
1387                                                        if ( num_bits < 15 ) { bit_buf |= ( ( (tinfl_bit_buf_t)MZ_READ_LE16( pIn_buf_cur ) ) << num_bits ); pIn_buf_cur += 2; num_bits += 16; }
1388#endif
1389                                                        if ( ( sym2 = r->m_tables[0].m_look_up[bit_buf & ( TINFL_FAST_LOOKUP_SIZE - 1 )] ) >= 0 )
1390                                                                code_len = sym2 >> 9;
1391                                                        else
1392                                                        {
1393                                                                code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ( ( bit_buf >> code_len++ ) & 1 )]; } while ( sym2 < 0 );
1394                                                        }
1395                                                        counter = sym2; bit_buf >>= code_len; num_bits -= code_len;
1396                                                        if ( counter & 256 )
1397                                                                break;
1398
1399#if !TINFL_USE_64BIT_BITBUF
1400                                                        if ( num_bits < 15 ) { bit_buf |= ( ( (tinfl_bit_buf_t)MZ_READ_LE16( pIn_buf_cur ) ) << num_bits ); pIn_buf_cur += 2; num_bits += 16; }
1401#endif
1402                                                        if ( ( sym2 = r->m_tables[0].m_look_up[bit_buf & ( TINFL_FAST_LOOKUP_SIZE - 1 )] ) >= 0 )
1403                                                                code_len = sym2 >> 9;
1404                                                        else
1405                                                        {
1406                                                                code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ( ( bit_buf >> code_len++ ) & 1 )]; } while ( sym2 < 0 );
1407                                                        }
1408                                                        bit_buf >>= code_len; num_bits -= code_len;
1409
1410                                                        pOut_buf_cur[0] = (mz_uint8)counter;
1411                                                        if ( sym2 & 256 )
1412                                                        {
1413                                                                pOut_buf_cur++;
1414                                                                counter = sym2;
1415                                                                break;
1416                                                        }
1417                                                        pOut_buf_cur[1] = (mz_uint8)sym2;
1418                                                        pOut_buf_cur += 2;
1419                                                }
1420                                        }
1421                                        if ( ( counter &= 511 ) == 256 ) break;
1422
1423                                        num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257];
1424                                        if ( num_extra ) { mz_uint extra_bits; TINFL_GET_BITS( 25, extra_bits, num_extra ); counter += extra_bits; }
1425
1426                                        TINFL_HUFF_DECODE( 26, dist, &r->m_tables[1] );
1427                                        num_extra = s_dist_extra[dist]; dist = s_dist_base[dist];
1428                                        if ( num_extra ) { mz_uint extra_bits; TINFL_GET_BITS( 27, extra_bits, num_extra ); dist += extra_bits; }
1429
1430                                        dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
1431                                        if ( ( dist > dist_from_out_buf_start ) && ( decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF ) )
1432                                        {
1433                                                TINFL_CR_RETURN_FOREVER( 37, TINFL_STATUS_FAILED );
1434                                        }
1435
1436                                        pSrc = pOut_buf_start + ( ( dist_from_out_buf_start - dist ) & out_buf_size_mask );
1437
1438                                        if ( ( MZ_MAX( pOut_buf_cur, pSrc ) + counter ) > pOut_buf_end )
1439                                        {
1440                                                while ( counter-- )
1441                                                {
1442                                                        while ( pOut_buf_cur >= pOut_buf_end ) { TINFL_CR_RETURN( 53, TINFL_STATUS_HAS_MORE_OUTPUT ); }
1443                                                        *pOut_buf_cur++ = pOut_buf_start[( dist_from_out_buf_start++ - dist ) & out_buf_size_mask];
1444                                                }
1445                                                continue;
1446                                        }
1447#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
1448                                        else if ( ( counter >= 9 ) && ( counter <= dist ) )
1449                                        {
1450                                                const mz_uint8 *pSrc_end = pSrc + ( counter & ~7 );
1451                                                do
1452                                                {
1453                                                        ( (mz_uint32 *)pOut_buf_cur )[0] = ( (const mz_uint32 *)pSrc )[0];
1454                                                        ( (mz_uint32 *)pOut_buf_cur )[1] = ( (const mz_uint32 *)pSrc )[1];
1455                                                        pOut_buf_cur += 8;
1456                                                } while ( ( pSrc += 8 ) < pSrc_end );
1457                                                if ( ( counter &= 7 ) < 3 )
1458                                                {
1459                                                        if ( counter )
1460                                                        {
1461                                                                pOut_buf_cur[0] = pSrc[0];
1462                                                                if ( counter > 1 )
1463                                                                        pOut_buf_cur[1] = pSrc[1];
1464                                                                pOut_buf_cur += counter;
1465                                                        }
1466                                                        continue;
1467                                                }
1468                                        }
1469#endif
1470                                        do
1471                                        {
1472                                                pOut_buf_cur[0] = pSrc[0];
1473                                                pOut_buf_cur[1] = pSrc[1];
1474                                                pOut_buf_cur[2] = pSrc[2];
1475                                                pOut_buf_cur += 3; pSrc += 3;
1476                                        } while ( (int)( counter -= 3 ) > 2 );
1477                                        if ( (int)counter > 0 )
1478                                        {
1479                                                pOut_buf_cur[0] = pSrc[0];
1480                                                if ( (int)counter > 1 )
1481                                                        pOut_buf_cur[1] = pSrc[1];
1482                                                pOut_buf_cur += counter;
1483                                        }
1484                                }
1485                        }
1486                } while ( !( r->m_final & 1 ) );
1487                if ( decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER )
1488                {
1489                        TINFL_SKIP_BITS( 32, num_bits & 7 ); for ( counter = 0; counter < 4; ++counter ) { mz_uint s; if ( num_bits ) TINFL_GET_BITS( 41, s, 8 ); else TINFL_GET_BYTE( 42, s ); r->m_z_adler32 = ( r->m_z_adler32 << 8 ) | s; }
1490                }
1491                TINFL_CR_RETURN_FOREVER( 34, TINFL_STATUS_DONE );
1492                TINFL_CR_FINISH
1493
1494                        common_exit :
1495                r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start;
1496                *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
1497                if ( ( decomp_flags & ( TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32 ) ) && ( status >= 0 ) )
1498                {
1499                        const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size;
1500                        mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552;
1501                        while ( buf_len )
1502                        {
1503                                for ( i = 0; i + 7 < block_len; i += 8, ptr += 8 )
1504                                {
1505                                        s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
1506                                        s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
1507                                }
1508                                for ( ; i < block_len; ++i ) s1 += *ptr++, s2 += s1;
1509                                s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
1510                        }
1511                        r->m_check_adler32 = ( s2 << 16 ) + s1; if ( ( status == TINFL_STATUS_DONE ) && ( decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER ) && ( r->m_check_adler32 != r->m_z_adler32 ) ) status = TINFL_STATUS_ADLER32_MISMATCH;
1512                }
1513                return status;
1514        }
1515
1516        // Higher level helper functions.
1517        void *tinfl_decompress_mem_to_heap( const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags )
1518        {
1519                tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0;
1520                *pOut_len = 0;
1521                tinfl_init( &decomp );
1522                for ( ; ; )
1523                {
1524                        size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
1525                        tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size,
1526                                ( flags & ~TINFL_FLAG_HAS_MORE_INPUT ) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF );
1527                        if ( ( status < 0 ) || ( status == TINFL_STATUS_NEEDS_MORE_INPUT ) )
1528                        {
1529                                MZ_FREE( pBuf ); *pOut_len = 0; return NULL;
1530                        }
1531                        src_buf_ofs += src_buf_size;
1532                        *pOut_len += dst_buf_size;
1533                        if ( status == TINFL_STATUS_DONE ) break;
1534                        new_out_buf_capacity = out_buf_capacity * 2; if ( new_out_buf_capacity < 128 ) new_out_buf_capacity = 128;
1535                        pNew_buf = MZ_REALLOC( pBuf, new_out_buf_capacity );
1536                        if ( !pNew_buf )
1537                        {
1538                                MZ_FREE( pBuf ); *pOut_len = 0; return NULL;
1539                        }
1540                        pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity;
1541                }
1542                return pBuf;
1543        }
1544
1545        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 )
1546        {
1547                tinfl_decompressor decomp; tinfl_status status; tinfl_init( &decomp );
1548                status = tinfl_decompress( &decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, ( flags & ~TINFL_FLAG_HAS_MORE_INPUT ) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF );
1549                return ( status != TINFL_STATUS_DONE ) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
1550        }
1551
1552        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 )
1553        {
1554                int result = 0;
1555                tinfl_decompressor decomp;
1556                mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC( TINFL_LZ_DICT_SIZE ); size_t in_buf_ofs = 0, dict_ofs = 0;
1557                if ( !pDict )
1558                        return TINFL_STATUS_FAILED;
1559                tinfl_init( &decomp );
1560                for ( ; ; )
1561                {
1562                        size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
1563                        tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
1564                                ( flags & ~( TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF ) ) );
1565                        in_buf_ofs += in_buf_size;
1566                        if ( ( dst_buf_size ) && ( !( *pPut_buf_func )( pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user ) ) )
1567                                break;
1568                        if ( status != TINFL_STATUS_HAS_MORE_OUTPUT )
1569                        {
1570                                result = ( status == TINFL_STATUS_DONE );
1571                                break;
1572                        }
1573                        dict_ofs = ( dict_ofs + dst_buf_size ) & ( TINFL_LZ_DICT_SIZE - 1 );
1574                }
1575                MZ_FREE( pDict );
1576                *pIn_buf_size = in_buf_ofs;
1577                return result;
1578        }
1579
1580        // ------------------- Low-level Compression (independent from all decompression API's)
1581
1582        // Purposely making these tables static for faster init and thread safety.
1583        static const mz_uint16 s_tdefl_len_sym[256] = {
1584                257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272,
1585                273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276,
1586                277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,
1587                279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,
1588                281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,
1589                282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,
1590                283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,
1591                284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 };
1592
1593        static const mz_uint8 s_tdefl_len_extra[256] = {
1594                0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
1595                4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
1596                5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
1597                5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 };
1598
1599        static const mz_uint8 s_tdefl_small_dist_sym[512] = {
1600                0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
1601                11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
1602                13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,
1603                14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
1604                14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
1605                15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,
1606                16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1607                16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1608                16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
1609                17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
1610                17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
1611                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 };
1612
1613        static const mz_uint8 s_tdefl_small_dist_extra[512] = {
1614                0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,
1615                5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1616                6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1617                6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1618                7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1619                7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1620                7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1621                7,7,7,7,7,7,7,7 };
1622
1623        static const mz_uint8 s_tdefl_large_dist_sym[128] = {
1624                0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,
1625                26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,
1626                28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 };
1627
1628        static const mz_uint8 s_tdefl_large_dist_extra[128] = {
1629                0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
1630                12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
1631                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 };
1632
1633        // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values.
1634        typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
1635        static tdefl_sym_freq* tdefl_radix_sort_syms( mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1 )
1636        {
1637                mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ( hist );
1638                for ( i = 0; i < num_syms; i++ ) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ( ( freq >> 8 ) & 0xFF )]++; }
1639                while ( ( total_passes > 1 ) && ( num_syms == hist[( total_passes - 1 ) * 256] ) ) total_passes--;
1640                for ( pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8 )
1641                {
1642                        const mz_uint32* pHist = &hist[pass << 8];
1643                        mz_uint offsets[256], cur_ofs = 0;
1644                        for ( i = 0; i < 256; i++ ) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }
1645                        for ( i = 0; i < num_syms; i++ ) pNew_syms[offsets[( pCur_syms[i].m_key >> pass_shift ) & 0xFF]++] = pCur_syms[i];
1646                        { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; }
1647                }
1648                return pCur_syms;
1649        }
1650
1651        // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
1652        static void tdefl_calculate_minimum_redundancy( tdefl_sym_freq *A, int n )
1653        {
1654                int root, leaf, next, avbl, used, dpth;
1655                if ( n == 0 ) return; else if ( n == 1 ) { A[0].m_key = 1; return; }
1656                A[0].m_key += A[1].m_key; root = 0; leaf = 2;
1657                for ( next = 1; next < n - 1; next++ )
1658                {
1659                        if ( leaf >= n || A[root].m_key < A[leaf].m_key ) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; }
1660                        else A[next].m_key = A[leaf++].m_key;
1661                        if ( leaf >= n || ( root < next && A[root].m_key < A[leaf].m_key ) ) { A[next].m_key = (mz_uint16)( A[next].m_key + A[root].m_key ); A[root++].m_key = (mz_uint16)next; }
1662                        else A[next].m_key = (mz_uint16)( A[next].m_key + A[leaf++].m_key );
1663                }
1664                A[n - 2].m_key = 0; for ( next = n - 3; next >= 0; next-- ) A[next].m_key = A[A[next].m_key].m_key + 1;
1665                avbl = 1; used = dpth = 0; root = n - 2; next = n - 1;
1666                while ( avbl > 0 )
1667                {
1668                        while ( root >= 0 && (int)A[root].m_key == dpth ) { used++; root--; }
1669                        while ( avbl > used ) { A[next--].m_key = (mz_uint16)( dpth ); avbl--; }
1670                        avbl = 2 * used; dpth++; used = 0;
1671                }
1672        }
1673
1674        // Limits canonical Huffman code table's max code size.
1675        enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
1676        static void tdefl_huffman_enforce_max_code_size( int *pNum_codes, int code_list_len, int max_code_size )
1677        {
1678                int i; mz_uint32 total = 0; if ( code_list_len <= 1 ) return;
1679                for ( i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++ ) pNum_codes[max_code_size] += pNum_codes[i];
1680                for ( i = max_code_size; i > 0; i-- ) total += ( ( (mz_uint32)pNum_codes[i] ) << ( max_code_size - i ) );
1681                while ( total != ( 1UL << max_code_size ) )
1682                {
1683                        pNum_codes[max_code_size]--;
1684                        for ( i = max_code_size - 1; i > 0; i-- ) if ( pNum_codes[i] ) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }
1685                        total--;
1686                }
1687        }
1688
1689        static void tdefl_optimize_huffman_table( tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table )
1690        {
1691                int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ( num_codes );
1692                if ( static_table )
1693                {
1694                        for ( i = 0; i < table_len; i++ ) num_codes[d->m_huff_code_sizes[table_num][i]]++;
1695                }
1696                else
1697                {
1698                        tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;
1699                        int num_used_syms = 0;
1700                        const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
1701                        for ( i = 0; i < table_len; i++ ) if ( pSym_count[i] ) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; }
1702
1703                        pSyms = tdefl_radix_sort_syms( num_used_syms, syms0, syms1 ); tdefl_calculate_minimum_redundancy( pSyms, num_used_syms );
1704
1705                        for ( i = 0; i < num_used_syms; i++ ) num_codes[pSyms[i].m_key]++;
1706
1707                        tdefl_huffman_enforce_max_code_size( num_codes, num_used_syms, code_size_limit );
1708
1709                        MZ_CLEAR_OBJ( d->m_huff_code_sizes[table_num] ); MZ_CLEAR_OBJ( d->m_huff_codes[table_num] );
1710                        for ( i = 1, j = num_used_syms; i <= code_size_limit; i++ )
1711                                for ( l = num_codes[i]; l > 0; l-- ) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)( i );
1712                }
1713
1714                next_code[1] = 0; for ( j = 0, i = 2; i <= code_size_limit; i++ ) next_code[i] = j = ( ( j + num_codes[i - 1] ) << 1 );
1715
1716                for ( i = 0; i < table_len; i++ )
1717                {
1718                        mz_uint rev_code = 0, code, code_size; if ( ( code_size = d->m_huff_code_sizes[table_num][i] ) == 0 ) continue;
1719                        code = next_code[code_size]++; for ( l = code_size; l > 0; l--, code >>= 1 ) rev_code = ( rev_code << 1 ) | ( code & 1 );
1720                        d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
1721                }
1722        }
1723
1724#define TDEFL_PUT_BITS(b, l) do { \
1725  mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \
1726  d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \
1727  while (d->m_bits_in >= 8) { \
1728    if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
1729      *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
1730      d->m_bit_buffer >>= 8; \
1731      d->m_bits_in -= 8; \
1732  } \
1733} MZ_MACRO_END
1734
1735#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \
1736  if (rle_repeat_count < 3) { \
1737    d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
1738    while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
1739  } else { \
1740    d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \
1741} rle_repeat_count = 0; } }
1742
1743#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \
1744  if (rle_z_count < 3) { \
1745    d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
1746  } else if (rle_z_count <= 10) { \
1747    d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \
1748  } else { \
1749    d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \
1750} rle_z_count = 0; } }
1751
1752        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 };
1753
1754        static void tdefl_start_dynamic_block( tdefl_compressor *d )
1755        {
1756                int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index;
1757                mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF;
1758
1759                d->m_huff_count[0][256] = 1;
1760
1761                tdefl_optimize_huffman_table( d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE );
1762                tdefl_optimize_huffman_table( d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE );
1763
1764                for ( num_lit_codes = 286; num_lit_codes > 257; num_lit_codes-- ) if ( d->m_huff_code_sizes[0][num_lit_codes - 1] ) break;
1765                for ( num_dist_codes = 30; num_dist_codes > 1; num_dist_codes-- ) if ( d->m_huff_code_sizes[1][num_dist_codes - 1] ) break;
1766
1767                memcpy( code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes );
1768                memcpy( code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes );
1769                total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0;
1770
1771                memset( &d->m_huff_count[2][0], 0, sizeof( d->m_huff_count[2][0] ) * TDEFL_MAX_HUFF_SYMBOLS_2 );
1772                for ( i = 0; i < total_code_sizes_to_pack; i++ )
1773                {
1774                        mz_uint8 code_size = code_sizes_to_pack[i];
1775                        if ( !code_size )
1776                        {
1777                                TDEFL_RLE_PREV_CODE_SIZE();
1778                                if ( ++rle_z_count == 138 ) { TDEFL_RLE_ZERO_CODE_SIZE(); }
1779                        }
1780                        else
1781                        {
1782                                TDEFL_RLE_ZERO_CODE_SIZE();
1783                                if ( code_size != prev_code_size )
1784                                {
1785                                        TDEFL_RLE_PREV_CODE_SIZE();
1786                                        d->m_huff_count[2][code_size] = (mz_uint16)( d->m_huff_count[2][code_size] + 1 ); packed_code_sizes[num_packed_code_sizes++] = code_size;
1787                                }
1788                                else if ( ++rle_repeat_count == 6 )
1789                                {
1790                                        TDEFL_RLE_PREV_CODE_SIZE();
1791                                }
1792                        }
1793                        prev_code_size = code_size;
1794                }
1795                if ( rle_repeat_count ) { TDEFL_RLE_PREV_CODE_SIZE(); }
1796                else { TDEFL_RLE_ZERO_CODE_SIZE(); }
1797
1798                tdefl_optimize_huffman_table( d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE );
1799
1800                TDEFL_PUT_BITS( 2, 2 );
1801
1802                TDEFL_PUT_BITS( num_lit_codes - 257, 5 );
1803                TDEFL_PUT_BITS( num_dist_codes - 1, 5 );
1804
1805                for ( num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths-- ) if ( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]] ) break;
1806                num_bit_lengths = MZ_MAX( 4, ( num_bit_lengths + 1 ) ); TDEFL_PUT_BITS( num_bit_lengths - 4, 4 );
1807                for ( i = 0; (int)i < num_bit_lengths; i++ ) TDEFL_PUT_BITS( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3 );
1808
1809                for ( packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; )
1810                {
1811                        mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT( code < TDEFL_MAX_HUFF_SYMBOLS_2 );
1812                        TDEFL_PUT_BITS( d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code] );
1813                        if ( code >= 16 ) TDEFL_PUT_BITS( packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16] );
1814                }
1815        }
1816
1817        static void tdefl_start_static_block( tdefl_compressor *d )
1818        {
1819                mz_uint i;
1820                mz_uint8 *p = &d->m_huff_code_sizes[0][0];
1821
1822                for ( i = 0; i <= 143; ++i ) *p++ = 8;
1823                for ( ; i <= 255; ++i ) *p++ = 9;
1824                for ( ; i <= 279; ++i ) *p++ = 7;
1825                for ( ; i <= 287; ++i ) *p++ = 8;
1826
1827                memset( d->m_huff_code_sizes[1], 5, 32 );
1828
1829                tdefl_optimize_huffman_table( d, 0, 288, 15, MZ_TRUE );
1830                tdefl_optimize_huffman_table( d, 1, 32, 15, MZ_TRUE );
1831
1832                TDEFL_PUT_BITS( 1, 2 );
1833        }
1834
1835        static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
1836
1837#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
1838        static mz_bool tdefl_compress_lz_codes( tdefl_compressor *d )
1839        {
1840                mz_uint flags;
1841                mz_uint8 *pLZ_codes;
1842                mz_uint8 *pOutput_buf = d->m_pOutput_buf;
1843                mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
1844                mz_uint64 bit_buffer = d->m_bit_buffer;
1845                mz_uint bits_in = d->m_bits_in;
1846
1847#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); }
1848
1849                flags = 1;
1850                for ( pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1 )
1851                {
1852                        if ( flags == 1 )
1853                                flags = *pLZ_codes++ | 0x100;
1854
1855                        if ( flags & 1 )
1856                        {
1857                                mz_uint s0, s1, n0, n1, sym, num_extra_bits;
1858                                mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)( pLZ_codes + 1 ); pLZ_codes += 3;
1859
1860                                MZ_ASSERT( d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]] );
1861                                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]] );
1862                                TDEFL_PUT_BITS_FAST( match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len] );
1863
1864                                // This sequence coaxes MSVC into using cmov's vs. jmp's.
1865                                s0 = s_tdefl_small_dist_sym[match_dist & 511];
1866                                n0 = s_tdefl_small_dist_extra[match_dist & 511];
1867                                s1 = s_tdefl_large_dist_sym[match_dist >> 8];
1868                                n1 = s_tdefl_large_dist_extra[match_dist >> 8];
1869                                sym = ( match_dist < 512 ) ? s0 : s1;
1870                                num_extra_bits = ( match_dist < 512 ) ? n0 : n1;
1871
1872                                MZ_ASSERT( d->m_huff_code_sizes[1][sym] );
1873                                TDEFL_PUT_BITS_FAST( d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym] );
1874                                TDEFL_PUT_BITS_FAST( match_dist & mz_bitmasks[num_extra_bits], num_extra_bits );
1875                        }
1876                        else
1877                        {
1878                                mz_uint lit = *pLZ_codes++;
1879                                MZ_ASSERT( d->m_huff_code_sizes[0][lit] );
1880                                TDEFL_PUT_BITS_FAST( d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit] );
1881
1882                                if ( ( ( flags & 2 ) == 0 ) && ( pLZ_codes < pLZ_code_buf_end ) )
1883                                {
1884                                        flags >>= 1;
1885                                        lit = *pLZ_codes++;
1886                                        MZ_ASSERT( d->m_huff_code_sizes[0][lit] );
1887                                        TDEFL_PUT_BITS_FAST( d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit] );
1888
1889                                        if ( ( ( flags & 2 ) == 0 ) && ( pLZ_codes < pLZ_code_buf_end ) )
1890                                        {
1891                                                flags >>= 1;
1892                                                lit = *pLZ_codes++;
1893                                                MZ_ASSERT( d->m_huff_code_sizes[0][lit] );
1894                                                TDEFL_PUT_BITS_FAST( d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit] );
1895                                        }
1896                                }
1897                        }
1898
1899                        if ( pOutput_buf >= d->m_pOutput_buf_end )
1900                                return MZ_FALSE;
1901
1902                        *(mz_uint64*)pOutput_buf = bit_buffer;
1903                        pOutput_buf += ( bits_in >> 3 );
1904                        bit_buffer >>= ( bits_in & ~7 );
1905                        bits_in &= 7;
1906                }
1907
1908#undef TDEFL_PUT_BITS_FAST
1909
1910                d->m_pOutput_buf = pOutput_buf;
1911                d->m_bits_in = 0;
1912                d->m_bit_buffer = 0;
1913
1914                while ( bits_in )
1915                {
1916                        mz_uint32 n = MZ_MIN( bits_in, 16 );
1917                        TDEFL_PUT_BITS( (mz_uint)bit_buffer & mz_bitmasks[n], n );
1918                        bit_buffer >>= n;
1919                        bits_in -= n;
1920                }
1921
1922                TDEFL_PUT_BITS( d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256] );
1923
1924                return ( d->m_pOutput_buf < d->m_pOutput_buf_end );
1925        }
1926#else
1927        static mz_bool tdefl_compress_lz_codes( tdefl_compressor *d )
1928        {
1929                mz_uint flags;
1930                mz_uint8 *pLZ_codes;
1931
1932                flags = 1;
1933                for ( pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1 )
1934                {
1935                        if ( flags == 1 )
1936                                flags = *pLZ_codes++ | 0x100;
1937                        if ( flags & 1 )
1938                        {
1939                                mz_uint sym, num_extra_bits;
1940                                mz_uint match_len = pLZ_codes[0], match_dist = ( pLZ_codes[1] | ( pLZ_codes[2] << 8 ) ); pLZ_codes += 3;
1941
1942                                MZ_ASSERT( d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]] );
1943                                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]] );
1944                                TDEFL_PUT_BITS( match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len] );
1945
1946                                if ( match_dist < 512 )
1947                                {
1948                                        sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist];
1949                                }
1950                                else
1951                                {
1952                                        sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
1953                                }
1954                                MZ_ASSERT( d->m_huff_code_sizes[1][sym] );
1955                                TDEFL_PUT_BITS( d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym] );
1956                                TDEFL_PUT_BITS( match_dist & mz_bitmasks[num_extra_bits], num_extra_bits );
1957                        }
1958                        else
1959                        {
1960                                mz_uint lit = *pLZ_codes++;
1961                                MZ_ASSERT( d->m_huff_code_sizes[0][lit] );
1962                                TDEFL_PUT_BITS( d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit] );
1963                        }
1964                }
1965
1966                TDEFL_PUT_BITS( d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256] );
1967
1968                return ( d->m_pOutput_buf < d->m_pOutput_buf_end );
1969        }
1970#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
1971
1972        static mz_bool tdefl_compress_block( tdefl_compressor *d, mz_bool static_block )
1973        {
1974                if ( static_block )
1975                        tdefl_start_static_block( d );
1976                else
1977                        tdefl_start_dynamic_block( d );
1978                return tdefl_compress_lz_codes( d );
1979        }
1980
1981        static int tdefl_flush_block( tdefl_compressor *d, int flush )
1982        {
1983                mz_uint saved_bit_buf, saved_bits_in;
1984                mz_uint8 *pSaved_output_buf;
1985                mz_bool comp_block_succeeded = MZ_FALSE;
1986                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;
1987                mz_uint8 *pOutput_buf_start = ( ( d->m_pPut_buf_func == NULL ) && ( ( *d->m_pOut_buf_size - d->m_out_buf_ofs ) >= TDEFL_OUT_BUF_SIZE ) ) ? ( (mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs ) : d->m_output_buf;
1988
1989                d->m_pOutput_buf = pOutput_buf_start;
1990                d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
1991
1992                MZ_ASSERT( !d->m_output_flush_remaining );
1993                d->m_output_flush_ofs = 0;
1994                d->m_output_flush_remaining = 0;
1995
1996                *d->m_pLZ_flags = (mz_uint8)( *d->m_pLZ_flags >> d->m_num_flags_left );
1997                d->m_pLZ_code_buf -= ( d->m_num_flags_left == 8 );
1998
1999                if ( ( d->m_flags & TDEFL_WRITE_ZLIB_HEADER ) && ( !d->m_block_index ) )
2000                {
2001                        TDEFL_PUT_BITS( 0x78, 8 ); TDEFL_PUT_BITS( 0x01, 8 );
2002                }
2003
2004                TDEFL_PUT_BITS( flush == TDEFL_FINISH, 1 );
2005
2006                pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in;
2007
2008                if ( !use_raw_block )
2009                        comp_block_succeeded = tdefl_compress_block( d, ( d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS ) || ( d->m_total_lz_bytes < 48 ) );
2010
2011                // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead.
2012                if ( ( ( use_raw_block ) || ( ( d->m_total_lz_bytes ) && ( ( d->m_pOutput_buf - pSaved_output_buf + 1U ) >= d->m_total_lz_bytes ) ) ) &&
2013                        ( ( d->m_lookahead_pos - d->m_lz_code_buf_dict_pos ) <= d->m_dict_size ) )
2014                {
2015                        mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
2016                        TDEFL_PUT_BITS( 0, 2 );
2017                        if ( d->m_bits_in ) { TDEFL_PUT_BITS( 0, 8 - d->m_bits_in ); }
2018                        for ( i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF )
2019                        {
2020                                TDEFL_PUT_BITS( d->m_total_lz_bytes & 0xFFFF, 16 );
2021                        }
2022                        for ( i = 0; i < d->m_total_lz_bytes; ++i )
2023                        {
2024                                TDEFL_PUT_BITS( d->m_dict[( d->m_lz_code_buf_dict_pos + i ) & TDEFL_LZ_DICT_SIZE_MASK], 8 );
2025                        }
2026                }
2027                // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes.
2028                else if ( !comp_block_succeeded )
2029                {
2030                        d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
2031                        tdefl_compress_block( d, MZ_TRUE );
2032                }
2033
2034                if ( flush )
2035                {
2036                        if ( flush == TDEFL_FINISH )
2037                        {
2038                                if ( d->m_bits_in ) { TDEFL_PUT_BITS( 0, 8 - d->m_bits_in ); }
2039                                if ( d->m_flags & TDEFL_WRITE_ZLIB_HEADER ) { mz_uint i, a = d->m_adler32; for ( i = 0; i < 4; i++ ) { TDEFL_PUT_BITS( ( a >> 24 ) & 0xFF, 8 ); a <<= 8; } }
2040                        }
2041                        else
2042                        {
2043                                mz_uint i, z = 0; TDEFL_PUT_BITS( 0, 3 ); if ( d->m_bits_in ) { TDEFL_PUT_BITS( 0, 8 - d->m_bits_in ); } for ( i = 2; i; --i, z ^= 0xFFFF ) { TDEFL_PUT_BITS( z & 0xFFFF, 16 ); }
2044                        }
2045                }
2046
2047                MZ_ASSERT( d->m_pOutput_buf < d->m_pOutput_buf_end );
2048
2049                memset( &d->m_huff_count[0][0], 0, sizeof( d->m_huff_count[0][0] ) * TDEFL_MAX_HUFF_SYMBOLS_0 );
2050                memset( &d->m_huff_count[1][0], 0, sizeof( d->m_huff_count[1][0] ) * TDEFL_MAX_HUFF_SYMBOLS_1 );
2051
2052                d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++;
2053
2054                if ( ( n = (int)( d->m_pOutput_buf - pOutput_buf_start ) ) != 0 )
2055                {
2056                        if ( d->m_pPut_buf_func )
2057                        {
2058                                *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
2059                                if ( !( *d->m_pPut_buf_func )( d->m_output_buf, n, d->m_pPut_buf_user ) )
2060                                        return ( d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED );
2061                        }
2062                        else if ( pOutput_buf_start == d->m_output_buf )
2063                        {
2064                                int bytes_to_copy = (int)MZ_MIN( (size_t)n, (size_t)( *d->m_pOut_buf_size - d->m_out_buf_ofs ) );
2065                                memcpy( (mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy );
2066                                d->m_out_buf_ofs += bytes_to_copy;
2067                                if ( ( n -= bytes_to_copy ) != 0 )
2068                                {
2069                                        d->m_output_flush_ofs = bytes_to_copy;
2070                                        d->m_output_flush_remaining = n;
2071                                }
2072                        }
2073                        else
2074                        {
2075                                d->m_out_buf_ofs += n;
2076                        }
2077                }
2078
2079                return d->m_output_flush_remaining;
2080        }
2081
2082#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
2083#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p)
2084        static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len )
2085        {
2086                mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
2087                mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
2088                const mz_uint16 *s = (const mz_uint16*)( d->m_dict + pos ), *p, *q;
2089                mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD( &d->m_dict[pos + match_len - 1] ), s01 = TDEFL_READ_UNALIGNED_WORD( s );
2090                MZ_ASSERT( max_match_len <= TDEFL_MAX_MATCH_LEN ); if ( max_match_len <= match_len ) return;
2091                for ( ; ; )
2092                {
2093                        for ( ; ; )
2094                        {
2095                                if ( --num_probes_left == 0 ) return;
2096#define TDEFL_PROBE \
2097        next_probe_pos = d->m_next[probe_pos]; \
2098        if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
2099        probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
2100        if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break;
2101                                TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
2102                        }
2103                        if ( !dist ) break; q = (const mz_uint16*)( d->m_dict + probe_pos ); if ( TDEFL_READ_UNALIGNED_WORD( q ) != s01 ) continue; p = s; probe_len = 32;
2104                        do {} while ( ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) &&
2105                                ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( --probe_len > 0 ) );
2106                        if ( !probe_len )
2107                        {
2108                                *pMatch_dist = dist; *pMatch_len = MZ_MIN( max_match_len, TDEFL_MAX_MATCH_LEN ); break;
2109                        }
2110                        else if ( ( probe_len = ( (mz_uint)( p - s ) * 2 ) + (mz_uint)( *(const mz_uint8*)p == *(const mz_uint8*)q ) ) > match_len )
2111                        {
2112                                *pMatch_dist = dist; if ( ( *pMatch_len = match_len = MZ_MIN( max_match_len, probe_len ) ) == max_match_len ) break;
2113                                c01 = TDEFL_READ_UNALIGNED_WORD( &d->m_dict[pos + match_len - 1] );
2114                        }
2115                }
2116        }
2117#else
2118        static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len )
2119        {
2120                mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
2121                mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
2122                const mz_uint8 *s = d->m_dict + pos, *p, *q;
2123                mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
2124                MZ_ASSERT( max_match_len <= TDEFL_MAX_MATCH_LEN ); if ( max_match_len <= match_len ) return;
2125                for ( ; ; )
2126                {
2127                        for ( ; ; )
2128                        {
2129                                if ( --num_probes_left == 0 ) return;
2130#define TDEFL_PROBE \
2131        next_probe_pos = d->m_next[probe_pos]; \
2132        if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
2133        probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
2134        if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break;
2135                                TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
2136                        }
2137                        if ( !dist ) break; p = s; q = d->m_dict + probe_pos; for ( probe_len = 0; probe_len < max_match_len; probe_len++ ) if ( *p++ != *q++ ) break;
2138                        if ( probe_len > match_len )
2139                        {
2140                                *pMatch_dist = dist; if ( ( *pMatch_len = match_len = probe_len ) == max_match_len ) return;
2141                                c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1];
2142                        }
2143                }
2144        }
2145#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
2146
2147#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
2148        static mz_bool tdefl_compress_fast( tdefl_compressor *d )
2149        {
2150                // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio.
2151                mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left;
2152                mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
2153                mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
2154
2155                while ( ( d->m_src_buf_left ) || ( ( d->m_flush ) && ( lookahead_size ) ) )
2156                {
2157                        const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
2158                        mz_uint dst_pos = ( lookahead_pos + lookahead_size ) & TDEFL_LZ_DICT_SIZE_MASK;
2159                        mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size );
2160                        d->m_src_buf_left -= num_bytes_to_process;
2161                        lookahead_size += num_bytes_to_process;
2162
2163                        while ( num_bytes_to_process )
2164                        {
2165                                mz_uint32 n = MZ_MIN( TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process );
2166                                memcpy( d->m_dict + dst_pos, d->m_pSrc, n );
2167                                if ( dst_pos < ( TDEFL_MAX_MATCH_LEN - 1 ) )
2168                                        memcpy( d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN( n, ( TDEFL_MAX_MATCH_LEN - 1 ) - dst_pos ) );
2169                                d->m_pSrc += n;
2170                                dst_pos = ( dst_pos + n ) & TDEFL_LZ_DICT_SIZE_MASK;
2171                                num_bytes_to_process -= n;
2172                        }
2173
2174                        dict_size = MZ_MIN( TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size );
2175                        if ( ( !d->m_flush ) && ( lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE ) ) break;
2176
2177                        while ( lookahead_size >= 4 )
2178                        {
2179                                mz_uint cur_match_dist, cur_match_len = 1;
2180                                mz_uint8 *pCur_dict = d->m_dict + cur_pos;
2181                                mz_uint first_trigram = ( *(const mz_uint32 *)pCur_dict ) & 0xFFFFFF;
2182                                mz_uint hash = ( first_trigram ^ ( first_trigram >> ( 24 - ( TDEFL_LZ_HASH_BITS - 8 ) ) ) ) & TDEFL_LEVEL1_HASH_SIZE_MASK;
2183                                mz_uint probe_pos = d->m_hash[hash];
2184                                d->m_hash[hash] = (mz_uint16)lookahead_pos;
2185
2186                                if ( ( ( cur_match_dist = (mz_uint16)( lookahead_pos - probe_pos ) ) <= dict_size ) && ( ( *(const mz_uint32 *)( d->m_dict + ( probe_pos &= TDEFL_LZ_DICT_SIZE_MASK ) ) & 0xFFFFFF ) == first_trigram ) )
2187                                {
2188                                        const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
2189                                        const mz_uint16 *q = (const mz_uint16 *)( d->m_dict + probe_pos );
2190                                        mz_uint32 probe_len = 32;
2191                                        do {} while ( ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) &&
2192                                                ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( --probe_len > 0 ) );
2193                                        cur_match_len = ( (mz_uint)( p - (const mz_uint16 *)pCur_dict ) * 2 ) + (mz_uint)( *(const mz_uint8 *)p == *(const mz_uint8 *)q );
2194                                        if ( !probe_len )
2195                                                cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
2196
2197                                        if ( ( cur_match_len < TDEFL_MIN_MATCH_LEN ) || ( ( cur_match_len == TDEFL_MIN_MATCH_LEN ) && ( cur_match_dist >= 8U * 1024U ) ) )
2198                                        {
2199                                                cur_match_len = 1;
2200                                                *pLZ_code_buf++ = (mz_uint8)first_trigram;
2201                                                *pLZ_flags = (mz_uint8)( *pLZ_flags >> 1 );
2202                                                d->m_huff_count[0][(mz_uint8)first_trigram]++;
2203                                        }
2204                                        else
2205                                        {
2206                                                mz_uint32 s0, s1;
2207                                                cur_match_len = MZ_MIN( cur_match_len, lookahead_size );
2208
2209                                                MZ_ASSERT( ( cur_match_len >= TDEFL_MIN_MATCH_LEN ) && ( cur_match_dist >= 1 ) && ( cur_match_dist <= TDEFL_LZ_DICT_SIZE ) );
2210
2211                                                cur_match_dist--;
2212
2213                                                pLZ_code_buf[0] = (mz_uint8)( cur_match_len - TDEFL_MIN_MATCH_LEN );
2214                                                *(mz_uint16 *)( &pLZ_code_buf[1] ) = (mz_uint16)cur_match_dist;
2215                                                pLZ_code_buf += 3;
2216                                                *pLZ_flags = (mz_uint8)( ( *pLZ_flags >> 1 ) | 0x80 );
2217
2218                                                s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
2219                                                s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
2220                                                d->m_huff_count[1][( cur_match_dist < 512 ) ? s0 : s1]++;
2221
2222                                                d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++;
2223                                        }
2224                                }
2225                                else
2226                                {
2227                                        *pLZ_code_buf++ = (mz_uint8)first_trigram;
2228                                        *pLZ_flags = (mz_uint8)( *pLZ_flags >> 1 );
2229                                        d->m_huff_count[0][(mz_uint8)first_trigram]++;
2230                                }
2231
2232                                if ( --num_flags_left == 0 ) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
2233
2234                                total_lz_bytes += cur_match_len;
2235                                lookahead_pos += cur_match_len;
2236                                dict_size = MZ_MIN( dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE );
2237                                cur_pos = ( cur_pos + cur_match_len ) & TDEFL_LZ_DICT_SIZE_MASK;
2238                                MZ_ASSERT( lookahead_size >= cur_match_len );
2239                                lookahead_size -= cur_match_len;
2240
2241                                if ( pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8] )
2242                                {
2243                                        int n;
2244                                        d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
2245                                        d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
2246                                        if ( ( n = tdefl_flush_block( d, 0 ) ) != 0 )
2247                                                return ( n < 0 ) ? MZ_FALSE : MZ_TRUE;
2248                                        total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
2249                                }
2250                        }
2251
2252                        while ( lookahead_size )
2253                        {
2254                                mz_uint8 lit = d->m_dict[cur_pos];
2255
2256                                total_lz_bytes++;
2257                                *pLZ_code_buf++ = lit;
2258                                *pLZ_flags = (mz_uint8)( *pLZ_flags >> 1 );
2259                                if ( --num_flags_left == 0 ) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
2260
2261                                d->m_huff_count[0][lit]++;
2262
2263                                lookahead_pos++;
2264                                dict_size = MZ_MIN( dict_size + 1, TDEFL_LZ_DICT_SIZE );
2265                                cur_pos = ( cur_pos + 1 ) & TDEFL_LZ_DICT_SIZE_MASK;
2266                                lookahead_size--;
2267
2268                                if ( pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8] )
2269                                {
2270                                        int n;
2271                                        d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
2272                                        d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
2273                                        if ( ( n = tdefl_flush_block( d, 0 ) ) != 0 )
2274                                                return ( n < 0 ) ? MZ_FALSE : MZ_TRUE;
2275                                        total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
2276                                }
2277                        }
2278                }
2279
2280                d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
2281                d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
2282                return MZ_TRUE;
2283        }
2284#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
2285
2286        static MZ_FORCEINLINE void tdefl_record_literal( tdefl_compressor *d, mz_uint8 lit )
2287        {
2288                d->m_total_lz_bytes++;
2289                *d->m_pLZ_code_buf++ = lit;
2290                *d->m_pLZ_flags = (mz_uint8)( *d->m_pLZ_flags >> 1 ); if ( --d->m_num_flags_left == 0 ) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
2291                d->m_huff_count[0][lit]++;
2292        }
2293
2294        static MZ_FORCEINLINE void tdefl_record_match( tdefl_compressor *d, mz_uint match_len, mz_uint match_dist )
2295        {
2296                mz_uint32 s0, s1;
2297
2298                MZ_ASSERT( ( match_len >= TDEFL_MIN_MATCH_LEN ) && ( match_dist >= 1 ) && ( match_dist <= TDEFL_LZ_DICT_SIZE ) );
2299
2300                d->m_total_lz_bytes += match_len;
2301
2302                d->m_pLZ_code_buf[0] = (mz_uint8)( match_len - TDEFL_MIN_MATCH_LEN );
2303
2304                match_dist -= 1;
2305                d->m_pLZ_code_buf[1] = (mz_uint8)( match_dist & 0xFF );
2306                d->m_pLZ_code_buf[2] = (mz_uint8)( match_dist >> 8 ); d->m_pLZ_code_buf += 3;
2307
2308                *d->m_pLZ_flags = (mz_uint8)( ( *d->m_pLZ_flags >> 1 ) | 0x80 ); if ( --d->m_num_flags_left == 0 ) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
2309
2310                s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[( match_dist >> 8 ) & 127];
2311                d->m_huff_count[1][( match_dist < 512 ) ? s0 : s1]++;
2312
2313                if ( match_len >= TDEFL_MIN_MATCH_LEN ) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
2314        }
2315
2316        static mz_bool tdefl_compress_normal( tdefl_compressor *d )
2317        {
2318                const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left;
2319                tdefl_flush flush = d->m_flush;
2320
2321                while ( ( src_buf_left ) || ( ( flush ) && ( d->m_lookahead_size ) ) )
2322                {
2323                        mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
2324                        // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN.
2325                        if ( ( d->m_lookahead_size + d->m_dict_size ) >= ( TDEFL_MIN_MATCH_LEN - 1 ) )
2326                        {
2327                                mz_uint dst_pos = ( d->m_lookahead_pos + d->m_lookahead_size ) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
2328                                mz_uint hash = ( d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT ) ^ d->m_dict[( ins_pos + 1 ) & TDEFL_LZ_DICT_SIZE_MASK];
2329                                mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size );
2330                                const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
2331                                src_buf_left -= num_bytes_to_process;
2332                                d->m_lookahead_size += num_bytes_to_process;
2333                                while ( pSrc != pSrc_end )
2334                                {
2335                                        mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if ( dst_pos < ( TDEFL_MAX_MATCH_LEN - 1 ) ) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
2336                                        hash = ( ( hash << TDEFL_LZ_HASH_SHIFT ) ^ c ) & ( TDEFL_LZ_HASH_SIZE - 1 );
2337                                        d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)( ins_pos );
2338                                        dst_pos = ( dst_pos + 1 ) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++;
2339                                }
2340                        }
2341                        else
2342                        {
2343                                while ( ( src_buf_left ) && ( d->m_lookahead_size < TDEFL_MAX_MATCH_LEN ) )
2344                                {
2345                                        mz_uint8 c = *pSrc++;
2346                                        mz_uint dst_pos = ( d->m_lookahead_pos + d->m_lookahead_size ) & TDEFL_LZ_DICT_SIZE_MASK;
2347                                        src_buf_left--;
2348                                        d->m_dict[dst_pos] = c;
2349                                        if ( dst_pos < ( TDEFL_MAX_MATCH_LEN - 1 ) )
2350                                                d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
2351                                        if ( ( ++d->m_lookahead_size + d->m_dict_size ) >= TDEFL_MIN_MATCH_LEN )
2352                                        {
2353                                                mz_uint ins_pos = d->m_lookahead_pos + ( d->m_lookahead_size - 1 ) - 2;
2354                                                mz_uint hash = ( ( d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << ( TDEFL_LZ_HASH_SHIFT * 2 ) ) ^ ( d->m_dict[( ins_pos + 1 ) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT ) ^ c ) & ( TDEFL_LZ_HASH_SIZE - 1 );
2355                                                d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)( ins_pos );
2356                                        }
2357                                }
2358                        }
2359                        d->m_dict_size = MZ_MIN( TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size );
2360                        if ( ( !flush ) && ( d->m_lookahead_size < TDEFL_MAX_MATCH_LEN ) )
2361                                break;
2362
2363                        // Simple lazy/greedy parsing state machine.
2364                        len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : ( TDEFL_MIN_MATCH_LEN - 1 ); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
2365                        if ( d->m_flags & ( TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS ) )
2366                        {
2367                                if ( ( d->m_dict_size ) && ( !( d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS ) ) )
2368                                {
2369                                        mz_uint8 c = d->m_dict[( cur_pos - 1 ) & TDEFL_LZ_DICT_SIZE_MASK];
2370                                        cur_match_len = 0; while ( cur_match_len < d->m_lookahead_size ) { if ( d->m_dict[cur_pos + cur_match_len] != c ) break; cur_match_len++; }
2371                                        if ( cur_match_len < TDEFL_MIN_MATCH_LEN ) cur_match_len = 0; else cur_match_dist = 1;
2372                                }
2373                        }
2374                        else
2375                        {
2376                                tdefl_find_match( d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len );
2377                        }
2378                        if ( ( ( cur_match_len == TDEFL_MIN_MATCH_LEN ) && ( cur_match_dist >= 8U * 1024U ) ) || ( cur_pos == cur_match_dist ) || ( ( d->m_flags & TDEFL_FILTER_MATCHES ) && ( cur_match_len <= 5 ) ) )
2379                        {
2380                                cur_match_dist = cur_match_len = 0;
2381                        }
2382                        if ( d->m_saved_match_len )
2383                        {
2384                                if ( cur_match_len > d->m_saved_match_len )
2385                                {
2386                                        tdefl_record_literal( d, (mz_uint8)d->m_saved_lit );
2387                                        if ( cur_match_len >= 128 )
2388                                        {
2389                                                tdefl_record_match( d, cur_match_len, cur_match_dist );
2390                                                d->m_saved_match_len = 0; len_to_move = cur_match_len;
2391                                        }
2392                                        else
2393                                        {
2394                                                d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
2395                                        }
2396                                }
2397                                else
2398                                {
2399                                        tdefl_record_match( d, d->m_saved_match_len, d->m_saved_match_dist );
2400                                        len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0;
2401                                }
2402                        }
2403                        else if ( !cur_match_dist )
2404                                tdefl_record_literal( d, d->m_dict[MZ_MIN( cur_pos, sizeof( d->m_dict ) - 1 )] );
2405                        else if ( ( d->m_greedy_parsing ) || ( d->m_flags & TDEFL_RLE_MATCHES ) || ( cur_match_len >= 128 ) )
2406                        {
2407                                tdefl_record_match( d, cur_match_len, cur_match_dist );
2408                                len_to_move = cur_match_len;
2409                        }
2410                        else
2411                        {
2412                                d->m_saved_lit = d->m_dict[MZ_MIN( cur_pos, sizeof( d->m_dict ) - 1 )]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
2413                        }
2414                        // Move the lookahead forward by len_to_move bytes.
2415                        d->m_lookahead_pos += len_to_move;
2416                        MZ_ASSERT( d->m_lookahead_size >= len_to_move );
2417                        d->m_lookahead_size -= len_to_move;
2418                        d->m_dict_size = MZ_MIN( d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE );
2419                        // Check if it's time to flush the current LZ codes to the internal output buffer.
2420                        if ( ( d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8] ) ||
2421                                ( ( d->m_total_lz_bytes > 31 * 1024 ) && ( ( ( ( (mz_uint)( d->m_pLZ_code_buf - d->m_lz_code_buf ) * 115 ) >> 7 ) >= d->m_total_lz_bytes ) || ( d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS ) ) ) )
2422                        {
2423                                int n;
2424                                d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
2425                                if ( ( n = tdefl_flush_block( d, 0 ) ) != 0 )
2426                                        return ( n < 0 ) ? MZ_FALSE : MZ_TRUE;
2427                        }
2428                }
2429
2430                d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
2431                return MZ_TRUE;
2432        }
2433
2434        static tdefl_status tdefl_flush_output_buffer( tdefl_compressor *d )
2435        {
2436                if ( d->m_pIn_buf_size )
2437                {
2438                        *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
2439                }
2440
2441                if ( d->m_pOut_buf_size )
2442                {
2443                        size_t n = MZ_MIN( *d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining );
2444                        memcpy( (mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n );
2445                        d->m_output_flush_ofs += (mz_uint)n;
2446                        d->m_output_flush_remaining -= (mz_uint)n;
2447                        d->m_out_buf_ofs += n;
2448
2449                        *d->m_pOut_buf_size = d->m_out_buf_ofs;
2450                }
2451
2452                return ( d->m_finished && !d->m_output_flush_remaining ) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;
2453        }
2454
2455        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 )
2456        {
2457                if ( !d )
2458                {
2459                        if ( pIn_buf_size ) *pIn_buf_size = 0;
2460                        if ( pOut_buf_size ) *pOut_buf_size = 0;
2461                        return TDEFL_STATUS_BAD_PARAM;
2462                }
2463
2464                d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size;
2465                d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size;
2466                d->m_pSrc = (const mz_uint8 *)( pIn_buf ); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
2467                d->m_out_buf_ofs = 0;
2468                d->m_flush = flush;
2469
2470                if ( ( ( d->m_pPut_buf_func != NULL ) == ( ( pOut_buf != NULL ) || ( pOut_buf_size != NULL ) ) ) || ( d->m_prev_return_status != TDEFL_STATUS_OKAY ) ||
2471                        ( d->m_wants_to_finish && ( flush != TDEFL_FINISH ) ) || ( pIn_buf_size && *pIn_buf_size && !pIn_buf ) || ( pOut_buf_size && *pOut_buf_size && !pOut_buf ) )
2472                {
2473                        if ( pIn_buf_size ) *pIn_buf_size = 0;
2474                        if ( pOut_buf_size ) *pOut_buf_size = 0;
2475                        return ( d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM );
2476                }
2477                d->m_wants_to_finish |= ( flush == TDEFL_FINISH );
2478
2479                if ( ( d->m_output_flush_remaining ) || ( d->m_finished ) )
2480                        return ( d->m_prev_return_status = tdefl_flush_output_buffer( d ) );
2481
2482#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
2483                if ( ( ( d->m_flags & TDEFL_MAX_PROBES_MASK ) == 1 ) &&
2484                        ( ( d->m_flags & TDEFL_GREEDY_PARSING_FLAG ) != 0 ) &&
2485                        ( ( d->m_flags & ( TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES ) ) == 0 ) )
2486                {
2487                        if ( !tdefl_compress_fast( d ) )
2488                                return d->m_prev_return_status;
2489                }
2490                else
2491#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
2492                {
2493                        if ( !tdefl_compress_normal( d ) )
2494                                return d->m_prev_return_status;
2495                }
2496
2497                if ( ( d->m_flags & ( TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32 ) ) && ( pIn_buf ) )
2498                        d->m_adler32 = (mz_uint32)mz_adler32( d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf );
2499
2500                if ( ( flush ) && ( !d->m_lookahead_size ) && ( !d->m_src_buf_left ) && ( !d->m_output_flush_remaining ) )
2501                {
2502                        if ( tdefl_flush_block( d, flush ) < 0 )
2503                                return d->m_prev_return_status;
2504                        d->m_finished = ( flush == TDEFL_FINISH );
2505                        if ( flush == TDEFL_FULL_FLUSH ) { MZ_CLEAR_OBJ( d->m_hash ); MZ_CLEAR_OBJ( d->m_next ); d->m_dict_size = 0; }
2506                }
2507
2508                return ( d->m_prev_return_status = tdefl_flush_output_buffer( d ) );
2509        }
2510
2511        tdefl_status tdefl_compress_buffer( tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush )
2512        {
2513                MZ_ASSERT( d->m_pPut_buf_func ); return tdefl_compress( d, pIn_buf, &in_buf_size, NULL, NULL, flush );
2514        }
2515
2516        tdefl_status tdefl_init( tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags )
2517        {
2518                d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user;
2519                d->m_flags = (mz_uint)( flags ); d->m_max_probes[0] = 1 + ( ( flags & 0xFFF ) + 2 ) / 3; d->m_greedy_parsing = ( flags & TDEFL_GREEDY_PARSING_FLAG ) != 0;
2520                d->m_max_probes[1] = 1 + ( ( ( flags & 0xFFF ) >> 2 ) + 2 ) / 3;
2521                if ( !( flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG ) ) MZ_CLEAR_OBJ( d->m_hash );
2522                d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
2523                d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
2524                d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8;
2525                d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY;
2526                d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1;
2527                d->m_pIn_buf = NULL; d->m_pOut_buf = NULL;
2528                d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL;
2529                d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0;
2530                memset( &d->m_huff_count[0][0], 0, sizeof( d->m_huff_count[0][0] ) * TDEFL_MAX_HUFF_SYMBOLS_0 );
2531                memset( &d->m_huff_count[1][0], 0, sizeof( d->m_huff_count[1][0] ) * TDEFL_MAX_HUFF_SYMBOLS_1 );
2532                return TDEFL_STATUS_OKAY;
2533        }
2534
2535        tdefl_status tdefl_get_prev_return_status( tdefl_compressor *d )
2536        {
2537                return d->m_prev_return_status;
2538        }
2539
2540        mz_uint32 tdefl_get_adler32( tdefl_compressor *d )
2541        {
2542                return d->m_adler32;
2543        }
2544
2545        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 )
2546        {
2547                tdefl_compressor *pComp; mz_bool succeeded; if ( ( ( buf_len ) && ( !pBuf ) ) || ( !pPut_buf_func ) ) return MZ_FALSE;
2548                pComp = (tdefl_compressor*)MZ_MALLOC( sizeof( tdefl_compressor ) ); if ( !pComp ) return MZ_FALSE;
2549                succeeded = ( tdefl_init( pComp, pPut_buf_func, pPut_buf_user, flags ) == TDEFL_STATUS_OKAY );
2550                succeeded = succeeded && ( tdefl_compress_buffer( pComp, pBuf, buf_len, TDEFL_FINISH ) == TDEFL_STATUS_DONE );
2551                MZ_FREE( pComp ); return succeeded;
2552        }
2553
2554        typedef struct
2555        {
2556                size_t m_size, m_capacity;
2557                mz_uint8 *m_pBuf;
2558                mz_bool m_expandable;
2559        } tdefl_output_buffer;
2560
2561        static mz_bool tdefl_output_buffer_putter( const void *pBuf, int len, void *pUser )
2562        {
2563                tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
2564                size_t new_size = p->m_size + len;
2565                if ( new_size > p->m_capacity )
2566                {
2567                        size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if ( !p->m_expandable ) return MZ_FALSE;
2568                        do { new_capacity = MZ_MAX( 128U, new_capacity << 1U ); } while ( new_size > new_capacity );
2569                        pNew_buf = (mz_uint8*)MZ_REALLOC( p->m_pBuf, new_capacity ); if ( !pNew_buf ) return MZ_FALSE;
2570                        p->m_pBuf = pNew_buf; p->m_capacity = new_capacity;
2571                }
2572                memcpy( (mz_uint8*)p->m_pBuf + p->m_size, pBuf, len ); p->m_size = new_size;
2573                return MZ_TRUE;
2574        }
2575
2576        void *tdefl_compress_mem_to_heap( const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags )
2577        {
2578                tdefl_output_buffer out_buf; MZ_CLEAR_OBJ( out_buf );
2579                if ( !pOut_len ) return MZ_FALSE; else *pOut_len = 0;
2580                out_buf.m_expandable = MZ_TRUE;
2581                if ( !tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags ) ) return NULL;
2582                *pOut_len = out_buf.m_size; return out_buf.m_pBuf;
2583        }
2584
2585        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 )
2586        {
2587                tdefl_output_buffer out_buf; MZ_CLEAR_OBJ( out_buf );
2588                if ( !pOut_buf ) return 0;
2589                out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len;
2590                if ( !tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags ) ) return 0;
2591                return out_buf.m_size;
2592        }
2593
2594#ifndef MINIZ_NO_ZLIB_APIS
2595        static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32,  16, 32, 128, 256,  512, 768, 1500 };
2596
2597        // 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).
2598        mz_uint tdefl_create_comp_flags_from_zip_params( int level, int window_bits, int strategy )
2599        {
2600                mz_uint comp_flags = s_tdefl_num_probes[( level >= 0 ) ? MZ_MIN( 10, level ) : MZ_DEFAULT_LEVEL] | ( ( level <= 3 ) ? TDEFL_GREEDY_PARSING_FLAG : 0 );
2601                if ( window_bits > 0 ) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
2602
2603                if ( !level ) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
2604                else if ( strategy == MZ_FILTERED ) comp_flags |= TDEFL_FILTER_MATCHES;
2605                else if ( strategy == MZ_HUFFMAN_ONLY ) comp_flags &= ~TDEFL_MAX_PROBES_MASK;
2606                else if ( strategy == MZ_FIXED ) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
2607                else if ( strategy == MZ_RLE ) comp_flags |= TDEFL_RLE_MATCHES;
2608
2609                return comp_flags;
2610        }
2611#endif //MINIZ_NO_ZLIB_APIS
2612
2613#ifdef _MSC_VER
2614#pragma warning (push)
2615#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal)
2616#endif
2617
2618        // Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at
2619        // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
2620        // This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck.
2621        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 )
2622        {
2623                // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined.
2624                static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32,  16, 32, 128, 256,  512, 768, 1500 };
2625                tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC( sizeof( tdefl_compressor ) ); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0;
2626                if ( !pComp ) return NULL;
2627                MZ_CLEAR_OBJ( out_buf ); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX( 64, ( 1 + bpl )*h ); if ( NULL == ( out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC( out_buf.m_capacity ) ) ) { MZ_FREE( pComp ); return NULL; }
2628                // write dummy header
2629                for ( z = 41; z; --z ) tdefl_output_buffer_putter( &z, 1, &out_buf );
2630                // compress image data
2631                tdefl_init( pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN( 10, level )] | TDEFL_WRITE_ZLIB_HEADER );
2632                for ( y = 0; y < h; ++y ) { tdefl_compress_buffer( pComp, &z, 1, TDEFL_NO_FLUSH ); tdefl_compress_buffer( pComp, (mz_uint8*)pImage + ( flip ? ( h - 1 - y ) : y ) * bpl, bpl, TDEFL_NO_FLUSH ); }
2633                if ( tdefl_compress_buffer( pComp, NULL, 0, TDEFL_FINISH ) != TDEFL_STATUS_DONE ) { MZ_FREE( pComp ); MZ_FREE( out_buf.m_pBuf ); return NULL; }
2634                // write real header
2635                *pLen_out = out_buf.m_size - 41;
2636                {
2637                        static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 };
2638                        mz_uint8 pnghdr[41] = { 0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,
2639                                0,0,(mz_uint8)( w >> 8 ),(mz_uint8)w,0,0,(mz_uint8)( h >> 8 ),(mz_uint8)h,8,chans[num_chans],0,0,0,0,0,0,0,
2640                                (mz_uint8)( *pLen_out >> 24 ),(mz_uint8)( *pLen_out >> 16 ),(mz_uint8)( *pLen_out >> 8 ),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54 };
2641                        c = (mz_uint32)mz_crc32( MZ_CRC32_INIT, pnghdr + 12, 17 ); for ( i = 0; i < 4; ++i, c <<= 8 ) ( (mz_uint8*)( pnghdr + 29 ) )[i] = (mz_uint8)( c >> 24 );
2642                        memcpy( out_buf.m_pBuf, pnghdr, 41 );
2643                }
2644                // write footer (IDAT CRC-32, followed by IEND chunk)
2645                if ( !tdefl_output_buffer_putter( "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf ) ) { *pLen_out = 0; MZ_FREE( pComp ); MZ_FREE( out_buf.m_pBuf ); return NULL; }
2646                c = (mz_uint32)mz_crc32( MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4 ); for ( i = 0; i < 4; ++i, c <<= 8 ) ( out_buf.m_pBuf + out_buf.m_size - 16 )[i] = (mz_uint8)( c >> 24 );
2647                // compute final size of file, grab compressed data buffer and return
2648                *pLen_out += 57; MZ_FREE( pComp ); return out_buf.m_pBuf;
2649        }
2650        void *tdefl_write_image_to_png_file_in_memory( const void *pImage, int w, int h, int num_chans, size_t *pLen_out )
2651        {
2652                // 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)
2653                return tdefl_write_image_to_png_file_in_memory_ex( pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE );
2654        }
2655
2656#ifdef _MSC_VER
2657#pragma warning (pop)
2658#endif
2659
2660
2661#ifdef __cplusplus
2662}
2663#endif
2664
2665void * nv::miniz_decompress( const void *source_buf, size_t source_buf_len, size_t *out_len, bool parse_header )
2666{
2667        NV_PROFILE( "decompress" );
2668        return tinfl_decompress_mem_to_heap( source_buf, source_buf_len, out_len, parse_header ? TINFL_FLAG_PARSE_ZLIB_HEADER : 0 );
2669}
[520]2670
2671int nv::miniz_compress( unsigned char *pDest, unsigned long *pDest_len, const unsigned char *pSource, unsigned long source_len, int level )
2672{
2673        NV_PROFILE( "compress" );
2674        return mz_compress2( pDest, pDest_len, pSource, source_len, level );
2675}
2676
2677unsigned long nv::miniz_bound( unsigned long source_len )
2678{
2679        return mz_compressBound( source_len );
2680}
Note: See TracBrowser for help on using the repository browser.