CookMem 1.4.0
A C++ memory context / allocator
Loading...
Searching...
No Matches
circularlist.h
1/*
2 * Copyright (c) 2018-2021 Heng Yuan
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef COOK_MEM_CIRCULAR_LIST_H
17#define COOK_MEM_CIRCULAR_LIST_H
18
19#include "exception.h"
20
21namespace cookmem
22{
23
29template<class Node>
31{
32public:
33 CircularList () : m_head (nullptr) {}
34
41 void
42 add (Node* ptr)
43 {
44 if (m_head)
45 {
46 Node* curr = m_head;
47 Node* next = m_head->next;
48 curr->next = ptr;
49 next->prev = ptr;
50 ptr->next = next;
51 ptr->prev = curr;
52 }
53 else
54 {
55 ptr->next = ptr;
56 ptr->prev = ptr;
57 m_head = ptr;
58 }
59 }
60
66 Node*
68 {
69 if (m_head == nullptr)
70 {
71 return nullptr;
72 }
73
74 Node* prev = m_head->prev;
75 Node* next = m_head->next;
76 Node* head = m_head;
77
78 if (m_head == prev)
79 {
80 COOKMEM_ASSERT(m_head == next);
81 m_head = nullptr;
82 }
83 else
84 {
85 prev->next = next;
86 next->prev = prev;
87 m_head = next;
88 }
89
90 return head;
91 }
92
101 bool
102 remove (Node* chunk)
103 {
104 Node* prev = chunk->prev;
105 Node* next = chunk->next;
106
107 if (prev == chunk)
108 {
109 COOKMEM_ASSERT(m_head == chunk && next == chunk);
110 m_head = nullptr;
111 return true;
112 }
113 else
114 {
115 if (m_head == chunk)
116 {
117 m_head = next;
118 }
119 prev->next = next;
120 next->prev = prev;
121 return false;
122 }
123 }
124
128 bool
130 {
131 if (m_head == nullptr)
132 {
133 return false;
134 }
135 Node* node = m_head;
136 do
137 {
138 if (node == chunk)
139 {
140 return true;
141 }
142 node = node->next;
143 }
144 while (node != m_head);
145 return false;
146 }
147
154 bool isEmpty () const { return m_head == nullptr; }
155
156private:
158 Node* m_head;
159};
160
161} // namespace cookmem
162
163#endif // COOK_MEM_CIRCULAR_LIST_H
Definition circularlist.h:31
bool remove(Node *chunk)
Definition circularlist.h:102
Node * remove()
Definition circularlist.h:67
bool contains(Node *chunk)
Definition circularlist.h:129
bool isEmpty() const
Definition circularlist.h:154
void add(Node *ptr)
Definition circularlist.h:42
Definition allocator.h:39
Definition allocator.h:29