My Project
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Modules
mem_pool.h
Go to the documentation of this file.
1 #pragma once
2 #include <3ds.h>
3 
4 struct MemChunk
5 {
6  u8* addr;
8 };
9 
10 struct MemBlock
11 {
13  u8* base;
15 
16  static MemBlock* Create(u8* base, u32 size)
17  {
18  auto b = (MemBlock*)malloc(sizeof(MemBlock));
19  if (!b) return nullptr;
20  b->prev = nullptr;
21  b->next = nullptr;
22  b->base = base;
23  b->size = size;
24  return b;
25  }
26 };
27 
28 struct MemPool
29 {
31 
32  bool Ready() { return first != nullptr; }
33 
34  void AddBlock(MemBlock* blk)
35  {
36  blk->prev = last;
37  if (last) last->next = blk;
38  if (!first) first = blk;
39  last = blk;
40  }
41 
42  void DelBlock(MemBlock* b)
43  {
44  auto prev = b->prev, &pNext = prev ? prev->next : first;
45  auto next = b->next, &nPrev = next ? next->prev : last;
46  pNext = next;
47  nPrev = prev;
48  free(b);
49  }
50 
52  {
53  auto prev = b->prev, &pNext = prev ? prev->next : first;
54  b->prev = p;
55  p->next = b;
56  p->prev = prev;
57  pNext = p;
58  }
59 
61  {
62  auto next = b->next, &nPrev = next ? next->prev : last;
63  b->next = n;
64  n->prev = b;
65  n->next = next;
66  nPrev = n;
67  }
68 
69  //void CoalesceLeft(MemBlock* b);
70  void CoalesceRight(MemBlock* b);
71 
72  bool Allocate(MemChunk& chunk, u32 size, int align);
73  void Deallocate(const MemChunk& chunk);
74 
75  void Destroy()
76  {
77  MemBlock* next = nullptr;
78  for (auto b = first; b; b = next)
79  {
80  next = b->next;
81  free(b);
82  }
83  first = nullptr;
84  last = nullptr;
85  }
86 
87  //void Dump(const char* title);
88  u32 GetFreeSpace();
89 };
void InsertAfter(MemBlock *b, MemBlock *n)
Definition: mem_pool.h:60
u32 size
Definition: mem_pool.h:7
void CoalesceRight(MemBlock *b)
Definition: mem_pool.cpp:19
bool Ready()
Definition: mem_pool.h:32
void Deallocate(const MemChunk &chunk)
Definition: mem_pool.cpp:76
void Destroy()
Definition: mem_pool.h:75
uint8_t u8
Definition: types.h:21
uint32_t u32
Definition: types.h:23
u32 GetFreeSpace()
Definition: mem_pool.cpp:127
MemBlock * next
Definition: mem_pool.h:12
MemBlock * first
Definition: mem_pool.h:30
u8 * base
Definition: mem_pool.h:13
u32 size
Definition: mem_pool.h:14
MemBlock * last
Definition: mem_pool.h:30
void InsertBefore(MemBlock *b, MemBlock *p)
Definition: mem_pool.h:51
void DelBlock(MemBlock *b)
Definition: mem_pool.h:42
void AddBlock(MemBlock *blk)
Definition: mem_pool.h:34
bool Allocate(MemChunk &chunk, u32 size, int align)
Definition: mem_pool.cpp:33
u8 * addr
Definition: mem_pool.h:6
static MemBlock * Create(u8 *base, u32 size)
Definition: mem_pool.h:16
MemBlock * prev
Definition: mem_pool.h:12