byteme
C++ wrappers for buffered inputs
Loading...
Searching...
No Matches
GzipFileReader.hpp
Go to the documentation of this file.
1#ifndef BYTEME_GZIP_FILE_READER_HPP
2#define BYTEME_GZIP_FILE_READER_HPP
3
4#include <cstddef>
5#include <stdexcept>
6#include <vector>
7#include <optional>
8
9#include "zlib.h"
10
11#include "check_buffer_size.hpp"
12#include "SelfClosingGzFile.hpp"
13#include "Reader.hpp"
14
21namespace byteme {
22
31 std::size_t buffer_size = 65536;
32
38 std::optional<unsigned> gzbuffer_size;
39};
40
46class GzipFileReader final : public Reader {
47public:
52 GzipFileReader(const char* path, const GzipFileReaderOptions& options) :
53 my_gzfile(path, "rb"),
54 my_buffer(
55 check_buffer_size<int>( // constrained for the gzread return type.
56 check_buffer_size<unsigned>( // constrained for the gzread argument type.
57 check_buffer_size(options.buffer_size)
58 )
59 )
60 )
61 {
62 set_optional_gzbuffer_size(my_gzfile, options.gzbuffer_size);
63 }
64
65public:
66 bool load() {
67 if (my_finished) {
68 // We need to check the status explicitly because gzread()
69 // doesn't return an error for a truncated file.
70 check_status();
71 return false;
72 }
73
74 const std::size_t bufsize = my_buffer.size();
75 auto ret = gzread(my_gzfile.handle, my_buffer.data(), bufsize);
76 if (ret < 0) {
77 check_status();
78 return false;
79 }
80
81 my_read = ret;
82 my_finished = (my_read < bufsize);
83 return true;
84 }
85
86 const unsigned char* buffer() const {
87 return my_buffer.data();
88 }
89
90 std::size_t available() const {
91 return my_read;
92 }
93
94private:
95 SelfClosingGzFile my_gzfile;
96 std::vector<unsigned char> my_buffer;
97 std::size_t my_read = 0;
98 bool my_finished = false;
99
100 void check_status() {
101 int status;
102 auto msg = gzerror(my_gzfile.handle, &status);
103 if (status != Z_OK) {
104 throw std::runtime_error(msg);
105 }
106 }
107
108};
109
110}
111
112#endif
Read an input source.
Read uncompressed bytes from a Gzip-compressed file.
Definition GzipFileReader.hpp:46
std::size_t available() const
Definition GzipFileReader.hpp:90
const unsigned char * buffer() const
Definition GzipFileReader.hpp:86
bool load()
Definition GzipFileReader.hpp:66
GzipFileReader(const char *path, const GzipFileReaderOptions &options)
Definition GzipFileReader.hpp:52
Virtual class for reading bytes from a source.
Definition Reader.hpp:17
Simple byte readers and writers.
Options for GzipFileReader construction.
Definition GzipFileReader.hpp:26
std::size_t buffer_size
Definition GzipFileReader.hpp:31
std::optional< unsigned > gzbuffer_size
Definition GzipFileReader.hpp:38