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