#5 Make arena allocator align depending on size #3

Merged
Archivist merged 2 commits from arena-allocator-alignment-fix-#3 into master 4 years ago
  1. +23
    -29
      include/gp/allocator/arena.hpp

+ 23
- 29
include/gp/allocator/arena.hpp View File

@ -3,27 +3,27 @@
#include "gp/buffer.hpp" #include "gp/buffer.hpp"
#include <type_traits> #include <type_traits>
#include <gp/algorithm/tmp_manip.hpp> #include <gp/algorithm/tmp_manip.hpp>
#include "gp/math/integer_math.hpp"
#include "gp/algorithm/min_max.hpp"
namespace gp{
template<typename page_allocator = int, size_t align = 1>
class arena{
namespace gp {
template<typename page_allocator = int>
class arena {
page_allocator allocator; page_allocator allocator;
gp::buffer<char> data; gp::buffer<char> data;
size_t last;
size_t next;
size_t count; size_t count;
public: public:
arena() arena()
:last(0)
,count(0)
,data(gp::buffer<char>(nullptr,nullptr))
: next(0)
, count(0)
, data(gp::buffer<char>(nullptr,nullptr))
{} {}
arena(size_t sz) arena(size_t sz)
:last(0)
,count(0)
,data(nullptr,nullptr)
: next(0)
, count(0)
, data(nullptr,nullptr)
{ {
if constexpr (gp::has_allocator_interface<page_allocator>::value) if constexpr (gp::has_allocator_interface<page_allocator>::value)
{ {
@ -39,28 +39,22 @@ namespace gp{
} }
arena(char* pos,size_t sz) arena(char* pos,size_t sz)
:last(0)
,count(0)
,data(pos,pos+sz)
{
}
: next(0)
, count(0)
, data(pos,pos+sz)
{}
void* allocate(size_t sz) void* allocate(size_t sz)
{ {
[[maybe_unused]]
size_t mod = 0;
if constexpr (align != 1)
{
mod = align - ((intptr_t)data.begin())%align;
}
size_t align = gp::min((1 << gp::math::log2(sz)), 16);
size_t padding = align - (reinterpret_cast<uintptr_t>(data.begin().data + next)) % align;
auto ret=data.begin()+last+mod;
auto ret=data.begin()+padding+next;
if(data.contains(ret)) if(data.contains(ret))
{ {
count++; count++;
last+=sz+mod;
return o">&*(ret);
next+=padding+sz;
return n">ret.data;
} }
else else
{ {
@ -83,7 +77,7 @@ namespace gp{
{ {
i=0; i=0;
} }
last=0;
next=0;
} }
return true; return true;
} }
@ -98,4 +92,4 @@ namespace gp{
} }
} }
}; };
}
}

Loading…
Cancel
Save