ReadSource

A ReadSource represents a source of data that can be read into caller-provided buffers. Data is obtained by calling the read member function one or more times, until it sets error::eof in the error code to indicate no more data is available.

Read sources are useful for representing streaming data sources where the complete data may not be available in memory, such as file streams or generated data.

Requirements

  • S denotes a read source class.

  • s denotes a value of type S.

  • c denotes a (possibly const) value of type S.

  • ec denotes a value of type system::error_code&.

  • M denotes a type meeting the requirements for MutableBufferSequence.

  • m denotes a value of type M const&.

Expression Type Semantics, Pre/Post-conditions

s.read(m, ec)

std::size_t

Reads data from the source into the mutable buffer sequence m. Returns the number of bytes written to the buffers. When no more data is available, error::eof is set in ec. On success, ec is cleared.

c.size() (optional)

std::uint64_t

Returns the total size, in bytes, of the data that can be read from the source. This member is optional. The metafunction has_size may be used to detect its availability.

s.rewind() (optional)

Resets the source to its initial state, allowing the data to be read again from the beginning. This member is optional. The metafunction has_rewind may be used to detect its availability.

Example

struct my_read_source
{
    std::string data_;
    std::size_t pos_ = 0;

    explicit my_read_source(std::string s)
        : data_(std::move(s))
    {
    }

    std::uint64_t size() const noexcept
    {
        return data_.size();
    }

    void rewind()
    {
        pos_ = 0;
    }

    template<class MutableBufferSequence>
    std::size_t read(
        MutableBufferSequence const& buffers,
        system::error_code& ec)
    {
        std::size_t n = buffers::copy(
            buffers,
            const_buffer(
                data_.data() + pos_,
                data_.size() - pos_));
        pos_ += n;
        if(pos_ >= data_.size())
            ec = error::eof;
        else
            ec = {};
        return n;
    }
};

static_assert(is_read_source<my_read_source>::value, "");
static_assert(has_size<my_read_source>::value, "");
static_assert(has_rewind<my_read_source>::value, "");

See Also

  • any_source - a type-erased wrapper that can hold either a ReadSource or DataSource

  • DataSource - a concept for in-memory data sources