Atlas  0.7.0
Networking protocol for the Worldforge system.
Gzip.cpp
1 // This file may be redistributed and modified only under the terms of
2 // the GNU Lesser General Public License (See COPYING for details).
3 // Copyright (C) 2000 Dmitry Derevyanko
4 
5 // $Id$
6 
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10 
11 #if defined(HAVE_ZLIB_H) && defined(HAVE_LIBZ)
12 #define ZLIB_CONST
13 #include <Atlas/Filters/Gzip.h>
14 
15 #ifndef ASSERT
16 #include <cassert>
17 #define ASSERT(exp) assert(exp)
18 #endif
19 
21 
22 const int DEFAULT_LEVEL = 6;
23 
24 void Gzip::begin()
25 {
26  incoming.next_in = Z_NULL;
27  incoming.avail_in = 0;
28  incoming.zalloc = Z_NULL;
29  incoming.zfree = Z_NULL;
30 
31  outgoing.zalloc = Z_NULL;
32  outgoing.zfree = Z_NULL;
33 
34  inflateInit(&incoming);
35  deflateInit(&outgoing, DEFAULT_LEVEL);
36 }
37 
38 void Gzip::end()
39 {
40  inflateEnd(&incoming);
41  deflateEnd(&outgoing);
42 }
43 
44 std::string Gzip::encode(const std::string& data)
45 {
46  std::string out_string;
47  int status;
48 
49  buf[0] = 0;
50 
51 //Handle early zlib versions
52 #if ZLIB_VERNUM < 0x1252
53  outgoing.next_in = (unsigned char *)data.data();
54 #else
55  outgoing.next_in = (z_const Bytef*)data.data();
56 #endif
57  outgoing.avail_in = data.size();
58 
59  do
60  {
61  outgoing.next_out = buf;
62  outgoing.avail_out = sizeof(buf);
63 
64  status = deflate(&outgoing, Z_SYNC_FLUSH);
65 
66  ASSERT(status == Z_OK);
67 
68  if (status >= 0) {
69  out_string.append((char*)buf, sizeof(buf) - outgoing.avail_out);
70  }
71  } while (outgoing.avail_out == 0);
72 
73  return out_string;
74 }
75 
76 std::string Gzip::decode(const std::string& data)
77 {
78  std::string out_string;
79 
80  buf[0] = 0;
81 
82 //Handle early zlib versions
83 #if ZLIB_VERNUM < 0x1252
84  incoming.next_in = (unsigned char *)data.data();
85 #else
86  incoming.next_in = (z_const Bytef*)data.data();
87 #endif
88  incoming.avail_in = data.size();
89 
90  do
91  {
92  incoming.next_out = buf;
93  incoming.avail_out = sizeof(buf);
94 
95  int status = inflate(&incoming, Z_SYNC_FLUSH);
96 
97  ASSERT(status == Z_OK);
98 
99  if (status >= 0) {
100  out_string.append((char*)buf, sizeof(buf) - incoming.avail_out);
101  }
102  } while(incoming.avail_out == 0);
103 
104  return out_string;
105 }
106 
107 #endif // HAVE_ZLIB_H && HAVE_LIBZ
Atlas::Filters::Gzip
Definition: Gzip.h:17