int miniz_deflate( unsigned char *dest, size_t *destLen, const unsigned char *source, size_t sourceLen, int level ){ tdefl_compressor comp; mz_uint comp_flags = tdefl_create_comp_flags_from_zip_params(level, -MAX_WBITS, MZ_DEFAULT_STRATEGY); int status=tdefl_init(&comp,NULL,NULL,comp_flags); size_t _sourceLen=sourceLen; if(status)return status; status=tdefl_compress(&comp,source,&_sourceLen,dest,destLen,MZ_FINISH); return status==MZ_STREAM_END ? MZ_OK : status; }
int compress_buffer_to_file(const char* filename, const char* inbuf, const size_t buffer_size) { // modified version of miniz.c's example5.c static const int COMPRESSION_FAIL = 1; int level = Z_BEST_COMPRESSION; void* next_out = outbuf; const void* next_in = (const void*)inbuf; size_t avail_in = buffer_size; size_t avail_out = OUT_BUF_SIZE; int error = 0; size_t total_in = 0, total_out = 0; size_t comp_flags = tdefl_create_comp_flags_from_zip_params( level, MZ_DEFAULT_WINDOW_BITS, MZ_DEFAULT_STRATEGY) | TDEFL_WRITE_ZLIB_HEADER; // Initialize the low-level compressor. tdefl_compressor deflator; tdefl_status status = tdefl_init(&deflator, NULL, NULL, int(comp_flags)); if (status != TDEFL_STATUS_OKAY) { printf("tdefl_init() failed!\n"); return COMPRESSION_FAIL; } FILE* outfile = fopen(filename, "wb"); if (outfile == NULL) { printf("Failed opening output file!\n"); return COMPRESSION_FAIL; } // Compression. for (;;) { size_t in_bytes = avail_in; size_t out_bytes = avail_out; // Compress as much of the input as possible (or all of it) to the output inbuf. status = tdefl_compress(&deflator, next_in, &in_bytes, next_out, &out_bytes, in_bytes ? TDEFL_NO_FLUSH : TDEFL_FINISH); next_in = (const char*)next_in + in_bytes; avail_in -= in_bytes; total_in += in_bytes; next_out = (char*)next_out + out_bytes; avail_out -= out_bytes; total_out += out_bytes; if ((status != TDEFL_STATUS_OKAY) || (!avail_out)) { // Output inbuf is full, or compression is done or failed, so write inbuf to output file. size_t n = OUT_BUF_SIZE - (size_t)avail_out; if (fwrite(outbuf, 1, n, outfile) != n) { printf("Failed writing to output file!\n"); error = COMPRESSION_FAIL; break; } next_out = outbuf; avail_out = OUT_BUF_SIZE; } if (status == TDEFL_STATUS_DONE) { // Compression completed successfully. break; } else if (status != TDEFL_STATUS_OKAY) { // Compression somehow failed. printf("tdefl_compress() failed with status %d!\n", status); error = COMPRESSION_FAIL; break; } } if (outfile != NULL) { int closed = fclose(outfile); if (closed) printf("failed to close file \"%s\"\n", filename); } return error; }