GLProgramming.com

home :: about :: development guides :: irc :: forums :: search :: paste :: links :: contribute :: code dump

-> Click here to learn how to get live help <-


New Paste :: Recent Pastes:: Add Line Numbers


blargh by godecho
#include <iostream>
#include <vector>

using namespace std;

typedef std::vector<unsigned char> ByteStream;

struct ByteStreamHandle
{
    ByteStreamHandle(const ByteStream& inStream)
        : stream(inStream),
          position(0)
    {
        
    }
    
    const ByteStream& stream;
    long position;
};

unsigned int streamRead(void* buffer, unsigned int size, unsigned int count, void* handle)
{
    ByteStreamHandle* byteStream = (ByteStreamHandle*)handle;
    
    const unsigned char* rawStream = &byteStream->stream[0];
    long begin = byteStream->position;
    long end   = min(static_cast<long>(byteStream->stream.size()), static_cast<long>(begin + (size*count)));
    
    copy(rawStream+begin, rawStream+end, (char*)buffer);
    //memcpy(buffer, rawStream+begin, end-begin);
    byteStream->position += end-begin;
    
    return end-begin;
}

int streamSeek(void* handle, long offset, int origin)
{
    ByteStreamHandle* byteStream = (ByteStreamHandle*)handle;
    
    switch(origin)
    {
        case SEEK_SET: byteStream->position = 0; break;
        case SEEK_CUR: break;
        case SEEK_END: byteStream->position = byteStream->stream.size(); break;
        default: return -1;
    }

    if((byteStream->position + offset) > static_cast<long>(byteStream->stream.size()) ||
       (byteStream->position + offset) < 0)
    {
        return -1;  // Error, we're trying to seek past the beginning or end of the stream
    }
    else
    {
        byteStream->position += offset;
        return 0;
    }
}

long streamTell(void* handle)
{
    return ((ByteStreamHandle*)handle)->position;
}


int main(int argc, char** argv)
{
    ByteStream stream;
    ByteStreamHandle handle(stream);
    stream.resize(10);

    unsigned char buffer[10];

    // put something in our stream
    for(int x = 0; x < stream.size(); ++x)
    {
        stream[x] = x;
    }

    // read each element out of the stream, one at a time
    for(int x = 0; x < 10; ++x)
    {
        cout << "reading from position " << streamTell((void*)&handle) << endl;
        streamRead(buffer+x, sizeof(unsigned char), 1, (void*)&handle);
    }

    // print buffer
    for(int x = 0; x < 10; ++x)
    {
        cout << int(buffer[x]) << endl;
    }

    return 0;
}