bzip官网:http://www.bzip.org/ 有源码及英文文档。
官网的英文文档比较齐全,可就是没有找到类似的demo代码,没办法,只能结合已有的官方文档,自己摸索了。
由于需要对内存的数据进行加压解压处理,因此调用的是bzip提供的低级接口:
typedef struct {
char *next_in; // 输入指针
unsigned int avail_in; // 输入数据长
unsigned int total_in_lo32;
unsigned int total_in_hi32;
char *next_out; // 输出指针
unsigned int avail_out; // 输出缓冲大小
unsigned int total_out_lo32;
unsigned int total_out_hi32;
void *state;
void *(*bzalloc)(void *,int,int);
void (*bzfree)(void *,void *);
void *opaque;
} bz_stream;
int BZ2_bzCompressInit ( bz_stream *strm,
int blockSize100k,
int verbosity,
int workFactor );
//一般使用默认推荐参数:BZ2_bzCompressInit(strm,5,2,30);
int BZ2_bzCompress ( bz_stream *strm, int action );
int BZ2_bzCompressEnd ( bz_stream *strm );
int BZ2_bzDecompressInit ( bz_stream *strm, int verbosity, int small );
// 一般使用默认推荐参数:BZ2_bzDecompressInit(strm,2,1);
int BZ2_bzDecompress ( bz_stream *strm );
int BZ2_bzDecompressEnd ( bz_stream *strm );
压缩过程:
1. 初始化压缩参数,分配资源。
2. 对数据进行压缩,输出压缩后的数据。
压缩的过程实际上是一个有限状态机处理过程,看英文文档感觉比较绕,比较麻烦。
3. 销毁释放分配的资源。
压缩过程的有限状态机:
RUNNING - 输入数据进行压缩。
FLUSHING - 输出压缩后的数据。
FINISHING - 没有输入,只有输出。
IDLE - 压缩未开始或者压缩结束。
压缩遵循的原则:
1. 进入压缩,即进入RUNNING状态,输入待压缩数据,如果BZ2_bzCompress ( bz_stream *strm, int action )返回BZ_RUN_OK,则继续输入。直到返回非BZ_RUN_OK或者没有更多的输入。
2. 如果上面返回的是BZ_FLUSH_OK,进入FLUSHING状态,输出压缩后的数据。
3. 如果返回的是BZ_FINISH_OK,进入FINISHING状态,进行输出,直到返回BZ_STREAM_END结束。
在压缩的过程中,如果出现错误或者异常,如果捕获到其他异常,压缩过程应该就是失败的了。具体异常返回查看