forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfreelist.h
92 lines (77 loc) · 1.7 KB
/
freelist.h
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
#ifndef SRC_FREELIST_H_
#define SRC_FREELIST_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "util.h"
namespace node {
struct DefaultFreelistTraits;
template <typename T,
size_t kMaximumLength,
typename FreelistTraits = DefaultFreelistTraits>
class Freelist {
public:
typedef struct list_item {
T* item = nullptr;
list_item* next = nullptr;
} list_item;
Freelist() {}
~Freelist() {
while (head_ != nullptr) {
list_item* item = head_;
head_ = item->next;
FreelistTraits::Free(item->item);
free(item);
}
}
void push(T* item) {
if (size_ > kMaximumLength) {
FreelistTraits::Free(item);
} else {
size_++;
FreelistTraits::Reset(item);
list_item* li = Calloc<list_item>(1);
li->item = item;
if (head_ == nullptr) {
head_ = li;
tail_ = li;
} else {
tail_->next = li;
tail_ = li;
}
}
}
T* pop() {
if (head_ != nullptr) {
size_--;
list_item* cur = head_;
T* item = cur->item;
head_ = cur->next;
free(cur);
return item;
} else {
return FreelistTraits::template Alloc<T>();
}
}
private:
size_t size_ = 0;
list_item* head_ = nullptr;
list_item* tail_ = nullptr;
};
struct DefaultFreelistTraits {
template <typename T>
static T* Alloc() {
return ::new (Malloc<T>(1)) T();
}
template <typename T>
static void Free(T* item) {
item->~T();
free(item);
}
template <typename T>
static void Reset(T* item) {
item->~T();
::new (item) T();
}
};
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_FREELIST_H_