VOX
A little voxel engine
Loading...
Searching...
No Matches
MemoryRange.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "logger.hpp"
4
5#include <cstdint>
6#include <map>
7
9{
10
11public:
12
14
15 MemoryRange(const uint64_t & capacity = 0):
16 m_capacity(capacity)
17 {
18 }
19
20 uint64_t capacity() { return m_capacity; }
21
22 void add(const uint64_t & capacity)
23 {
24 m_capacity += capacity;
25 }
26
27 uint64_t alloc(const uint64_t & alloc_size)
28 {
29 uint64_t address = 0;
30
31 if (m_used_ranges.empty() && m_capacity >= alloc_size)
32 {
33 m_used_ranges[0] = alloc_size;
34 return 0;
35 }
36
37 for (auto it = m_used_ranges.begin(); it != m_used_ranges.end(); ++it)
38 {
39 if (it->first - address >= alloc_size)
40 {
41 m_used_ranges[address] = alloc_size;
42 return address;
43 }
44 address = it->first + it->second;
45 }
46
47 if (m_capacity - address >= alloc_size)
48 {
49 m_used_ranges[address] = alloc_size;
50 return address;
51 }
52
53 return capacity();
54 }
55
56 void free(const uint64_t & address)
57 {
58 m_used_ranges.erase(address);
59 }
60
61private:
62
63 std::map<uint64_t, uint64_t> m_used_ranges;
64 uint64_t m_capacity;
65
66};
67
68// add 10
69// 0 10
70
71// alloc 5
72// 0 0 5 10
73
74// add 10
75// 0 0 5 20
76
77// alloc 10
78// 0 0 5 5 15 20
79
80// free 0
81// 0 5 15 20
Definition: MemoryRange.hpp:9
~MemoryRange()
Definition: MemoryRange.hpp:13
MemoryRange(const uint64_t &capacity=0)
Definition: MemoryRange.hpp:15
void add(const uint64_t &capacity)
Definition: MemoryRange.hpp:22
uint64_t alloc(const uint64_t &alloc_size)
Definition: MemoryRange.hpp:27
uint64_t capacity()
Definition: MemoryRange.hpp:20
void free(const uint64_t &address)
Definition: MemoryRange.hpp:56