Skip to content

Instantly share code, notes, and snippets.

@t-mat
Last active August 29, 2015 14:05
Show Gist options
  • Save t-mat/5cfa24898c7897460315 to your computer and use it in GitHub Desktop.
Save t-mat/5cfa24898c7897460315 to your computer and use it in GitHub Desktop.
lz4-framing-api-example1.c
#include <stdio.h>
#include "lz4Frame.h"
size_t LZ4F_getSrcSize(const LZ4F_preferences_t* preferences); // still missing function ?
int main() {
int result = EXIT_FAILURE;
FILE* inpFp = fopen("src.bin", "rb");
FILE* outFp = fopen("dst.lz4", "wb");
LZ4F_preferences_t preferences = { 0 };
preferences.maxBlockSize = max64KB;
preferences.blockMode = blockIndependent;
preferences.contentChecksum = contentChecksumEnabled;
LZ4F_compressOptions_t options = { 0 };
options.compressionLevel = 9;
options.autoFlush = FALSE;
const size_t srcSize = LZ4F_getSrcSize(&preferences); // still missing function ?
const size_t dstMaxSize = LZ4F_compressBound(srcSize, &preferences);
if(! LZ4_isError(srcSize) && ! LZ4_isError(dstMaxSize)) {
void* const srcBuffer = malloc(srcSize);
void* const dstBuffer = malloc(dstMaxSize);
LZ4F_compressionContext_t* cc = NULL;
const size_t headerSize =
LZ4F_compressInit(&cc, dstBuffer, dstMaxSize, &preferences);
if(! LZ4_isError(headerSize)) {
int finished = 0;
fwrite(dstBuffer, 1, headerSize, outFp);
for(;;) {
const size_t readBytes = fread(srcBuffer, 1, srcSize, inpFp);
if(0 == readBytes || feof(inpFp)) {
finished = 1;
break;
}
const size_t cmpSize =
LZ4F_compress(cc, dstBuffer, dstMaxSize, srcBuffer, readBytes, &options);
if(LZ4_isError(cmpSize)) {
break;
}
fwrite(dstBuffer, 1, cmpSize, outFp);
}
// It seems just a bit complicated.
// (1) Users must always call LZ4F_compressEnd() to resource deallocation.
// (2) And users must decide wirte the final data or not.
const size_t endSize = LZ4F_compressEnd(cc, dstBuffer, dstMaxSize, &options);
if(finished && ! LZ4_isError(endSize)) {
fwrite(dstBuffer, 1, endSize, outFp);
result = EXIT_SUCCESS;
}
}
// I would like to call some kind of resource cleanup thing, even if cc is NULL.
// LZ4F_compressCleanup(cc);
free(srcBuffer);
free(dstBuffer);
}
fclose(outFp);
fclose(inpFp);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment