-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlab.cpp
More file actions
75 lines (53 loc) · 1.53 KB
/
Copy pathSlab.cpp
File metadata and controls
75 lines (53 loc) · 1.53 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
#include "Slab.hpp"
#include <cstdlib>
#include <cstring>
#include <iostream>
namespace slab {
Slab::Slab(size_t chunkSize) : chunkSize_(chunkSize), memory_(nullptr), freeList_(nullptr) {
memory_ = malloc(kSlabSize);
for (size_t i = 0; i < kSlabSize; i += chunkSize_) {
void* chunk = ((char*)memory_) + i;
Node* node = (Node*)chunk;
node->next = freeList_;
freeList_ = node;
}
// std::cout << "Slab initialized with " << kSlabSize << " bytes" << std::endl;
}
Slab::~Slab() {
free(memory_);
freeList_ = nullptr;
}
void* Slab::allocate() {
if (freeList_ == nullptr) return nullptr;
Node* node = freeList_;
freeList_ = node->next;
return (void*)node;
}
void Slab::deallocate(void* ptr) {
auto* base = (char*)memory_;
auto* end_of_slab = ((char*)memory_ + kSlabSize);
auto* p = (char*)ptr;
if(p >= base && p < end_of_slab) {
Node* node = (Node*)ptr;
node->next = freeList_;
freeList_ = node;
}
}
bool Slab::empty() const {
size_t totalChunks = kSlabSize / chunkSize_;
size_t freeChunks = 0;
Node* current = freeList_;
while (current != nullptr) {
freeChunks++;
current = current->next;
}
return freeChunks == totalChunks;
}
bool Slab::contains(void* ptr) const {
auto* base = (char*)memory_;
auto* end_of_slab = ((char*)memory_ + kSlabSize);
auto* p = (char*)ptr;
if(p >= base && p < end_of_slab) return true;
return false;
}
} // namespace slab