Node.js  v8.x
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine
freelist.h
Go to the documentation of this file.
1 #ifndef SRC_FREELIST_H_
2 #define SRC_FREELIST_H_
3 
4 #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
5 
6 #include "util.h"
7 
8 namespace node {
9 
10 struct DefaultFreelistTraits;
11 
12 template <typename T,
13  size_t kMaximumLength,
14  typename FreelistTraits = DefaultFreelistTraits>
15 class Freelist {
16  public:
17  typedef struct list_item {
18  T* item = nullptr;
19  list_item* next = nullptr;
20  } list_item;
21 
22  Freelist() {}
23  ~Freelist() {
24  while (head_ != nullptr) {
25  list_item* item = head_;
26  head_ = item->next;
27  FreelistTraits::Free(item->item);
28  free(item);
29  }
30  }
31 
32  void push(T* item) {
33  if (size_ > kMaximumLength) {
34  FreelistTraits::Free(item);
35  } else {
36  size_++;
37  FreelistTraits::Reset(item);
38  list_item* li = Calloc<list_item>(1);
39  li->item = item;
40  if (head_ == nullptr) {
41  head_ = li;
42  tail_ = li;
43  } else {
44  tail_->next = li;
45  tail_ = li;
46  }
47  }
48  }
49 
50  T* pop() {
51  if (head_ != nullptr) {
52  size_--;
53  list_item* cur = head_;
54  T* item = cur->item;
55  head_ = cur->next;
56  free(cur);
57  return item;
58  } else {
59  return FreelistTraits::template Alloc<T>();
60  }
61  }
62 
63  private:
64  size_t size_ = 0;
65  list_item* head_ = nullptr;
66  list_item* tail_ = nullptr;
67 };
68 
69 struct DefaultFreelistTraits {
70  template <typename T>
71  static T* Alloc() {
72  return ::new (Malloc<T>(1)) T();
73  }
74 
75  template <typename T>
76  static void Free(T* item) {
77  item->~T();
78  free(item);
79  }
80 
81  template <typename T>
82  static void Reset(T* item) {
83  item->~T();
84  ::new (item) T();
85  }
86 };
87 
88 } // namespace node
89 
90 #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
91 
92 #endif // SRC_FREELIST_H_
size_t size_