int main() { StreamPtr inp = StringStream::Open("hello world!"); cout << "Size: " << inp->size() << endl; cout << "Pos: " << inp->tell() << "\nSeeking...\n"; inp->seek(3); cout << "Pos: " << inp->tell() << endl; char data[12]; memset(data, 0, 12); cout << "Reading: " << inp->read(data, 4) << endl; cout << "Four bytes: " << data << endl; cout << "Eof: " << inp->eof() << endl; cout << "Pos: " << inp->tell() << "\nSeeking again...\n"; inp->seek(33); cout << "Pos: " << inp->tell() << endl; cout << "Eof: " << inp->eof() << "\nSeek to 6\n"; inp->seek(6); cout << "Eof: " << inp->eof() << endl; cout << "Pos: " << inp->tell() << endl; cout << "Over-reading: " << inp->read(data, 200) << endl; cout << "Result: " << data << endl; cout << "Eof: " << inp->eof() << endl; cout << "Pos: " << inp->tell() << endl; inp->seek(0); cout << "Finally, reading the entire string: " << inp->read(data,11) << endl; cout << "Result: " << data << endl; cout << "Eof: " << inp->eof() << endl; cout << "Pos: " << inp->tell() << endl; cout << "Entire stream from pointer: " << (char*)inp->getPtr() << endl; return 0; }
/* input = stream to copy ADD = each read increment (for streams without size()) */ BufferStream(StreamPtr input, size_t ADD = 32*1024) { assert(input); // Allocate memory, read the stream into it. Then call set() if(input->hasSize) { // We assume that we can get the position as well assert(input->hasPosition); // Calculate how much is left of the stream size_t left = input->size() - input->tell(); // Allocate the buffer and fill it buffer.resize(left); input->read(&buffer[0], left); } else { // We DON'T know how big the stream is. We'll have to read // it in increments. size_t len=0, newlen; while(!input->eof()) { // Read one block newlen = len + ADD; buffer.resize(newlen); size_t read = input->read(&buffer[len], ADD); // Increase the total length len += read; // If we read less than expected, we should be at the // end of the stream assert(read == ADD || (read < ADD && input->eof())); } // Downsize to match the real length buffer.resize(len); } // After the buffer has been filled, set up our MemoryStream // ancestor to reference it. set(&buffer[0], buffer.size()); }
void read_all(StreamPtr in, std::function<void(Buffer)> callback) { in->set_on_read_ready([callback, in]() { while(true) { StackBuffer<1024> buff; Buffer data = in->read(buff); callback(data); if(data.size == 0) break; } }); }
void test(StreamPtr inp) { cout << "Size: " << inp->size() << endl; cout << "Pos: " << inp->tell() << endl; cout << "Eof: " << inp->eof() << endl; char data[6]; while(!inp->eof()) { memset(data, 0, 6); cout << "\nReading " << inp->read(data, 5) << " bytes\n"; cout << "Result: '" << data << "'\n"; cout << "Pos: " << inp->tell() << endl; cout << "Eof: " << inp->eof() << endl; } }
/// Read 'count' bytes, return bytes successfully read int ADR_CALL read(void *buf, int count) { return inp->read(buf,count); }