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

#include <bobcat/exception>

// overrides
int MemoryBuf::overflow(int ch)
{
    if (not (d_mode & (ios::trunc | ios::out))) // writing must be OK
        return EOF;

    if (d_mode & ios::app)
        seekoff(0, ios::end);

    streamsize offset = getOffset();

    if (offset >= d_bridge.maxEnd())
        d_bridge.extend();

    d_bridge.load();                        // load offset's segment
    setp(d_bridge.beginPtr(), d_bridge.endPtr());
    pbump(offset - d_bridge.blockBegin());

//xerr("offset " << d_bridge.offset() << " points to " << 
//(void *)d_bridge.beginPtr() << " to " << (void *)d_bridge.endPtr() );

    *pptr() = ch;

//xerr("offset " << d_bridge.offset() << " points to " << 
//(void *)d_bridge.beginPtr() << " contains " << *d_bridge.beginPtr() );
    pbump(1);
    d_bridge.offset(++offset);



    d_bridge.writtenUntil(offset);

    d_last = WRITE;
    return static_cast<unsigned char>(ch);
}
