Merge branch 'MG_test_T196-Stack_Allocator_Test' into dev
This commit is contained in:
@@ -55,3 +55,10 @@ private:
|
||||
TOKEN_PASTE(auto_, counter)(TOKEN_PASTE(auto_func_, counter));
|
||||
|
||||
#define Auto(Destructor) Auto_INTERNAL(Destructor, __COUNTER__)
|
||||
|
||||
// -- example:
|
||||
// Auto(f());
|
||||
// -- is expended to:
|
||||
// auto auto_func_1 = [&]() { f(); };
|
||||
// OnScopeExit<decltype(auto_func_1)> auto_1(auto_func_1);
|
||||
// -- f() is called at the end of a scope
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
|
||||
#include "utils/auto_scope.hpp"
|
||||
|
||||
/* @brief Allocates blocks of block_size and stores
|
||||
* the pointers on allocated blocks inside a vector.
|
||||
*/
|
||||
template <size_t block_size>
|
||||
class BlockAllocator
|
||||
{
|
||||
@@ -23,29 +26,45 @@ public:
|
||||
BlockAllocator(size_t capacity = 0)
|
||||
{
|
||||
for (size_t i = 0; i < capacity; ++i)
|
||||
blocks.emplace_back();
|
||||
unused_.emplace_back();
|
||||
}
|
||||
|
||||
~BlockAllocator()
|
||||
{
|
||||
for (auto b : blocks) {
|
||||
free(b.data);
|
||||
}
|
||||
blocks.clear();
|
||||
for (auto block : unused_)
|
||||
free(block.data);
|
||||
unused_.clear();
|
||||
for (auto block : release_)
|
||||
free(block.data);
|
||||
release_.clear();
|
||||
}
|
||||
|
||||
size_t unused_size() const
|
||||
{
|
||||
return unused_.size();
|
||||
}
|
||||
|
||||
size_t release_size() const
|
||||
{
|
||||
return release_.size();
|
||||
}
|
||||
|
||||
// Returns nullptr on no memory.
|
||||
void *acquire()
|
||||
{
|
||||
if (blocks.size() == 0) blocks.emplace_back();
|
||||
if (unused_.size() == 0) unused_.emplace_back();
|
||||
|
||||
auto ptr = blocks.back().data;
|
||||
Auto(blocks.pop_back());
|
||||
auto ptr = unused_.back().data;
|
||||
Auto(unused_.pop_back());
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void release(void *ptr) { blocks.emplace_back(ptr); }
|
||||
void release(void *ptr) { release_.emplace_back(ptr); }
|
||||
|
||||
private:
|
||||
std::vector<Block> blocks;
|
||||
// TODO: try implement with just one vector
|
||||
// but consecutive acquire release calls should work
|
||||
// TODO: measure first!
|
||||
std::vector<Block> unused_;
|
||||
std::vector<Block> release_;
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <cmath>
|
||||
|
||||
#include "utils/exceptions/out_of_memory.hpp"
|
||||
#include "utils/likely.hpp"
|
||||
#include "utils/memory/block_allocator.hpp"
|
||||
|
||||
// http://en.cppreference.com/w/cpp/language/new
|
||||
|
||||
Reference in New Issue
Block a user