streamsize StreamBuf::xsputn(char const *buf, streamsize nChars)
{
    size_t toWrite = nChars;
    size_t nWritten = 0;

    size_t offs = getOffset();
    size_t avail = epptr() - pptr();        // available buffer space

    while (toWrite)
    {
        if (avail == 0)                     // no space: try to reload
        {                                   // the buffer
            if (overflow(*buf) == EOF)      // storage space exhausted?
                break;                      // yes: done

            ++buf;                          // no: 1 byte was written
            ++nWritten;
            ++offs;

            --toWrite;

            avail = epptr() - pptr();       // remaining buffer space

            if (avail == 0)                 // next cycle if avail == 0
                continue;
        }

        size_t next = min(avail, toWrite);  // next #bytes to write

        memcpy(pptr(), buf, next);          // write to the buffer
        pbump(next);                        // update pptr

        buf += next;                        // update the buf location
        nWritten += next;                   // and update the counters
        toWrite -= next;
        offset = offs += next;
    }

    if (getend < offs + nWritten)           // maybe enlarge the reading
        getend = offs + nWritten;           // area

    d_last = WRITE;                         // WRITE state: now writing,
                                            // maybe overflow wasn't used
    return nWritten;
}
