| 1 | // -*- C++ -*- |
| 2 | |
| 3 | /* |
| 4 | |
| 5 | Heap Layers: An Extensible Memory Allocation Infrastructure |
| 6 | |
| 7 | Copyright (C) 2000-2020 by Emery Berger |
| 8 | http://www.emeryberger.com |
| 9 | [email protected] |
| 10 | |
| 11 | Heap Layers is distributed under the terms of the Apache 2.0 license. |
| 12 | |
| 13 | You may obtain a copy of the License at |
| 14 | http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | |
| 16 | */ |
| 17 | |
| 18 | #ifndef HL_DLLIST_H |
| 19 | #define HL_DLLIST_H |
| 20 | |
| 21 | #include <assert.h> |
| 22 | |
| 23 | /** |
| 24 | * |
| 25 | * @class DLList |
| 26 | * @brief A "memory neutral" (intrusive) doubly-linked list. |
| 27 | * @author Emery Berger |
| 28 | */ |
| 29 | |
| 30 | namespace HL { |
| 31 | |
| 32 | class DLList { |
| 33 | public: |
| 34 | |
| 35 | inline DLList() { |
| 36 | clear(); |
| 37 | } |
| 38 | |
| 39 | class Entry; |
| 40 | |
| 41 | /// Clear the list. |
| 42 | inline void clear() { |
| 43 | head.setPrev (&head); |
| 44 | head.setNext (&head); |
| 45 | } |
| 46 | |
| 47 | /// Is the list empty? |
| 48 | inline bool isEmpty() const { |
| 49 | return (head.getNext() == &head); |
| 50 | } |
| 51 | |
| 52 | /// Get the head of the list. |
| 53 | inline Entry * get() { |
| 54 | const Entry * e = head.next; |
| 55 | if (e == &head) { |
| 56 | return nullptr; |
| 57 | } |
| 58 | head.next = e->next; |
| 59 | head.next->prev = &head; |
| 60 | return (Entry *) e; |
| 61 | } |
| 62 | |
| 63 | /// Remove one item from the list. |
| 64 | inline void remove (Entry * e) { |
| 65 | e->remove(); |
| 66 | } |
| 67 | |
| 68 | /// Insert an entry into the head of the list. |
| 69 | inline void insert (Entry * e) { |
| 70 | e->insert (&head, head.next); |
| 71 | } |
| 72 | |
| 73 | /// An entry in the list. |
| 74 | class Entry { |
| 75 | public: |
| 76 | // private: |
| 77 | inline void setPrev (Entry * p) { assert (p != nullptr); prev = p; } |
| 78 | inline void setNext (Entry * p) { assert (p != nullptr); next = p; } |
| 79 | inline Entry * getPrev() const { return prev; } |
| 80 | inline Entry * getNext() const { return next; } |
| 81 | inline void remove() const { |
| 82 | prev->setNext(next); |
| 83 | next->setPrev(prev); |
| 84 | } |
| 85 | inline void insert (Entry * p, Entry * n) { |
| 86 | prev = p; |
| 87 | next = n; |
| 88 | p->setNext (this); |
| 89 | n->setPrev (this); |
| 90 | } |
| 91 | Entry * prev; |
| 92 | Entry * next; |
| 93 | }; |
| 94 | |
| 95 | |
| 96 | private: |
| 97 | |
| 98 | /// The head of the list. |
| 99 | Entry head; |
| 100 | |
| 101 | }; |
| 102 | |
| 103 | } |
| 104 | |
| 105 | #endif |