Posted on 2010-03-05 17:51
David Fang 阅读(3825)
评论(4) 编辑 收藏 引用 所属分类:
磨刀不误砍柴工
zlib的使用一般是以文件作为输入输出,而本类在zlib库基础上进行了一层封装,以便在内存中解压gzip数据,源码如下:
1 #ifndef __CONTENT_DECODER_H__
2 #define __CONTENT_DECODER_H__
3
4 #include <string>
5
6 class gzip_decoder
7 {
8 public:
9 gzip_decoder(size_t uncompress_buff_len = 1024);
10
11 ~gzip_decoder();
12
13 bool ungzip(unsigned char* gzdata, size_t gzdata_len, std::string& out_data);
14
15 protected:
16 private:
17 const size_t uncompress_buff_len_;
18 unsigned char* uncompress_buff_;
19 };
20
21 #endif
22
23
24
实现文件:
1 #include "content_decoder.h"
2 #include <stdlib.h>
3 #include "zlib.h"
4
5
6 gzip_decoder::gzip_decoder(size_t uncompress_buff_len)
7 :uncompress_buff_len_(uncompress_buff_len),
8 uncompress_buff_(NULL)
9 {
10 uncompress_buff_ = (unsigned char*)malloc(uncompress_buff_len_);
11 }
12
13 gzip_decoder::~gzip_decoder()
14 {
15 if (uncompress_buff_)
16 {
17 free(uncompress_buff_);
18 }
19 }
20
21 bool gzip_decoder::ungzip(unsigned char* gzdata, size_t gzdata_len, std::string& out_data)
22 {
23 int err;
24 unsigned long out_count = 0;
25 z_stream d_stream = {0}; /* decompression stream */
26
27 d_stream.zalloc = (alloc_func)0;
28 d_stream.zfree = (free_func)0;
29 d_stream.opaque = (voidpf)0;
30 d_stream.next_in = gzdata;
31 d_stream.avail_in = gzdata_len;
32 d_stream.avail_out = uncompress_buff_len_;
33 d_stream.next_out = uncompress_buff_;
34
35 if(inflateInit2(&d_stream, 47) != Z_OK)
36 return false;
37
38 out_data.clear();
39
40 while (d_stream.total_in < gzdata_len)
41 {
42 if((err = inflate(&d_stream, Z_SYNC_FLUSH)) == Z_STREAM_END)
43 {
44 out_data.append((const char*)uncompress_buff_, d_stream.total_out - out_count);
45 err = inflateEnd(&d_stream);
46 break;
47 }
48
49 if(err == Z_OK)
50 {
51 out_data.append((const char*)uncompress_buff_, d_stream.total_out - out_count);
52 out_count = d_stream.total_out;
53 d_stream.avail_out = uncompress_buff_len_;
54 d_stream.next_out = uncompress_buff_;
55 }
56 else
57 {
58 goto unzip_exit;
59 }
60 }
61
62 unzip_exit:
63 return err == Z_OK;
64 }
代码下载:
gzip_decoder.rar