block-allocator.icc
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038 namespace Gecode { namespace Support {
00039
00048 template <class T, int blocksize = 512>
00049 class BlockAllocator {
00050 private:
00052 class Block {
00053 public:
00054 T b[blocksize];
00055 Block* next;
00056 };
00058 Block* b;
00060 T* n;
00062 size_t _size;
00064 void allocate(void);
00065 public:
00067 BlockAllocator(void);
00069 ~BlockAllocator(void);
00071 T* operator()(void);
00073 size_t size(void) const;
00074 };
00075
00083 template <class T, int blocksize = 512>
00084 class BlockClient {
00085 public:
00087 static void* operator new(size_t s, BlockAllocator<T,blocksize>& ba);
00089 static void operator delete(void*, BlockAllocator<T,blocksize>& ba);
00091 static void operator delete(void*);
00092 };
00093
00094
00095
00096 template <class T, int blocksize>
00097 forceinline
00098 BlockAllocator<T,blocksize>::BlockAllocator(void) {
00099 b = static_cast<Block*>(Memory::malloc(sizeof(Block)));
00100 b->next = NULL;
00101 n = &b->b[blocksize];
00102 _size = sizeof(Block);
00103 }
00104
00105 template <class T, int blocksize>
00106 forceinline
00107 BlockAllocator<T,blocksize>::~BlockAllocator(void) {
00108 while (b != NULL) {
00109 Block* f = b; b = b->next;
00110 Memory::free(f);
00111 }
00112 }
00113
00114 template <class T, int blocksize>
00115 forceinline T*
00116 BlockAllocator<T,blocksize>::operator()(void) {
00117 T* t = --n;
00118 if (t == &b->b[0])
00119 allocate();
00120 return t;
00121 }
00122
00123 template <class T, int blocksize>
00124 void
00125 BlockAllocator<T,blocksize>::allocate(void) {
00126
00127 Block* nb = static_cast<Block*>(Memory::malloc(sizeof(Block)));
00128 nb->next = b; b = nb;
00129 n = &nb->b[blocksize];
00130 _size += sizeof(Block);
00131 }
00132
00133 template <class T, int blocksize>
00134 forceinline size_t
00135 BlockAllocator<T,blocksize>::size(void) const {
00136 return _size;
00137 }
00138
00139
00140
00141 template <class T, int blocksize>
00142 forceinline void
00143 BlockClient<T,blocksize>::operator delete(void*,
00144 BlockAllocator<T,blocksize>&) {
00145 }
00146 template <class T, int blocksize>
00147 forceinline void
00148 BlockClient<T,blocksize>::operator delete(void*) {
00149 }
00150 template <class T, int blocksize>
00151 forceinline void*
00152 BlockClient<T,blocksize>::operator new(size_t,
00153 BlockAllocator<T,blocksize>& ba) {
00154 return ba();
00155 }
00156
00157 }}
00158
00159