gloox  1.1-svn
compressionzlib.cpp
1 /*
2  Copyright (c) 2005-2009 by Jakob Schroeter <js@camaya.net>
3  This file is part of the gloox library. http://camaya.net/gloox
4 
5  This software is distributed under a license. The full license
6  agreement can be found in the file LICENSE in this distribution.
7  This software may not be copied, modified, sold or distributed
8  other than expressed in the named license agreement.
9 
10  This software is distributed without any warranty.
11 */
12 
13 
14 
15 #include "compressionzlib.h"
16 
17 #ifdef HAVE_ZLIB
18 
19 namespace gloox
20 {
21 
23  : CompressionBase( cdh )
24  {
25  }
26 
28  {
29  int ret = Z_OK;
30  m_zinflate.zalloc = Z_NULL;
31  m_zinflate.zfree = Z_NULL;
32  m_zinflate.opaque = Z_NULL;
33  m_zinflate.avail_in = 0;
34  m_zinflate.next_in = Z_NULL;
35  ret = inflateInit( &m_zinflate );
36  if( ret != Z_OK )
37  return false;
38 
39  m_zdeflate.zalloc = Z_NULL;
40  m_zdeflate.zfree = Z_NULL;
41  m_zdeflate.opaque = Z_NULL;
42  m_zinflate.avail_in = 0;
43  m_zinflate.next_in = Z_NULL;
44  ret = deflateInit( &m_zdeflate, Z_BEST_COMPRESSION/*Z_DEFAULT_COMPRESSION*/ );
45  if( ret != Z_OK )
46  return false;
47 
48  m_valid = true;
49  return true;
50  }
51 
53  {
54  cleanup();
55  }
56 
57  void CompressionZlib::compress( const std::string& data )
58  {
59  if( !m_valid )
60  init();
61 
62  if( !m_valid || !m_handler || data.empty() )
63  return;
64 
65  long unsigned int CHUNK = data.length() + ( data.length() / 100 ) + 13;
66  Bytef* out = new Bytef[CHUNK];
67  char* in = const_cast<char*>( data.c_str() );
68 
69  m_compressMutex.lock();
70 
71  m_zdeflate.avail_in = static_cast<uInt>( data.length() );
72  m_zdeflate.next_in = (Bytef*)in;
73 
74  int ret;
75  std::string result;
76  do {
77  m_zdeflate.avail_out = static_cast<uInt>( CHUNK );
78  m_zdeflate.next_out = (Bytef*)out;
79 
80  ret = deflate( &m_zdeflate, Z_SYNC_FLUSH );
81  result.append( (char*)out, CHUNK - m_zdeflate.avail_out );
82  } while( m_zdeflate.avail_out == 0 );
83 
84  m_compressMutex.unlock();
85 
86  delete[] out;
87 
89  }
90 
91  void CompressionZlib::decompress( const std::string& data )
92  {
93  if( !m_valid )
94  init();
95 
96  if( !m_valid || !m_handler || data.empty() )
97  return;
98 
99  int CHUNK = 50;
100  char* out = new char[CHUNK];
101  char* in = const_cast<char*>( data.c_str() );
102 
103  m_zinflate.avail_in = static_cast<uInt>( data.length() );
104  m_zinflate.next_in = (Bytef*)in;
105 
106  int ret = Z_OK;
107  std::string result;
108  do
109  {
110  m_zinflate.avail_out = CHUNK;
111  m_zinflate.next_out = (Bytef*)out;
112 
113  ret = inflate( &m_zinflate, Z_SYNC_FLUSH );
114  result.append( out, CHUNK - m_zinflate.avail_out );
115  } while( m_zinflate.avail_out == 0 );
116 
117  delete[] out;
118 
120  }
121 
123  {
124  if( !m_valid )
125  return;
126 
127  inflateEnd( &m_zinflate );
128  deflateEnd( &m_zdeflate );
129 
130  m_valid = false;
131  }
132 
133 }
134 
135 #endif // HAVE_ZLIB