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