This has been vexing me all morning.
I have a stream class that keeps a buffer and wraps other streams. (I'd use the STL but I can't for reasons)
The idea is that it wraps an underlying stream and reads from that stream in large chunks which is faster than reading a lot of little chunks. It then keeps a chunk in memory, and pulls from that when the user calls read()
The trouble is, it's corrupting my underlying stream's data somehow. I think I've narrowed it to the read method, as all methods are trivial, with the exception of seek() which clears the buffer.
Anyway I've been staring at this code till I'm cross eyed and I just can't spot where I've got it wrong.
read()
takes a buffer and a size, and reads that many bytes from the stream unless the end happens in which case it may read less. In any case, it returns the number of bytes read.
m_buffer_index
holds the current offset within the buffer where the next read takes place.
m_buffer_capacity
holds the total amount of bytes allocated to the buffer. This may be greater than the actual amount of data in the buffer in the case where the end of the stream was reached.
m_buffer_size
indicates the actual count of bytes from the stream that are contained in the buffer. In the case where the end of the stream was reached, this may be less than
m_buffer_capacity
Further questions I can cover in the comments
What I have tried:
virtual size_t read(uint8_t* destination,size_t size) {
if(!initialize()) {
return 0;
}
if(!m_buffer_size || m_buffer_index>=m_buffer_capacity) {
m_buffer_size = m_stream.read(m_buffer,m_buffer_capacity);
m_buffer_index = 0;
}
int sz = m_buffer_size-m_buffer_index<size?m_buffer_size-m_buffer_index:size;
if(sz>0) {
memcpy(destination,m_buffer+m_buffer_index,sz);
m_buffer_index+=sz;
if(sz!=size) {
sz+=read(destination+sz,size-sz);
}
}
return sz;
}