byteme
Read/write bytes from various sources
Loading...
Searching...
No Matches
OstreamWriter.hpp
Go to the documentation of this file.
1#ifndef BYTEME_OSTREAM_WRITER_HPP
2#define BYTEME_OSTREAM_WRITER_HPP
3
4#include <memory>
5#include <stdexcept>
6#include <cstddef>
7
8#include "Writer.hpp"
9#include "utils.hpp"
10
17namespace byteme {
18
28template<class Pointer_>
29class OstreamWriter final : public Writer {
30public:
34 OstreamWriter(Pointer_ output) : my_output(std::move(output)) {}
35
40 try {
41 my_output->flush();
42 } catch (...) {
43 ; // don't allow exceptions to propagate out of this function, as destructors shouldn't throw.
44 }
45 }
50public:
51 using Writer::write;
52
53 void write(const unsigned char* buffer, std::size_t n) {
54 safe_write<std::streamsize, false>(
55 buffer,
56 n,
57 [&](const unsigned char* ptr0, std::streamsize n0) -> void {
58 my_output->write(reinterpret_cast<const char*>(ptr0), n0);
59 if (!(my_output->good())) {
60 throw std::runtime_error("failed to write to arbitrary output stream");
61 }
62 }
63 );
64 }
65
66 void finish() {
67 my_output->flush();
68 if (my_output->fail() || my_output->bad()) {
69 throw std::runtime_error("failed to flush to arbitrary output stream");
70 }
71 }
72
73private:
74 Pointer_ my_output;
75};
76
77}
78
79#endif
Write to an output sink.
Read bytes from a std::ostream.
Definition OstreamWriter.hpp:29
OstreamWriter(Pointer_ output)
Definition OstreamWriter.hpp:34
void write(const unsigned char *buffer, std::size_t n)
Definition OstreamWriter.hpp:53
void finish()
Definition OstreamWriter.hpp:66
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