00001
00002
00003
00004
00005 #ifndef EQBASE_BUFFER_H
00006 #define EQBASE_BUFFER_H
00007
00008 #include <eq/base/nonCopyable.h>
00009 #include <eq/base/debug.h>
00010
00011 namespace eq
00012 {
00013 namespace base
00014 {
00024 template< typename T >
00025 class Buffer
00026 {
00027 public:
00028 Buffer() : data(0), size(0), _maxSize(0) {}
00029 ~Buffer() { clear(); }
00030
00032 void clear() { if( data ) free( data ); data=0; size=0; _maxSize=0; }
00033
00035 Buffer( Buffer& from )
00036 {
00037 data = from.data; size = from.size; _maxSize = from._maxSize;
00038 from.data = 0; from.size = 0; from._maxSize = 0;
00039 }
00040
00042 const Buffer& operator = ( Buffer& from )
00043 {
00044 replace( from.data, from.size );
00045 return *this;
00046 }
00047
00048 T& operator[]( const size_t position )
00049 { EQASSERT( size > position ); return data[ position ]; }
00050 const T& operator[]( const size_t position) const
00051 { EQASSERT( size > position ); return data[ position ]; }
00052
00057 void resize( const uint64_t newSize )
00058 {
00059 size = newSize;
00060 if( newSize <= _maxSize )
00061 return;
00062
00063 const size_t nBytes = newSize * sizeof( T );
00064 if( data )
00065 data = static_cast< T* >( realloc( data, nBytes ));
00066 else
00067 data = static_cast< T* >( malloc( nBytes ));
00068
00069 _maxSize = newSize;
00070 }
00071
00076 void reserve( const uint64_t newSize )
00077 {
00078 if( newSize <= _maxSize )
00079 return;
00080
00081 if( data )
00082 free( data );
00083
00084 data = static_cast< T* >( malloc( newSize * sizeof( T )));
00085 _maxSize = size;
00086 }
00087
00089 void append( const T* addData, const uint64_t addSize )
00090 {
00091 EQASSERT( addData );
00092 EQASSERT( addSize );
00093
00094 const uint64_t oldSize = size;
00095 resize( oldSize + addSize );
00096 memcpy( data + oldSize, addData, addSize * sizeof( T ));
00097 }
00098
00100 void append( const T& element )
00101 {
00102 resize( size + 1 );
00103 data[ size - 1 ] = element;
00104 }
00105
00107 void replace( const void* newData, const uint64_t newSize )
00108 {
00109 EQASSERT( newData );
00110 EQASSERT( newSize );
00111
00112 reserve( newSize );
00113 memcpy( data, newData, newSize * sizeof( T ));
00114 size = newSize;
00115 }
00116
00118 void swap( Buffer& buffer )
00119 {
00120 T* tmpData = buffer.data;
00121 const uint64_t tmpSize = buffer.size;
00122 const uint64_t tmpMaxSize = buffer._maxSize;
00123
00124 buffer.data = data;
00125 buffer.size = size;
00126 buffer._maxSize = _maxSize;
00127
00128 data = tmpData;
00129 size = tmpSize;
00130 _maxSize = tmpMaxSize;
00131 }
00132
00134 uint64_t getMaxSize() const { return _maxSize; }
00135
00137 T* data;
00139 uint64_t size;
00140
00141 private:
00143 uint64_t _maxSize;
00144 };
00145
00146 typedef Buffer< uint8_t > Bufferb;
00147 }
00148
00149 }
00150 #endif //EQBASE_BUFFER_H