Writing output stream with sink - novalexei/nstream GitHub Wiki

Writing output stream with sink.

In order to write your own output stream with nova::stream you'll need to write sink class. The sink class has the following requirements:

  • It should have type definitions for character type and for category (which in this case is always sink):
typedef sink                   category;
typedef /* character type */   char_type;
  • It should implement the following methods:
std::streamsize write(const char_type* s, std::streamsize n);
void flush();

Method write will attempt to write n characters from provided buffer s and return the number of bytes successfully written.

Method flush will flush the underlying stream or do nothing if the stream cannot be flushed.

Example.

Let's write simple replacement for std::ostringstream

#include <nova/io.h>

using namespace nova;

template<typename CharT>
class string_sink
{
public:
    typedef sink                          category;
    typedef CharT                         char_type;

    typedef std::basic_string<CharT>      string_type;

    std::streamsize write(const char_type* s, std::streamsize n)
    {
        _buffer.append(s, n);
        return n;
    }
    void flush() { }

    const string_type& view() const { return _buffer; }
private:
    string_type _buffer;
};

Looks self-explanatory so far? Let's use it.

int main()
{
    outstream<string_sink<char>> out;
    out << 123 << ' ' << 456;
    out.flush();
    std::cout << out->view() << std::endl;
    return 0;
}

This is it.

Buffering

Same as nova::instream nova::outstream accepts buffering as a second template argument (by default nova::outstream is unbuffered):

outstream<string_sink<char>, buffering<1024>> out;

nova::stream also provides a number of predefined classes for buffering:

outstream<string_sink<char>, buffer_1k> out;

To the next section: Writing input stream with in_buffer_provider

Back to the Tutorial

⚠️ **GitHub.com Fallback** ⚠️