byteme
Read/write bytes from various sources
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 "SelfClosingGzFile.hpp"
12#include "Reader.hpp"
13#include "utils.hpp"
14
21namespace byteme {
22
32 std::optional<unsigned> buffer_size;
33};
34
40class GzipFileReader final : public Reader {
41public:
46 GzipFileReader(const char* path, const GzipFileReaderOptions& options) : my_gzfile(path, "rb") {
47 set_optional_gzbuffer_size(my_gzfile, options.buffer_size);
48 }
49
50public:
51 std::size_t read(unsigned char* buffer, std::size_t n) {
52 // While gzbuffer and gzread accepts 'unsigned', the output number of bytes is actually an 'int'!
53 // Moreover, if the requested 'len' can't fit in an 'int', gzread will throw an error -
54 // see comments on the return value for gzread at https://www.zlib.net/manual.html.
55 // So, we forcibly cap the length to 'int'.
56 return safe_read<int>(buffer, n, [this](unsigned char* buffer, int n) -> int {
57 const auto ret = gzread(this->my_gzfile.handle, buffer, n);
58 if (ret < n) {
59 int status;
60 const auto msg = gzerror(this->my_gzfile.handle, &status);
61 if (status != Z_OK) {
62 throw std::runtime_error(msg);
63 }
64 }
65 return ret;
66 });
67 }
68
69private:
70 SelfClosingGzFile my_gzfile;
71};
72
73}
74
75#endif
Read an input source.
Read uncompressed bytes from a Gzip-compressed file.
Definition GzipFileReader.hpp:40
std::size_t read(unsigned char *buffer, std::size_t n)
Definition GzipFileReader.hpp:51
GzipFileReader(const char *path, const GzipFileReaderOptions &options)
Definition GzipFileReader.hpp:46
Virtual class for reading bytes from a source.
Definition Reader.hpp:17
Simple byte readers and writers.
Definition BufferedReader.hpp:21
Options for GzipFileReader construction.
Definition GzipFileReader.hpp:26
std::optional< unsigned > buffer_size
Definition GzipFileReader.hpp:32