Made on Kubuntu
00001 // Copyright (C) 2009-2010 Ferdinand Majerech 00002 // This file is part of MiniINI 00003 // For conditions of distribution and use, see copyright notice in LICENSE.txt 00004 00005 00006 #ifndef ALLOCATOR_H_INCLUDED 00007 #define ALLOCATOR_H_INCLUDED 00008 00009 #include "typedefs.h" 00010 #include "miniini_assert.h" 00011 00012 namespace miniini_private 00013 { 00015 00017 class Block 00018 { 00020 friend class Allocator; 00021 private: 00023 ui Allocated; 00025 ui Used; 00027 ui PtrsGiven; 00029 ui PtrsDeleted; 00031 c * Data; 00032 00033 public: 00035 00039 Block(const ui alloc) 00040 :Allocated(alloc) 00041 ,Used(0) 00042 ,PtrsGiven(0) 00043 ,PtrsDeleted(0) 00044 ,Data(new c [Allocated]) 00045 {} 00046 00048 ~Block() 00049 { 00050 delete [] Data; 00051 } 00052 00054 ui GetRemainingSpace() const 00055 { 00056 return Allocated - Used; 00057 } 00058 00060 00064 void Reallocate(const ui size) 00065 { 00066 //This can only be called before this block is used for the first time. 00067 MINIINI_ASSERT(!(Used || PtrsGiven || PtrsDeleted), 00068 "Block::Reallocate called on block that was already" 00069 "used."); 00070 Allocated = size; 00071 delete [] Data; 00072 Data = new c [Allocated]; 00073 } 00074 00075 private: 00076 00078 00079 Block(const Block &); 00080 00081 void operator = (const Block &); 00082 }; 00083 00085 00088 class Allocator 00089 { 00090 private: 00092 ui NumBlocks; 00093 00095 /* 00096 * When the first block gets filled, we start taking memory from the 00097 * second one, and so on. 00098 */ 00099 ui CurrentBlock; 00100 00102 ui BlockMinSize; 00103 00105 Block * * Blocks; 00106 00107 public: 00109 00114 Allocator(const ui size, const ui blocks); 00115 00117 void Trim(); 00118 00120 00124 void DeleteSpace(c * const ptr); 00125 00127 00131 c * NewSpace(const ui size); 00132 00134 ~Allocator(); 00135 00136 private: 00137 00139 00142 void NextBlock(ui minsize); 00143 00145 void NewBlock(); 00146 00148 00151 void DeleteBlock(ui index); 00152 00154 00159 i FindBlock(c * const ptr); 00160 00161 //No copy construction or assignment. 00162 00163 Allocator(const Allocator &); 00164 00165 void operator = (const Allocator &); 00166 }; 00168 00169 } 00170 #endif