]> git.tdb.fi Git - libs/core.git/blob - source/io/zlibcompressed.h
Avoid invoking callbacks of a deleted object
[libs/core.git] / source / io / zlibcompressed.h
1 #ifndef MSP_IO_ZLIBCOMPRESSED_H_
2 #define MSP_IO_ZLIBCOMPRESSED_H_
3
4 #include <stdexcept>
5 #include <string>
6 #include <sigc++/trackable.h>
7 #include "base.h"
8
9 namespace Msp {
10 namespace IO {
11
12 class zlib_error: public std::runtime_error
13 {
14 private:
15         int code_;
16
17 public:
18         zlib_error(const std::string &, int);
19         ~zlib_error() throw() { }
20
21         int code() const throw() { return code_; }
22 };
23
24 /**
25 Compresses or decompresses data with zlib.  This class is a filter that
26 operates on top of another I/O object.
27
28 To ensure proper termination of the compressed data stream, the ZlibCompressed
29 object must be destroyed before the underlying object is closed.
30 */
31 class ZlibCompressed: public Base, public sigc::trackable
32 {
33 private:
34         struct Private;
35
36         Base &below;
37         unsigned buffer_size;
38         unsigned char *in_buffer;
39         unsigned char *out_buffer;
40         bool stream_end;
41         Private *priv;
42
43 public:
44         /** Creates a zlib de/compression object.  The underlying object must be
45         open for reading or writing, not both.  The level parameter determines
46         compression quality, ranging from 1 (fastest) to 9 (best compression). */
47         ZlibCompressed(Base &, unsigned level = 9);
48
49         virtual ~ZlibCompressed();
50
51         void flush();
52
53 protected:
54         virtual unsigned do_write(const char *, unsigned);
55
56 private:
57         /** Compresses data and writes it to the underlying object.  Returns true if
58         progress was made, false otherwise.  flush_mode can be any of zlib's flush
59         modes.  If it is Z_FINISH, false is also returned when the stream has been
60         terminated. */
61         bool compress_data(int flush_mode);
62
63 public:
64         virtual unsigned do_read(char *, unsigned);
65 };
66
67 } // namespace IO
68 } // namespace Msp
69
70 #endif