Search code examples
c++boostboost-iostreams

Trying to access source device from boost::iostreams


I wrote a custom source device that counts the bytes read so far:

class socket_stream_source : public boost::iostreams::source
{
public:

    int readSoFar=0;

    socket_stream_source(socket_ptr sock) : _sock(sock)
    {

    }

    std::streamsize read(char* s, std::streamsize n)
    {
        int readCount = _sock->read_some(boost::asio::buffer(s, n));
        readSoFar += readCount;
        return readCount;
    }

private:
    socket_ptr _sock;

};

I'm using it like this:

boost::iostreams::stream<socket_stream_source> in(sock);

How can I access my readSoFar variable ?

Or is there another way to count the bytes read so far from an istream ?


Solution

  • Just use the device access operators provided by boost::iostreams::stream, i.e.

    T& operator*();
    T* operator->();
    

    In your code this suffice:

    in->readSoFar;