1 // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
2 // (C) Copyright 2003-2007 Jonathan Turkanis
3 // Distributed under the Boost Software License, Version 1.0. (See accompanying
4 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
5 
6 // See http://www.boost.org/libs/iostreams for documentation.
7 
8 // Note: custom allocators are not supported on VC6, since that compiler
9 // had trouble finding the function zlib_base::do_init.
10 
11 #ifndef BOOST_IOSTREAMS_ZLIB_HPP_INCLUDED
12 #define BOOST_IOSTREAMS_ZLIB_HPP_INCLUDED
13 
14 #if defined(_MSC_VER) && (_MSC_VER >= 1020)
15 # pragma once
16 #endif
17 
18 #include <cassert>
19 #include <iosfwd>            // streamsize.
20 #include <memory>            // allocator, bad_alloc.
21 #include <new>
22 #include <boost/config.hpp>  // MSVC, STATIC_CONSTANT, DEDUCED_TYPENAME, DINKUM.
23 #include <boost/cstdint.hpp> // uint*_t
24 #include <boost/detail/workaround.hpp>
25 #include <boost/iostreams/constants.hpp>   // buffer size.
26 #include <boost/iostreams/detail/config/auto_link.hpp>
27 #include <boost/iostreams/detail/config/dyn_link.hpp>
28 #include <boost/iostreams/detail/config/wide_streams.hpp>
29 #include <boost/iostreams/detail/config/zlib.hpp>
30 #include <boost/iostreams/detail/ios.hpp>  // failure, streamsize.
31 #include <boost/iostreams/filter/symmetric.hpp>
32 #include <boost/iostreams/pipeline.hpp>
33 #include <boost/type_traits/is_same.hpp>
34 
35 // Must come last.
36 #ifdef BOOST_MSVC
37 # pragma warning(push)
38 # pragma warning(disable:4251 4231 4660)         // Dependencies not exported.
39 #endif
40 #include <boost/config/abi_prefix.hpp>
41 
42 namespace boost { namespace iostreams {
43 
44 namespace zlib {
45                     // Typedefs
46 
47 typedef uint32_t uint;
48 typedef uint8_t byte;
49 typedef uint32_t ulong;
50 
51 // Prefix 'x' prevents symbols from being redefined when Z_PREFIX is defined
52 typedef void* (*xalloc_func)(void*, zlib::uint, zlib::uint);
53 typedef void (*xfree_func)(void*, void*);
54 
55                     // Compression levels
56 
57 BOOST_IOSTREAMS_DECL extern const int no_compression;
58 BOOST_IOSTREAMS_DECL extern const int best_speed;
59 BOOST_IOSTREAMS_DECL extern const int best_compression;
60 BOOST_IOSTREAMS_DECL extern const int default_compression;
61 
62                     // Compression methods
63 
64 BOOST_IOSTREAMS_DECL extern const int deflated;
65 
66                     // Compression strategies
67 
68 BOOST_IOSTREAMS_DECL extern const int default_strategy;
69 BOOST_IOSTREAMS_DECL extern const int filtered;
70 BOOST_IOSTREAMS_DECL extern const int huffman_only;
71 
72                     // Status codes
73 
74 BOOST_IOSTREAMS_DECL extern const int okay;
75 BOOST_IOSTREAMS_DECL extern const int stream_end;
76 BOOST_IOSTREAMS_DECL extern const int stream_error;
77 BOOST_IOSTREAMS_DECL extern const int version_error;
78 BOOST_IOSTREAMS_DECL extern const int data_error;
79 BOOST_IOSTREAMS_DECL extern const int mem_error;
80 BOOST_IOSTREAMS_DECL extern const int buf_error;
81 
82                     // Flush codes
83 
84 BOOST_IOSTREAMS_DECL extern const int finish;
85 BOOST_IOSTREAMS_DECL extern const int no_flush;
86 BOOST_IOSTREAMS_DECL extern const int sync_flush;
87 
88                     // Code for current OS
89 
90 //BOOST_IOSTREAMS_DECL extern const int os_code;
91 
92                     // Null pointer constant.
93 
94 const int null                               = 0;
95 
96                     // Default values
97 
98 const int default_window_bits                = 15;
99 const int default_mem_level                  = 8;
100 const bool default_crc                       = false;
101 const bool default_noheader                  = false;
102 
103 } // End namespace zlib.
104 
105 //
106 // Class name: zlib_params.
107 // Description: Encapsulates the parameters passed to deflateInit2
108 //      and inflateInit2 to customize compression and decompression.
109 //
110 struct zlib_params {
111 
112     // Non-explicit constructor.
zlib_paramsboost::iostreams::zlib_params113     zlib_params( int level           = zlib::default_compression,
114                  int method          = zlib::deflated,
115                  int window_bits     = zlib::default_window_bits,
116                  int mem_level       = zlib::default_mem_level,
117                  int strategy        = zlib::default_strategy,
118                  bool noheader       = zlib::default_noheader,
119                  bool calculate_crc  = zlib::default_crc )
120         : level(level), method(method), window_bits(window_bits),
121           mem_level(mem_level), strategy(strategy),
122           noheader(noheader), calculate_crc(calculate_crc)
123         { }
124     int level;
125     int method;
126     int window_bits;
127     int mem_level;
128     int strategy;
129     bool noheader;
130     bool calculate_crc;
131 };
132 
133 //
134 // Class name: zlib_error.
135 // Description: Subclass of std::ios::failure thrown to indicate
136 //     zlib errors other than out-of-memory conditions.
137 //
138 class BOOST_IOSTREAMS_DECL zlib_error : public BOOST_IOSTREAMS_FAILURE {
139 public:
140     explicit zlib_error(int error);
error() const141     int error() const { return error_; }
142     static void check BOOST_PREVENT_MACRO_SUBSTITUTION(int error);
143 private:
144     int error_;
145 };
146 
147 namespace detail {
148 
149 template<typename Alloc>
150 struct zlib_allocator_traits {
151 #ifndef BOOST_NO_STD_ALLOCATOR
152     typedef typename Alloc::template rebind<char>::other type;
153 #else
154     typedef std::allocator<char> type;
155 #endif
156 };
157 
158 template< typename Alloc,
159           typename Base = // VC6 workaround (C2516)
160               BOOST_DEDUCED_TYPENAME zlib_allocator_traits<Alloc>::type >
161 struct zlib_allocator : private Base {
162 private:
163     typedef typename Base::size_type size_type;
164 public:
165     BOOST_STATIC_CONSTANT(bool, custom =
166         (!is_same<std::allocator<char>, Base>::value));
167     typedef typename zlib_allocator_traits<Alloc>::type allocator_type;
168     static void* allocate(void* self, zlib::uint items, zlib::uint size);
169     static void deallocate(void* self, void* address);
170 };
171 
172 class BOOST_IOSTREAMS_DECL zlib_base {
173 public:
174     typedef char char_type;
175 protected:
176     zlib_base();
177     ~zlib_base();
stream()178     void* stream() { return stream_; }
179     template<typename Alloc>
init(const zlib_params & p,bool compress,zlib_allocator<Alloc> & zalloc)180     void init( const zlib_params& p,
181                bool compress,
182                zlib_allocator<Alloc>& zalloc )
183         {
184             bool custom = zlib_allocator<Alloc>::custom;
185             do_init( p, compress,
186                      #if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
187                          custom ? zlib_allocator<Alloc>::allocate : 0,
188                          custom ? zlib_allocator<Alloc>::deallocate : 0,
189                      #endif
190                      &zalloc );
191         }
192     void before( const char*& src_begin, const char* src_end,
193                  char*& dest_begin, char* dest_end );
194     void after( const char*& src_begin, char*& dest_begin,
195                 bool compress );
196     int xdeflate(int flush);  // Prefix 'x' prevents symbols from being
197     int xinflate(int flush);  // redefined when Z_PREFIX is defined
198     void reset(bool compress, bool realloc);
199 public:
crc() const200     zlib::ulong crc() const { return crc_; }
total_in() const201     int total_in() const { return total_in_; }
total_out() const202     int total_out() const { return total_out_; }
203 private:
204     void do_init( const zlib_params& p, bool compress,
205                   #if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
206                       zlib::xalloc_func,
207                       zlib::xfree_func,
208                   #endif
209                   void* derived );
210     void*        stream_;         // Actual type: z_stream*.
211     bool         calculate_crc_;
212     zlib::ulong  crc_;
213     zlib::ulong  crc_imp_;
214     int          total_in_;
215     int          total_out_;
216 };
217 
218 //
219 // Template name: zlib_compressor_impl
220 // Description: Model of C-Style Filte implementing compression by
221 //      delegating to the zlib function deflate.
222 //
223 template<typename Alloc = std::allocator<char> >
224 class zlib_compressor_impl : public zlib_base, public zlib_allocator<Alloc> {
225 public:
226     zlib_compressor_impl(const zlib_params& = zlib::default_compression);
227     ~zlib_compressor_impl();
228     bool filter( const char*& src_begin, const char* src_end,
229                  char*& dest_begin, char* dest_end, bool flush );
230     void close();
231 };
232 
233 //
234 // Template name: zlib_compressor
235 // Description: Model of C-Style Filte implementing decompression by
236 //      delegating to the zlib function inflate.
237 //
238 template<typename Alloc = std::allocator<char> >
239 class zlib_decompressor_impl : public zlib_base, public zlib_allocator<Alloc> {
240 public:
241     zlib_decompressor_impl(const zlib_params&);
242     zlib_decompressor_impl(int window_bits = zlib::default_window_bits);
243     ~zlib_decompressor_impl();
244     bool filter( const char*& begin_in, const char* end_in,
245                  char*& begin_out, char* end_out, bool flush );
246     void close();
eof() const247     bool eof() const { return eof_; }
248 private:
249     bool eof_;
250 };
251 
252 } // End namespace detail.
253 
254 //
255 // Template name: zlib_compressor
256 // Description: Model of InputFilter and OutputFilter implementing
257 //      compression using zlib.
258 //
259 template<typename Alloc = std::allocator<char> >
260 struct basic_zlib_compressor
261     : symmetric_filter<detail::zlib_compressor_impl<Alloc>, Alloc>
262 {
263 private:
264     typedef detail::zlib_compressor_impl<Alloc>         impl_type;
265     typedef symmetric_filter<impl_type, Alloc>  base_type;
266 public:
267     typedef typename base_type::char_type               char_type;
268     typedef typename base_type::category                category;
269     basic_zlib_compressor( const zlib_params& = zlib::default_compression,
270                            int buffer_size = default_device_buffer_size );
crcboost::iostreams::basic_zlib_compressor271     zlib::ulong crc() { return this->filter().crc(); }
total_inboost::iostreams::basic_zlib_compressor272     int total_in() {  return this->filter().total_in(); }
273 };
274 BOOST_IOSTREAMS_PIPABLE(basic_zlib_compressor, 1)
275 
276 typedef basic_zlib_compressor<> zlib_compressor;
277 
278 //
279 // Template name: zlib_decompressor
280 // Description: Model of InputFilter and OutputFilter implementing
281 //      decompression using zlib.
282 //
283 template<typename Alloc = std::allocator<char> >
284 struct basic_zlib_decompressor
285     : symmetric_filter<detail::zlib_decompressor_impl<Alloc>, Alloc>
286 {
287 private:
288     typedef detail::zlib_decompressor_impl<Alloc>       impl_type;
289     typedef symmetric_filter<impl_type, Alloc>  base_type;
290 public:
291     typedef typename base_type::char_type               char_type;
292     typedef typename base_type::category                category;
293     basic_zlib_decompressor( int window_bits = zlib::default_window_bits,
294                              int buffer_size = default_device_buffer_size );
295     basic_zlib_decompressor( const zlib_params& p,
296                              int buffer_size = default_device_buffer_size );
crcboost::iostreams::basic_zlib_decompressor297     zlib::ulong crc() { return this->filter().crc(); }
total_outboost::iostreams::basic_zlib_decompressor298     int total_out() {  return this->filter().total_out(); }
eofboost::iostreams::basic_zlib_decompressor299     bool eof() { return this->filter().eof(); }
300 };
301 BOOST_IOSTREAMS_PIPABLE(basic_zlib_decompressor, 1)
302 
303 typedef basic_zlib_decompressor<> zlib_decompressor;
304 
305 //----------------------------------------------------------------------------//
306 
307 //------------------Implementation of zlib_allocator--------------------------//
308 
309 namespace detail {
310 
311 template<typename Alloc, typename Base>
allocate(void * self,zlib::uint items,zlib::uint size)312 void* zlib_allocator<Alloc, Base>::allocate
313     (void* self, zlib::uint items, zlib::uint size)
314 {
315     size_type len = items * size;
316     char* ptr =
317         static_cast<allocator_type*>(self)->allocate
318             (len + sizeof(size_type)
319             #if BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, == 1)
320                 , (char*)0
321             #endif
322             );
323     *reinterpret_cast<size_type*>(ptr) = len;
324     return ptr + sizeof(size_type);
325 }
326 
327 template<typename Alloc, typename Base>
deallocate(void * self,void * address)328 void zlib_allocator<Alloc, Base>::deallocate(void* self, void* address)
329 {
330     char* ptr = reinterpret_cast<char*>(address) - sizeof(size_type);
331     size_type len = *reinterpret_cast<size_type*>(ptr) + sizeof(size_type);
332     static_cast<allocator_type*>(self)->deallocate(ptr, len);
333 }
334 
335 //------------------Implementation of zlib_compressor_impl--------------------//
336 
337 template<typename Alloc>
zlib_compressor_impl(const zlib_params & p)338 zlib_compressor_impl<Alloc>::zlib_compressor_impl(const zlib_params& p)
339 { init(p, true, static_cast<zlib_allocator<Alloc>&>(*this)); }
340 
341 template<typename Alloc>
~zlib_compressor_impl()342 zlib_compressor_impl<Alloc>::~zlib_compressor_impl()
343 { reset(true, false); }
344 
345 template<typename Alloc>
filter(const char * & src_begin,const char * src_end,char * & dest_begin,char * dest_end,bool flush)346 bool zlib_compressor_impl<Alloc>::filter
347     ( const char*& src_begin, const char* src_end,
348       char*& dest_begin, char* dest_end, bool flush )
349 {
350     before(src_begin, src_end, dest_begin, dest_end);
351     int result = xdeflate(flush ? zlib::finish : zlib::no_flush);
352     after(src_begin, dest_begin, true);
353     zlib_error::check BOOST_PREVENT_MACRO_SUBSTITUTION(result);
354     return result != zlib::stream_end;
355 }
356 
357 template<typename Alloc>
close()358 void zlib_compressor_impl<Alloc>::close() { reset(true, true); }
359 
360 //------------------Implementation of zlib_decompressor_impl------------------//
361 
362 template<typename Alloc>
zlib_decompressor_impl(const zlib_params & p)363 zlib_decompressor_impl<Alloc>::zlib_decompressor_impl(const zlib_params& p)
364   : eof_(false)
365 { init(p, false, static_cast<zlib_allocator<Alloc>&>(*this)); }
366 
367 template<typename Alloc>
~zlib_decompressor_impl()368 zlib_decompressor_impl<Alloc>::~zlib_decompressor_impl()
369 { reset(false, false); }
370 
371 template<typename Alloc>
zlib_decompressor_impl(int window_bits)372 zlib_decompressor_impl<Alloc>::zlib_decompressor_impl(int window_bits)
373 {
374     zlib_params p;
375     p.window_bits = window_bits;
376     init(p, false, static_cast<zlib_allocator<Alloc>&>(*this));
377 }
378 
379 template<typename Alloc>
filter(const char * & src_begin,const char * src_end,char * & dest_begin,char * dest_end,bool)380 bool zlib_decompressor_impl<Alloc>::filter
381     ( const char*& src_begin, const char* src_end,
382       char*& dest_begin, char* dest_end, bool /* flush */ )
383 {
384     before(src_begin, src_end, dest_begin, dest_end);
385     int result = xinflate(zlib::sync_flush);
386     after(src_begin, dest_begin, false);
387     zlib_error::check BOOST_PREVENT_MACRO_SUBSTITUTION(result);
388     return !(eof_ = result == zlib::stream_end);
389 }
390 
391 template<typename Alloc>
close()392 void zlib_decompressor_impl<Alloc>::close() {
393     eof_ = false;
394     reset(false, true);
395 }
396 
397 } // End namespace detail.
398 
399 //------------------Implementation of zlib_decompressor-----------------------//
400 
401 template<typename Alloc>
basic_zlib_compressor(const zlib_params & p,int buffer_size)402 basic_zlib_compressor<Alloc>::basic_zlib_compressor
403     (const zlib_params& p, int buffer_size)
404     : base_type(buffer_size, p) { }
405 
406 //------------------Implementation of zlib_decompressor-----------------------//
407 
408 template<typename Alloc>
basic_zlib_decompressor(int window_bits,int buffer_size)409 basic_zlib_decompressor<Alloc>::basic_zlib_decompressor
410     (int window_bits, int buffer_size)
411     : base_type(buffer_size, window_bits) { }
412 
413 template<typename Alloc>
basic_zlib_decompressor(const zlib_params & p,int buffer_size)414 basic_zlib_decompressor<Alloc>::basic_zlib_decompressor
415     (const zlib_params& p, int buffer_size)
416     : base_type(buffer_size, p) { }
417 
418 //----------------------------------------------------------------------------//
419 
420 } } // End namespaces iostreams, boost.
421 
422 #include <boost/config/abi_suffix.hpp> // Pops abi_suffix.hpp pragmas.
423 #ifdef BOOST_MSVC
424 # pragma warning(pop)
425 #endif
426 
427 #endif // #ifndef BOOST_IOSTREAMS_ZLIB_HPP_INCLUDED
428