Lugdunum  0.1.0
FreeList.cpp
Go to the documentation of this file.
2 #include <memory>
3 #include <lug/System/Debug.hpp>
4 
5 namespace lug {
6 namespace System {
7 namespace Memory {
8 
9 FreeList::FreeList(size_t size) : _size(size) {
10  LUG_ASSERT(_size > sizeof(FreeList::Element*), "The size is not enough for this implementation of freelist");
11 }
12 
13 bool FreeList::grow(void* start, void* end, size_t alignment, size_t offset) {
14  // First, align the start pointer
15  {
16  start = static_cast<char*>(start) + offset;
17 
18  if (start > end) {
19  return false;
20  }
21 
22  size_t size = static_cast<char*>(end) - static_cast<char*>(start) + 1;
23 
24  if (!std::align(alignment, _size - offset, start, size)) {
25  return false;
26  }
27 
28  start = static_cast<char*>(start) - offset;
29  }
30 
31  // Second create the linked list
32  {
33  Element* it = static_cast<Element*>(start);
34  _nextFree = it;
35 
36  size_t size = static_cast<char*>(end) - static_cast<char*>(start) + 1;
37 
38  for (size_t i = 1, count = size / _size; i < count; ++i) {
39  void* const next = static_cast<char*>(static_cast<void*>(it)) + _size;
40 
41  it->next = static_cast<Element*>(next);
42  it = static_cast<Element*>(next);
43  }
44 
45  it->next = nullptr;
46  }
47 
48  return true;
49 }
50 
52  if (!_nextFree) {
53  return nullptr;
54  }
55 
56  Element* const head = _nextFree;
58  return head;
59 }
60 
61 void FreeList::free(void* ptr) {
62  Element* const head = static_cast<Element*>(ptr);
63 
64  head->next = _nextFree;
65  _nextFree = head;
66 }
67 
69  _nextFree = nullptr;
70 }
71 
72 } // Memory
73 } // System
74 } // lug
#define LUG_ASSERT(assertion, message)
Definition: Debug.hpp:38
bool grow(void *start, void *end, size_t alignment, size_t offset)
Definition: FreeList.cpp:13