#define XERR "memoryaccess"
#include "memoryaccess.ih"

    // by read.f, write.cc

    // mem is static_cast to char * by copy = memRead
size_t MemoryAccess::io(char const *mem, size_t len, 
                         void (*copy)(char const *, char const *, size_t),
                         size_t offset)
{
    size_t nProcessed = 0;

    while (len and load(offset))    // load: false if no block for d_offset
    {
        size_t available = min(len, d_blockEnd - offset); // # to proces

        if (available == 0)
            break;

        (*copy)(mem, ptr(offset), available);           // copy the bytes

        nProcessed += available;                        // update nProcesseders
        len -= available;                               // and the current 
        offset += available;                            // offset

        mem += available;                               // beyond the last
                                                        // assigned byte
    }

    return nProcessed;
}


//xerr("for " << (copy == &memWrite ? "writing" : "reading"));

//    static size_t total = 0;
//    static fstream outf{ "/tmp/outf", ios::in|ios::out};

//if (copy == &memWrite)
//{
//xerr("compare: " << memcmp(mem, ptr(), nAvailable));
//xerr("WRITING " << nAvailable << " bytes, total = " << (total += len));
//outf.write(ptr(), nAvailable);
//}
//else
//{
//xerr("READING " << nAvailable << " bytes, total = " << (total += len));
//char *buffer = new char[nAvailable];
//outf.read(buffer, nAvailable);
//xerr("read compare: " << memcmp(buffer, ptr(), nAvailable));
//xerr("read compare: " << memcmp(mem, ptr(), nAvailable));
//delete[] buffer;
//}

//if (copy == &memWrite)
//{
//xerr("block: " << d_currentBlock << 
//", offset = " << d_offset << 
//", ptr = " << (void *)ptr() << 
//", data = " << (void *)d_data << 
//", begin = " << (void *)d_begin << 
//", available: " << nAvailable);
//}

