压缩,解压缩数据块的接口

压缩一个数据块

输入:

  • ibuf 未压缩数据块
  • isize 输入数据大小
  • obuf 压缩后数据块
  • osizm 输出数据容量
    返回:
  • 0表示压缩成功
  • *osizp 压缩后数据的大小
static int pw__compress(byte* ibuf,uint isiz,byte* obuf,uint osizm,
  uint* osizp) {
  // 压缩一个数据块;
  // return: 0: compression was successful;
  //         !=0: error number from zlib;
  // *osizp: 压缩后数据的大小;
  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) {
  // 解压缩一个数据块;
  // return: 0: 解压缩成功;
  //         !=0: error number from zlib;
  // *osizp: 解压缩后的数据的大小;
  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;
  // 读数据
  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);
  // 添加一些零字节
  if(i>4) i= 4;
  while(--i>=0) *obuf++= 0;
  return 0;
  }  // end   pb__decompress()

你可能感兴趣的:(压缩,解压缩数据块的接口)