壓縮一個數(shù)據(jù)塊
輸入:
- ibuf 未壓縮數(shù)據(jù)塊
- isize 輸入數(shù)據(jù)大小
- obuf 壓縮后數(shù)據(jù)塊
- osizm 輸出數(shù)據(jù)容量
返回: - 0表示壓縮成功
- *osizp 壓縮后數(shù)據(jù)的大小
static int pw__compress(byte* ibuf,uint isiz,byte* obuf,uint osizm,
uint* osizp) {
// 壓縮一個數(shù)據(jù)塊;
// return: 0: compression was successful;
// !=0: error number from zlib;
// *osizp: 壓縮后數(shù)據(jù)的大小;
z_stream strm;
int r,i;
// initialization
strm.zalloc= Z_NULL;
strm.zfree= Z_NULL;
strm.opaque= Z_NULL;
strm.next_in= Z_NULL;
strm.total_in= 0;
strm.avail_out= 0;
strm.next_out= Z_NULL;
strm.total_out= 0;
strm.msg= NULL;
r= deflateInit(&strm,Z_DEFAULT_COMPRESSION);
if(r!=Z_OK)
return r;
// read data
strm.next_in = ibuf;
strm.avail_in= isiz;
// compress
strm.next_out= obuf;
strm.avail_out= osizm;
r= deflate(&strm,Z_FINISH);
if(/*r!=Z_OK &&*/ r!=Z_STREAM_END) {
deflateEnd(&strm);
*osizp= 0;
if(r==0) r= 1000;
return r;
}
// clean-up
deflateEnd(&strm);
obuf+= *osizp= osizm-(i= strm.avail_out);
// add some zero bytes
if(i>4) i= 4;
while(--i>=0) *obuf++= 0;
return 0;
} // end pw__compress()
解壓縮
static int pb__decompress(byte* ibuf,uint isiz,byte* obuf,uint osizm,
uint* osizp) {
// 解壓縮一個數(shù)據(jù)塊;
// return: 0: 解壓縮成功;
// !=0: error number from zlib;
// *osizp: 解壓縮后的數(shù)據(jù)的大小;
z_stream strm;
int r,i;
// 初始化
strm.zalloc= Z_NULL;
strm.zfree= Z_NULL;
strm.opaque= Z_NULL;
strm.next_in= Z_NULL;
strm.total_in= 0;
strm.avail_out= 0;
strm.next_out= Z_NULL;
strm.total_out= 0;
strm.msg= NULL;
r= inflateInit(&strm);
if(r!=Z_OK)
return r;
// 讀數(shù)據(jù)
strm.next_in = ibuf;
strm.avail_in= isiz;
// 解壓縮
strm.next_out= obuf;
strm.avail_out= osizm;
r= inflate(&strm,Z_FINISH);
if(r!=Z_OK && r!=Z_STREAM_END) {
inflateEnd(&strm);
*osizp= 0;
return r;
}
// clean-up
inflateEnd(&strm);
obuf+= *osizp= osizm-(i= strm.avail_out);
// 添加一些零字節(jié)
if(i>4) i= 4;
while(--i>=0) *obuf++= 0;
return 0;
} // end pb__decompress()