gloox  0.9.9.12
compressionzlib.cpp
1 /*
2  Copyright (c) 2005-2008 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  int ret = Z_OK;
26  m_zinflate.zalloc = Z_NULL;
27  m_zinflate.zfree = Z_NULL;
28  m_zinflate.opaque = Z_NULL;
29  m_zinflate.avail_in = 0;
30  m_zinflate.next_in = Z_NULL;
31  ret = inflateInit( &m_zinflate );
32 
33  if( ret == Z_OK )
34  {
35  m_zdeflate.zalloc = Z_NULL;
36  m_zdeflate.zfree = Z_NULL;
37  m_zdeflate.opaque = Z_NULL;
38  m_zinflate.avail_in = 0;
39  m_zinflate.next_in = Z_NULL;
40  ret = deflateInit( &m_zdeflate, Z_BEST_COMPRESSION/*Z_DEFAULT_COMPRESSION*/ );
41 
42  if( ret == Z_OK )
43  m_valid = true;
44  }
45  }
46 
48  {
49  inflateEnd( &m_zinflate );
50  deflateEnd( &m_zdeflate );
51  }
52 
53  void CompressionZlib::compress( const std::string& data )
54  {
55  if( !m_valid || !m_handler || data.empty() )
56  return;
57 
58  m_compressMutex.lock();
59 
60  int CHUNK = data.length() + ( data.length() / 100 ) + 13;
61  Bytef *out = new Bytef[CHUNK];
62  char *in = const_cast<char*>( data.c_str() );
63 
64  m_zdeflate.avail_in = data.length();
65  m_zdeflate.next_in = (Bytef*)in;
66 
67  int ret;
68  std::string result;
69  do {
70  m_zdeflate.avail_out = CHUNK;
71  m_zdeflate.next_out = (Bytef*)out;
72 
73  ret = deflate( &m_zdeflate, Z_SYNC_FLUSH );
74  result.append( (char*)out, CHUNK - m_zdeflate.avail_out );
75  } while( m_zdeflate.avail_out == 0 );
76 
77  delete[] out;
78 
79  m_compressMutex.unlock();
80 
81  m_handler->handleCompressedData( result );
82  }
83 
84  void CompressionZlib::decompress( const std::string& data )
85  {
86  if( !m_valid || !m_handler || data.empty() )
87  return;
88 
89  int CHUNK = 50;
90  char *out = new char[CHUNK];
91  char *in = const_cast<char*>( data.c_str() );
92 
93  m_zinflate.avail_in = data.length();
94  m_zinflate.next_in = (Bytef*)in;
95 
96  int ret = Z_OK;
97  std::string result;
98  do
99  {
100  m_zinflate.avail_out = CHUNK;
101  m_zinflate.next_out = (Bytef*)out;
102 
103  ret = inflate( &m_zinflate, Z_SYNC_FLUSH );
104  result.append( out, CHUNK - m_zinflate.avail_out );
105  } while( m_zinflate.avail_out == 0 );
106 
107  delete[] out;
108 
109  m_handler->handleDecompressedData( result );
110  }
111 
112 }
113 
114 #endif // HAVE_ZLIB