byteme
C++ wrappers for buffered inputs
Loading...
Searching...
No Matches
GzipFileWriter.hpp
Go to the documentation of this file.
1#ifndef BYTEME_GZIP_FILE_WRITER_HPP
2#define BYTEME_GZIP_FILE_WRITER_HPP
3
4#include <stdexcept>
5#include <vector>
6#include <optional>
7
8#include "Writer.hpp"
9#include "check_buffer_size.hpp"
10
17namespace byteme {
18
28
34 std::optional<unsigned> gzbuffer_size;
35};
36
42class GzipFileWriter final : public Writer {
43public:
48 GzipFileWriter(const char* path, const GzipFileWriterOptions& options) : my_gzfile(path, "wb") {
49 set_optional_gzbuffer_size(my_gzfile, options.gzbuffer_size);
50 if (gzsetparams(my_gzfile.handle, options.compression_level, Z_DEFAULT_STRATEGY) != Z_OK) {
51 throw std::runtime_error("failed to set the Gzip compression parameters");
52 }
53 }
54
55public:
56 using Writer::write;
57
58 void write(const unsigned char* buffer, std::size_t n) {
59 safe_write<unsigned, true>(
60 buffer,
61 n,
62 [&](const unsigned char* buffer0, unsigned n0) -> void {
63 auto ok = gzwrite(my_gzfile.handle, buffer0, n0);
64 if (ok <= 0) {
65 throw std::runtime_error("failed to write to the Gzip-compressed file");
66 }
67 }
68 );
69 }
70
71 void finish() {
72 my_gzfile.closed = true;
73 if (gzclose(my_gzfile.handle) != Z_OK) {
74 throw std::runtime_error("failed to close the Gzip-compressed file after writing");
75 }
76 }
77
78private:
79 SelfClosingGzFile my_gzfile;
80};
81
82}
83
84#endif
Write to an output sink.
Write uncompressed bytes to a Gzip-compressed file.
Definition GzipFileWriter.hpp:42
void write(const unsigned char *buffer, std::size_t n)
Definition GzipFileWriter.hpp:58
GzipFileWriter(const char *path, const GzipFileWriterOptions &options)
Definition GzipFileWriter.hpp:48
void finish()
Definition GzipFileWriter.hpp:71
Virtual class for writing bytes to a sink.
Definition Writer.hpp:21
virtual void write(const unsigned char *buffer, std::size_t n)=0
Simple byte readers and writers.
Options for GzipFileWriter construction.
Definition GzipFileWriter.hpp:22
int compression_level
Definition GzipFileWriter.hpp:27
std::optional< unsigned > gzbuffer_size
Definition GzipFileWriter.hpp:34