#define XERR "memorybuf"
#include "memorybuf.ih"

// overrides
streamsize MemoryBuf::xsgetn(char *buf, streamsize nChars)
{
    size_t toRead = nChars;
    size_t nRead = 0;
    char *endReadPtr = d_bridge.endReadPtr();

    while (toRead)
    {
        size_t avail = egptr() - gptr();    // available buffer space

                                            // no or empty memory buffer
                                            // but no more readable chars
        if (avail == 0 and underflow() == EOF)
            return nRead;

        avail = endReadPtr - d_bridge.offsetPtr();
        size_t next = min(avail, toRead);       // next #bytes to write

        memcpy(buf, gptr(), next);              // write to the buffer
        gbump(next);                            // update gptr

        toRead -= next;

        buf += next;      
        nRead += next;
        d_bridge.offset(d_bridge.offset() + next);
    }

    d_last = READ;

    return nRead;
}

