#ifndef __UTILS_TARRAYALLOCATOR_HPP__ #define __UTILS_TARRAYALLOCATOR_HPP__ ///////////////////////////////////////////////////////////////////////////// // includes ///////////////////////////////////////////////////////////////////////////// #include #include #include #include "TAtomic.hpp" ///////////////////////////////////////////////////////////////////////////// // declaration ///////////////////////////////////////////////////////////////////////////// namespace Utils { template class TArrayAllocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef OBJECT* pointer; typedef const OBJECT* const_pointer; typedef OBJECT& reference; typedef const OBJECT& const_reference; typedef OBJECT value_type; template struct rebind { typedef TArrayAllocator other; }; inline TArrayAllocator(size_t size = 10000) throw() : _size(size) { __allocArray(); } inline TArrayAllocator(const TArrayAllocator& __a) throw() : _size(__a._size) { __allocArray(); } template inline TArrayAllocator(const TArrayAllocator& __a) throw() : _size(__a._size) { __allocArray(); } inline ~TArrayAllocator() throw() { __deallocArray(); } inline pointer allocate(size_type objSize, const void* = 0) { if (objSize > this->max_size()) std::__throw_bad_alloc(); size_type pos = _currentPos++; if(pos < _size ) return _array[pos]; return (pointer)::operator new(objSize); } inline void deallocate(pointer ptr, size_type) { if(ptr < _array[0] || ptr > _array[_size -1 ]) ::operator delete(ptr); } inline size_type max_size() const throw() { return sizeof(OBJECT); } inline void construct(pointer ptr, const OBJECT& cpy) { ::new((void *)ptr) OBJECT(cpy); } inline void destroy(pointer ptr) { ptr->~OBJECT(); } void clear(); private: inline void __allocArray() { //std::cout << _size << " x " << sizeof(value_type)<< std::endl; _currentPos = 0; _allocatedBytes = sizeof(value_type) * _size; _array = new pointer[_size]; char* rawMem = (char*)::operator new(_allocatedBytes); for(size_type pos = 0; pos < _size; ++pos) _array[pos] = (pointer)(rawMem + (pos * sizeof(value_type))); } inline void __deallocArray() { ::operator delete(_array[0]); delete [] _array; } private: pointer* _array; size_type _allocatedBytes; size_type _size; Utils::TAtomic _currentPos; TArrayAllocator& operator = (const TArrayAllocator&); }; template inline bool operator==(const TArrayAllocator&, const TArrayAllocator&) { return true; } template inline bool operator==(const TArrayAllocator&, const TArrayAllocator&) { return true; } template inline bool operator!=(const TArrayAllocator&, const TArrayAllocator&) { return false; } template inline bool operator!=(const TArrayAllocator&, const TArrayAllocator&) { return false; } template void TArrayAllocator::clear() { __deallocArray(); // TODO We may use the _currentPos as the new _size when it's higher. __allocArray(); } } #endif