Last active
August 29, 2015 14:05
-
-
Save t-mat/67b6aba68e63b90d2400 to your computer and use it in GitHub Desktop.
lz4-framing-api-decoupled.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "lz4frame.h" | |
size_t compress(LZ4F_compressionContext_t* ctx, FILE* outFp, FILE* inpFp, | |
void* dstBuffer, size_t dstMaxSize, void* srcBuffer, size_t srcSize, | |
const LZ4F_compressOptions_t* options) | |
{ | |
// Maybe LZ4F_compressBegin()'s compressOptions seems to have overlooked. | |
const size_t headerSize = LZ4F_compressBegin( | |
ctx, dstBuffer, dstMaxSize, options); | |
if(LZ4_isError(headerSize)) { | |
return headerSize; | |
} | |
fwrite(dstBuffer, 1, headerSize, outFp); | |
for(;;) { | |
const size_t readBytes = fread(srcBuffer, 1, srcSize, inpFp); | |
if(0 == readBytes || feof(inpFp)) { | |
break; | |
} | |
const size_t cmpSize = LZ4F_compress( | |
ctx, dstBuffer, dstMaxSize, srcBuffer, readBytes, options); | |
if(LZ4_isError(cmpSize)) { | |
return cmpSize; | |
} | |
fwrite(dstBuffer, 1, cmpSize, outFp); | |
} | |
const size_t endSize = LZ4F_compressEnd(ctx, dstBuffer, dstMaxSize, options); | |
if(LZ4_isError(endSize)) { | |
return endSize; | |
} | |
fwrite(dstBuffer, 1, endSize, outFp); | |
return 0; | |
} | |
int main() { | |
int result = EXIT_FAILURE; | |
FILE* inpFp = fopen("inp.bin", "rb"); | |
FILE* outFp = fopen("out.lz4", "wb"); | |
LZ4F_preferences_t preferences = { 0 }; | |
preferences.compressionLevel = 9; | |
preferences.maxBlockSize = max64KB; | |
preferences.blockMode = blockIndependent; | |
preferences.contentChecksum = contentChecksumEnabled; | |
LZ4F_compressOptions_t options = { 0 }; | |
options.autoFlush = FALSE; | |
options.stableSrc = FALSE; | |
const size_t srcSize = LZ4F_getMaxSrcSize(0, &preferences); | |
const size_t dstMaxSize = LZ4F_compressBound(srcSize, &preferences); | |
if(! LZ4_isError(srcSize) && ! LZ4_isError(dstMaxSize)) { | |
LZ4F_compressionContext_t* ctx = LZ4F_createCompressionContext( | |
LZ4F_VERSION, &preferences); | |
void* srcBuffer = malloc(srcSize); | |
void* dstBuffer = malloc(dstMaxSize); | |
if(ctx && srcBuffer && dstBuffer) { | |
const size_t c = compress(ctx, outFp, inpFp, dstBuffer, dstSize, | |
srcBuffer, srcSize, &options); | |
if(! LZ4_isError(c)) { | |
result = EXIT_SUCCESS; | |
} | |
} | |
free(dstBuffer); | |
free(srcBuffer); | |
LZ4F_freeCompressionContext(ctx); | |
} | |
fclose(outFp); | |
fclose(inpFp); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment