-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
99 lines (84 loc) · 2.23 KB
/
stack.cpp
File metadata and controls
99 lines (84 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "stack.hpp"
#include <functional>
#include <cstring>
Stack::Stack() : SP(data), HP(SP + MAX_ADDRESS + 1) {
}
void Stack::push(int_type value) {
*SP = value;
SP++;
}
int_type Stack::pop() {
SP--;
return *SP;
}
int_type Stack::load(int_type address) {
return *(data+address);
}
void Stack::store(int_type address, int_type value) {
*(data+address) = value;
}
void Stack::dup() {
this->push(*(SP-1));
}
void Stack::reserveStackSpace(int_type size) {
SP += size;
}
void Stack::removeStackSpace(int_type size) {
SP -= size;
}
int_type Stack::reserveHeapSpace(int_type size) {
auto last = MAX_ADDRESS + 1;
for(const auto &entry : heapEntries) {
if(last - (entry.address + entry.size) >= size) {
HeapData newEntry;
newEntry.address = entry.address + entry.size;
newEntry.size = size;
heapEntries.push_back(newEntry);
std::sort(heapEntries.begin(), heapEntries.end(), [](HeapData a, HeapData b) { return a.address > b.address; });
return newEntry.address;
}
}
HP -= size;
HeapData newEntry;
newEntry.address = HP - data;
newEntry.size = size;
heapEntries.push_back(newEntry);
std::sort(heapEntries.begin(), heapEntries.end(), [](HeapData a, HeapData b) { return a.address > b.address; });
return newEntry.address;
return 0;
}
void Stack::removeHeapSpace(int_type address) {
for(auto it = heapEntries.begin(); it != heapEntries.end(); it++) {
if(it->address == address) {
heapEntries.erase(it);
return;
}
}
}
int_type Stack::resizeHeapSpace(int_type address, int_type new_size) {
auto it = std::find_if(heapEntries.begin(), heapEntries.end(), [address](HeapData data) { return data.address == address; });
if(it == heapEntries.end()) {
return reserveHeapSpace(new_size);
}
auto size = it->size;
auto next = it + 1;
if(next != heapEntries.end()) {
if(next->address - it->address >= new_size) {
it->size = new_size;
return address;
}
}
removeHeapSpace(address);
auto new_address = reserveHeapSpace(new_size);
if(new_address == 0) {
return 0;
}
std::memcpy(&data[new_address], &data[address], size);
return new_address;
}
bool Stack::isEmpty() const {
return SP == data;
}
void Stack::reset() {
SP = data;
}