From d1e486136db52b466b788c1d81a5c88b6f24acd9 Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Thu, 2 Nov 2006 06:14:41 +0000 Subject: Added the SBuffer class, a memory buffer that can be used like a stream. Yay! --- src/sbuffer.cpp | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/sbuffer.h | 34 ++++++++++++++++++++++++++++ src/tests/sbuffer.cpp | 27 ++++++++++++++++++++++ 3 files changed, 123 insertions(+) create mode 100644 src/sbuffer.cpp create mode 100644 src/sbuffer.h create mode 100644 src/tests/sbuffer.cpp diff --git a/src/sbuffer.cpp b/src/sbuffer.cpp new file mode 100644 index 0000000..00324b5 --- /dev/null +++ b/src/sbuffer.cpp @@ -0,0 +1,62 @@ +#include +#include "sbuffer.h" + +SBuffer::SBuffer() : + bOpen( true ), + nPos( 0 ) +{ +} + +SBuffer::~SBuffer() +{ +} + +void SBuffer::close() +{ + bOpen = false; + fbData.clearData(); +} + +size_t SBuffer::read( char *pBuf, size_t nBytes ) +{ + long nLeft = fbData.getLength() - nPos; + if( nBytes > nLeft ) + nBytes = nLeft; + + if( nLeft == 0 ) + return 0; + + memcpy( pBuf, fbData.getData()+nPos, nBytes ); + nPos += nBytes; + + return nBytes; +} + +size_t SBuffer::write( const char *pBuf, size_t nBytes ) +{ + fbData.appendData( pBuf, nBytes ); + nPos += nBytes; + + return nBytes; +} + +long SBuffer::tell() +{ + return nPos; +} + +void SBuffer::seek( long offset ) +{ + nPos += offset; +} + +void SBuffer::setPos( long pos ) +{ + nPos = pos; +} + +void SBuffer::setPosEnd( long pos ) +{ + nPos = fbData.getLength() - pos; +} + diff --git a/src/sbuffer.h b/src/sbuffer.h new file mode 100644 index 0000000..1dda33a --- /dev/null +++ b/src/sbuffer.h @@ -0,0 +1,34 @@ +#ifndef S_BUFFER_H +#define S_BUFFER_H + +#include + +#include "stream.h" +#include "flexbuf.h" + +class SBuffer : public Stream +{ +public: + SBuffer(); + virtual ~SBuffer(); + + virtual void close(); + virtual size_t read( char *pBuf, size_t nBytes ); + + /** + *@todo Update this to write at nPos, not just append data. + */ + virtual size_t write( const char *pBuf, size_t nBytes ); + + virtual long tell(); + virtual void seek( long offset ); + virtual void setPos( long pos ); + virtual void setPosEnd( long pos ); + +private: + long nPos; + bool bOpen; + FlexBuf fbData; +}; + +#endif diff --git a/src/tests/sbuffer.cpp b/src/tests/sbuffer.cpp new file mode 100644 index 0000000..d8bbe4d --- /dev/null +++ b/src/tests/sbuffer.cpp @@ -0,0 +1,27 @@ +#include "sbuffer.h" + +int main() +{ + SBuffer buf; + + buf.write("abcdefg", 7 ); + + printf("tell: %d\n", buf.tell() ); + + char abuf[6]; + int nRead; + nRead = buf.read( abuf, 5 ); + abuf[nRead] = '\0'; + printf("Read %d bytes \"%s\"\n", nRead, abuf ); + + buf.setPos( 0 ); + nRead = buf.read( abuf, 5 ); + abuf[nRead] = '\0'; + printf("Read %d bytes \"%s\"\n", nRead, abuf ); + + nRead = buf.read( abuf, 5 ); + abuf[nRead] = '\0'; + printf("Read %d bytes \"%s\"\n", nRead, abuf ); + +} + -- cgit v1.2.3