]> git.tdb.fi Git - libs/core.git/blob - source/io/zlibcompressed.h
The EOF logic wasn't quite correct
[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         bool stream_end;
40         Private *priv;
41
42 public:
43         /** Creates a zlib de/compression object.  The underlying object must be
44         open for reading or writing, not both.  The level parameter determines
45         compression quality, ranging from 1 (fastest) to 9 (best compression). */
46         ZlibCompressed(Base &, unsigned level = 9);
47
48         virtual ~ZlibCompressed();
49
50         void flush();
51
52 protected:
53         virtual unsigned do_write(const char *, unsigned);
54
55 private:
56         /** Compresses data and writes it to the underlying object.  Returns true if
57         progress was made, false otherwise.  flush_mode can be any of zlib's flush
58         modes.  If it is Z_FINISH, false is also returned when the stream has been
59         terminated. */
60         bool compress_data(int flush_mode);
61
62 public:
63         virtual unsigned do_read(char *, unsigned);
64 };
65
66 } // namespace IO
67 } // namespace Msp
68
69 #endif