How to compress a buffer with zlib?

后端 未结 5 510
無奈伤痛
無奈伤痛 2020-12-23 13:15

There is a usage example at the zlib website: http://www.zlib.net/zlib_how.html

However in the example they are compressing a file. I would like to compress a binary

5条回答
  •  佛祖请我去吃肉
    2020-12-23 13:35

    This is an example to pack a buffer with zlib and save the compressed contents in a vector.

    void compress_memory(void *in_data, size_t in_data_size, std::vector &out_data)
    {
     std::vector buffer;
    
     const size_t BUFSIZE = 128 * 1024;
     uint8_t temp_buffer[BUFSIZE];
    
     z_stream strm;
     strm.zalloc = 0;
     strm.zfree = 0;
     strm.next_in = reinterpret_cast(in_data);
     strm.avail_in = in_data_size;
     strm.next_out = temp_buffer;
     strm.avail_out = BUFSIZE;
    
     deflateInit(&strm, Z_BEST_COMPRESSION);
    
     while (strm.avail_in != 0)
     {
      int res = deflate(&strm, Z_NO_FLUSH);
      assert(res == Z_OK);
      if (strm.avail_out == 0)
      {
       buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);
       strm.next_out = temp_buffer;
       strm.avail_out = BUFSIZE;
      }
     }
    
     int deflate_res = Z_OK;
     while (deflate_res == Z_OK)
     {
      if (strm.avail_out == 0)
      {
       buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);
       strm.next_out = temp_buffer;
       strm.avail_out = BUFSIZE;
      }
      deflate_res = deflate(&strm, Z_FINISH);
     }
    
     assert(deflate_res == Z_STREAM_END);
     buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE - strm.avail_out);
     deflateEnd(&strm);
    
     out_data.swap(buffer);
    }
    

提交回复
热议问题