CrossFramework Library
|
00001 00006 #if defined(XBASE_INCLUDED_RUNTIMEMARRAY_HPP) 00007 #else 00008 #define XBASE_INCLUDED_RUNTIMEMARRAY_HPP 00009 00010 //------------------------------------------------------------ 00011 #include <XBase/IAllocator.hpp> 00012 #include <XBase/NonCopyable.hpp> 00013 #include <XBase/RuntimeAssert.hpp> 00014 00015 //------------------------------------------------------------ 00016 namespace XBase { 00018 00019 00020 template< typename T > 00021 class RuntimeMArray : public ::XBase::NonCopyable 00022 { 00023 public: 00025 00026 typedef T ValueType; 00028 00030 00031 00039 RuntimeMArray( uint aCountMax , IAllocator& aAllocator = IAllocator::Default() ) 00040 : mAllocator( aAllocator ) 00041 , mCountMax( aCountMax ) 00042 , mCount( 0 ) 00043 , mPtr( 0 ) 00044 { 00045 if ( 0 < aCountMax ) 00046 { 00047 mPtr = reinterpret_cast< ValueType* >( mAllocator.alloc( sizeof( ValueType ) * aCountMax ) ); 00048 } 00049 } 00050 00052 ~RuntimeMArray() 00053 { 00054 if ( mPtr != 0 ) 00055 { 00056 ValueType* ptr = mPtr; 00057 mPtr = 0; 00058 mAllocator.free( reinterpret_cast< ptr_t >( ptr ) ); 00059 } 00060 } 00061 00063 00065 00066 00067 bool isEmpty()const 00068 { 00069 return mCount == 0; 00070 } 00071 00073 bool isFull()const 00074 { 00075 return mCount == mCountMax; 00076 } 00077 00079 uint count()const 00080 { 00081 return mCount; 00082 } 00083 00085 uint countMax()const 00086 { 00087 return mCountMax; 00088 } 00089 00091 ValueType& at( const uint aIndex ) 00092 { 00093 if ( mCount <= aIndex ) 00094 { 00095 XBASE_RANGE_ASSERT_MAX( aIndex , mCount ); 00096 return mPtr[ 0 ]; // fail safe code 00097 } 00098 return mPtr[ aIndex ]; 00099 } 00100 00102 const ValueType& at( const uint aIndex )const 00103 { 00104 if ( mCount <= aIndex ) 00105 { 00106 XBASE_RANGE_ASSERT_MAX( aIndex , mCount ); 00107 return mPtr[ 0 ]; // fail safe code 00108 } 00109 return mPtr[ aIndex ]; 00110 } 00111 00113 ValueType& first() { return at( 0 ); } 00115 const ValueType& first()const { return at( 0 ); } 00116 00118 ValueType& last() { return at( mCount - 1 ); } 00120 const ValueType& last()const { return at( mCount - 1 ); } 00121 00123 00125 00126 00128 void clear() 00129 { 00130 mCount = 0; 00131 } 00132 00134 void add( const ValueType& aVal ) 00135 { 00136 if ( isFull() ) 00137 { 00138 XBASE_NOT_REACH_ASSERT(); 00139 return; 00140 } 00141 mPtr[ mCount ] = aVal; 00142 ++mCount; 00143 } 00144 00146 00148 00149 ValueType& operator[]( const uint aIndex ) { return at( aIndex ); } 00150 const ValueType& operator[]( const uint aIndex )const { return at( aIndex ); } 00151 00152 00153 private: 00154 IAllocator& mAllocator; 00155 const uint mCountMax; 00156 uint mCount; 00157 ValueType* mPtr; 00158 }; 00160 } 00161 //------------------------------------------------------------ 00162 #endif 00163 // EOF