]> git.tdb.fi Git - libs/core.git/blob - source/io/zlibcompressed.h
Use nullptr instead of 0 for pointers
[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 m_code;
16
17 public:
18         zlib_error(const std::string &, int);
19         virtual ~zlib_error() throw() = default;
20
21         int code() const throw() { return m_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         std::size_t buffer_size = 1024;
38         unsigned char *in_buffer = nullptr;
39         unsigned char *out_buffer = nullptr;
40         bool stream_end = false;
41         Private *priv = nullptr;
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 &b, unsigned level = 9): ZlibCompressed(b, b.get_mode()&M_RDWR, level) { }
48
49         /** Creates a zlib de/compression object.  Mode must be either read or
50         write, and compatible with the underlying object. */
51         ZlibCompressed(Base &, Mode, unsigned level = 9);
52
53         virtual ~ZlibCompressed();
54
55         virtual void set_block(bool);
56         virtual void set_inherit(bool);
57
58         void flush();
59
60 protected:
61         virtual std::size_t do_write(const char *, std::size_t);
62
63 private:
64         /** Compresses data and writes it to the underlying object.  Returns true if
65         progress was made, false otherwise.  flush_mode can be any of zlib's flush
66         modes.  If it is Z_FINISH, false is also returned when the stream has been
67         terminated. */
68         bool compress_data(int flush_mode);
69
70 public:
71         virtual std::size_t do_read(char *, std::size_t);
72
73         virtual const Handle &get_handle(Mode);
74 };
75
76 } // namespace IO
77 } // namespace Msp
78
79 #endif