Permalink
Browse files

Added PoolAllocator.

  • Loading branch information...
1 parent 6550723 commit 704901fec09b532d7c923c883f8b21c5dee84d93 @yuriks committed May 25, 2012
Showing with 66 additions and 0 deletions.
  1. +1 −0 Heatwave.vcxproj
  2. +3 −0 Heatwave.vcxproj.filters
  3. +1 −0 src/main.cpp
  4. +61 −0 src/memory/PoolAllocator.hpp
View
@@ -86,6 +86,7 @@
<ClInclude Include="src\hw_config.hpp" />
<ClInclude Include="src\job_system\JobManager.hpp" />
<ClInclude Include="src\memory\LinearAllocator.hpp" />
+ <ClInclude Include="src\memory\PoolAllocator.hpp" />
<ClInclude Include="src\obj_model\Chain.hpp" />
<ClInclude Include="src\obj_model\GameObject.hpp" />
<ClInclude Include="src\obj_model\GameObjectFunctions.hpp" />
View
@@ -45,6 +45,9 @@
<ClInclude Include="src\obj_model\Chain.hpp">
<Filter>Header Files</Filter>
</ClInclude>
+ <ClInclude Include="src\memory\PoolAllocator.hpp">
+ <Filter>Header Files</Filter>
+ </ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="src\hw_assert.cpp">
View
@@ -3,6 +3,7 @@
#include "hw_assert.hpp"
#include "memory/LinearAllocator.hpp"
+#include "memory/PoolAllocator.hpp"
#include "obj_model/GameObject.hpp"
#include "obj_model/GameObjectFunctions.hpp"
#include "obj_model/ObjectPool.hpp"
@@ -0,0 +1,61 @@
+#include "Heatwave.hpp"
+
+#include <cstddef>
+
+namespace hw {
+namespace memory {
+
+template<typename T>
+class PoolAllocator {
+ static_assert(sizeof(T) >= sizeof(u16), "sizeof(T) needs to be at least sizeof(u16).");
+
+ u16& id_at_index(u16 i)
+ {
+ return *reinterpret_cast<u16*>(&memory[i]);
+ }
+
+public:
+ PoolAllocator(T* memory_area, u16 num_items) :
+ memory(memory_area),
+ num_items(num_items),
+ next_free_obj(0)
+ {
+ for (u16 i = 0; i < num_items; ++i) {
+ id_at_index(i) = i+1;
+ }
+ }
+
+ u16 allocate()
+ {
+ u16 new_obj_id = next_free_obj;
+#if DBG_CHECKED_ALLOCATORS
+ HW_ASSERT(new_obj_id < num_items, "Pool allocator full.");
+#endif
+
+ next_free_obj = id_at_index(new_obj_id);
+
+ return new_obj_id;
+ }
+
+ void free(u16 id)
+ {
+ HW_DBG_ASSERT(id < num_items/*, "Tried to free invalid pool item."*/);
+
+ id_at_index(id) = next_free_obj;
+ next_free_obj = id;
+ }
+
+ T& operator[] (u16 id)
+ {
+ HW_DBG_ASSERT(id < num_items/*, "Out of bounds pool access."*/);
+ return memory[id];
+ }
+
+private:
+ T *const memory;
+ const u16 num_items;
+ u16 next_free_obj;
+};
+
+}
+}

0 comments on commit 704901f

Please sign in to comment.