byteme
Read/write bytes from various sources
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 "utils.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 // File closing is done automatically in the SelfClosingGzFile destructor.
73 // So, there's no need to call it manually in our destructor.
74 my_gzfile.closed = true; // set it before gzclose; if the latter fails, we don't try again in the destructor.
75 if (gzclose(my_gzfile.handle) != Z_OK) {
76 throw std::runtime_error("failed to close the Gzip-compressed file");
77 }
78 }
79
80private:
81 SelfClosingGzFile my_gzfile;
82};
83
84}
85
86#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.
Definition BufferedReader.hpp:21
Options for GzipFileWriter construction.
Definition GzipFileWriter.hpp:22
int compression_level
Definition GzipFileWriter.hpp:27
std::optional< unsigned > gzbuffer_size
Definition GzipFileWriter.hpp:34