Easylzma是一个实现了LZMA压缩和解压缩算法的C语言库。
LZMA,(Lempel-Ziv-Markovchain-Algorithm的縮寫),是2001年以來得到發展的一個數據壓縮演算法,它用於7-Zip歸檔工具中的7z格式。它使用類似於LZ77的字典編碼機制,在一般的情況下壓縮率比bzip2為高,用於壓縮的字典檔大小可達4GB。
示例代码:
/* *anexampleofbasicLZMAcompressiontoandfrommemorybuffers *usingtheeasylzmalibrary. */ #include"easylzma/compress.h" #include<string.h>#include<assert.h> structdataStream{ constunsignedchar*inData; size_tinLen; unsignedchar*outData; size_toutLen;};/*aninputcallbackthatwillbepassedtoelzma_compress_run(), *itreadsfromamemorybuffer*/staticintinputCallback(void*ctx,void*buf,size_t*size){ size_trd=0; structdataStream*ds=(structdataStream*)ctx; assert(ds!=NULL); rd=(ds->inLen<*size)?ds->inLen:*size; if(rd>0){ memcpy(buf,(void*)ds->inData,rd); ds->inData+=rd; ds->inLen-=rd; } *size=rd; return0;}/*anouputcallbackthatwillbepassedtoelzma_compress_run(), *itreallocsandwritestoamemorybuffer*/staticsize_toutputCallback(void*ctx,constvoid*buf,size_tsize){ structdataStream*ds=(structdataStream*)ctx; assert(ds!=NULL); if(size>0){ ds->outData=realloc(ds->outData,ds->outLen+size); memcpy((void*)(ds->outData+ds->outLen),buf,size); ds->outLen+=size; } returnsize;}/*afunctionthatwillcompressdatausinga1mbdictionaryanda *clientspecifiedencodingformat(oneofELZMA_lziporELZMA_lzma)*/intsimpleCompress(elzma_file_formatformat,constunsignedchar*inData, size_tinLen,unsignedchar**outData, size_t*outLen){ intrc; elzma_compress_handlehand; /*allocatecompressionhandle*/ hand=elzma_compress_alloc(); assert(hand!=NULL); /*configurethecompressionrunwithmostlydefaultparameters */ rc=elzma_compress_config(hand,ELZMA_LC_DEFAULT, ELZMA_LP_DEFAULT,ELZMA_PB_DEFAULT, 5,(1<<20)/*1mb*/, format,inLen); /*failifwecouldn'tallocate*/ if(rc!=ELZMA_E_OK){ elzma_compress_free(&hand); returnrc; } /*nowrunthecompression*/ { /*setupthecontextstructurethatwillbepassedto *streamcallbacks*/ structdataStreamds; ds.inData=inData; ds.inLen=inLen; ds.outData=NULL; ds.outLen=0; /*runthestreamingcompression*/ rc=elzma_compress_run(hand,inputCallback,(void*)&ds, outputCallback,(void*)&ds); if(rc!=ELZMA_E_OK){ if(ds.outData!=NULL)free(ds.outData); elzma_compress_free(&hand); returnrc; } *outData=ds.outData; *outLen=ds.outLen; } returnrc;}
评论