]> git.tdb.fi Git - libs/core.git/blobdiff - source/io/zlibcompressed.h
Add support for de/compression with zlib
[libs/core.git] / source / io / zlibcompressed.h
diff --git a/source/io/zlibcompressed.h b/source/io/zlibcompressed.h
new file mode 100644 (file)
index 0000000..1ee4274
--- /dev/null
@@ -0,0 +1,68 @@
+#ifndef MSP_IO_ZLIBCOMPRESSED_H_
+#define MSP_IO_ZLIBCOMPRESSED_H_
+
+#include <stdexcept>
+#include <string>
+#include "base.h"
+
+namespace Msp {
+namespace IO {
+
+class zlib_error: public std::runtime_error
+{
+private:
+       int code_;
+
+public:
+       zlib_error(const std::string &, int);
+       ~zlib_error() throw() { }
+
+       int code() const throw() { return code_; }
+};
+
+/**
+Compresses or decompresses data with zlib.  This class is a filter that
+operates on top of another I/O object.
+
+To ensure proper termination of the compressed data stream, the ZlibCompressed
+object must be destroyed before the underlying object is closed.
+*/
+class ZlibCompressed: public Base
+{
+private:
+       struct Private;
+
+       Base &below;
+       unsigned buffer_size;
+       unsigned char *in_buffer;
+       unsigned char *out_buffer;
+       Private *priv;
+
+public:
+       /** Creates a zlib de/compression object.  The underlying object must be
+       open for reading or writing, not both.  The level parameter determines
+       compression quality, ranging from 1 (fastest) to 9 (best compression). */
+       ZlibCompressed(Base &, unsigned level = 9);
+
+       virtual ~ZlibCompressed();
+
+       void flush();
+
+protected:
+       virtual unsigned do_write(const char *, unsigned);
+
+private:
+       /** Compresses data and writes it to the underlying object.  Returns true if
+       progress was made, false otherwise.  flush_mode can be any of zlib's flush
+       modes.  If it is Z_FINISH, false is also returned when the stream has been
+       terminated. */
+       bool compress_data(int flush_mode);
+
+public:
+       virtual unsigned do_read(char *, unsigned);
+};
+
+} // namespace IO
+} // namespace Msp
+
+#endif