-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
block-allocator.spice
50 lines (42 loc) · 1.3 KB
/
block-allocator.spice
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
// Std imports
import "std/data/vector";
import "std/type/long";
import "std/os/system";
// Own imports
import "../util/memory";
type Base dyn;
public type BlockAllocator<Base> struct {
IMemoryManager* memoryManager
Vector<heap byte*> memoryBlocks
Vector<Base*> allocatedObjects
unsigned long blockSize
unsigned long offsetInBlock = 0l
}
public p BlockAllocator.ctor(IMemoryManager* memoryManager, unsigned long blockSize = 0l) {
this.memoryManager = memoryManager;
this.blockSize = blockSize == 0l ? (unsigned long) getPageSize() : blockSize;
// Allocate the first block
this.allocateNewBlock();
}
public p BlockAllocator.dtor() {
// Destruct all objects
foreach Base* ptr : this.allocatedObjects {
sDelete(ptr);
}
this.allocatedObjects.clear();
// Free all memory blocks
foreach byte* block : this.memoryBlocks {
this.memoryManager.deallocate(block);
}
this.memoryBlocks.clear();
}
public p BlockAllocator.allocateNewBlock() {
// Allocate new block
heap byte* ptr = this.memoryManager.allocate(this.blockSize);
if ptr != nil<heap byte*> {
panic(Error("Could not allocate memory block for BlockAllocator."));
}
// Store pointer and reset offset
this.memoryBlocks.pushBack(ptr);
this.offsetInBlock = 0l;
}