File: OstreamWriter.hpp

package info (click to toggle)
r-bioc-alabaster.base 1.6.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,652 kB
  • sloc: cpp: 11,377; sh: 29; makefile: 2
file content (54 lines) | stat: -rw-r--r-- 1,228 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#ifndef BYTEME_OSTREAM_WRITER_HPP
#define BYTEME_OSTREAM_WRITER_HPP

#include <ostream>
#include <stdexcept>
#include "Writer.hpp"

/**
 * @file OstreamWriter.hpp
 *
 * @brief Write bytes to an arbitrary output stream.
 */

namespace byteme {

/**
 * @brief Read bytes from a `std::ostream`.
 *
 * @tparam Pointer_ A (possibly smart) pointer to an `std::ostream` object.
 *
 * This is just a wrapper around `std::ostream::write` for compatibility.
 */
template<class Pointer_ = std::ostream*>
class OstreamWriter : public Writer {
public:
    /**
     * @param output Pointer to an output stream.
     * This is assumed to live until `finish()` is called.
     */
    OstreamWriter(Pointer_ output) : ptr(std::move(output)) {}

    using Writer::write;

    void write(const unsigned char* buffer, size_t n) {
        ptr->write(reinterpret_cast<const char*>(buffer), n);
        if (!(ptr->good())) {
            throw std::runtime_error("failed to write to arbitrary output stream");
        }
    }

    void finish() {
        ptr->flush();
        if (ptr->fail() || ptr->bad()) {
            throw std::runtime_error("failed to flush to arbitrary output stream");
        }
    }

private:
    Pointer_ ptr;
};

}

#endif