Unified Memory Group Allocator
ListAllocator.h
Go to the documentation of this file.
1 
5 #include <list>
6 
7 #pragma once
8 
9 namespace groupallocator {
10 
14  inline size_t getPadding(size_t startingptr, size_t alignment) {
15  size_t multiplier = startingptr / alignment + 1;
16  size_t padding = multiplier * alignment - startingptr;
17  return padding;
18  }
19 
21  class ListAllocator {
22  private:
23  struct MallocData {
24  size_t size;
25  size_t used;
26  void* start;
27  };
28 
29  public:
30  // s needs to be larger than 2 MallocData
31  ListAllocator(void *p, size_t s) : ptr(p), size(s) {
32  // needs to maintain p to p + s
33  l.push_back({s, 0, p});
34  }
35 
36  ListAllocator() : ptr(nullptr), size(0) {}
37 
39  template<typename T>
40  inline void alloc(T **p, size_t s, bool forceAligned128) {
41  size_t alignment = forceAligned128 ? 128 : std::alignment_of<T *>();
42 
43  for(auto iter = l.begin(); iter != l.end(); ++iter) {
44 
45  if(iter->used == 0 && getPadding((size_t)iter->start, alignment) + s <= iter->size){
46 
47  *p = (T*) iter->start;
48 
49  size_t prevSize = iter->size;
50  void* prevStart = iter->start;
51 
52  iter->size = s + getPadding((size_t)iter->start, alignment);
53  iter->used = 1;
54 
55  MallocData m = {prevSize - iter->size, 0, (void*)((size_t)prevStart + iter->size)};
56  iter++;
57  l.insert(iter, m);
58  return;
59  }
60  }
61 
62  *p = nullptr;
63  }
64 
66  template<typename T>
67  inline void free(T *p) {
68  for(auto & iter : l){
69  if((size_t)iter.start == (size_t)p){
70  iter.used = 0;
71  return;
72  }
73  }
74  }
75 
76  private:
77  void *ptr;
78  size_t size;
79  std::list<MallocData> l;
80 
81  };
82 } // namespace groupallocator
groupallocator::getPadding
size_t getPadding(size_t startingptr, size_t alignment)
Definition: ListAllocator.h:14
groupallocator::ListAllocator::alloc
void alloc(T **p, size_t s, bool forceAligned128)
allocates data in a free area or sets p to nullptr
Definition: ListAllocator.h:40
groupallocator::ListAllocator::free
void free(T *p)
right now there is no compaction
Definition: ListAllocator.h:67
groupallocator::ListAllocator
not thread safe and no compaction
Definition: ListAllocator.h:21