OLD | NEW |
| (Empty) |
1 /* | |
2 * Copyright 2016 Google Inc. | |
3 * | |
4 * Use of this source code is governed by a BSD-style license that can be | |
5 * found in the LICENSE file. | |
6 */ | |
7 #ifndef SkSinglyLinkedList_DEFINED | |
8 #define SkSinglyLinkedList_DEFINED | |
9 | |
10 #include <utility> | |
11 | |
12 #include "SkTypes.h" | |
13 | |
14 template <typename T> class SkSinglyLinkedList { | |
15 struct Node; | |
16 public: | |
17 SkSinglyLinkedList() : fHead(nullptr), fTail(nullptr) {} | |
18 ~SkSinglyLinkedList() { this->reset(); } | |
19 void reset() { | |
20 SkASSERT(fHead != nullptr || nullptr == fTail); | |
21 // Use a while loop rather than recursion to avoid stack overflow. | |
22 Node* node = fHead; | |
23 while (node) { | |
24 Node* next = node->fNext; | |
25 SkASSERT(next != nullptr || node == fTail); | |
26 delete node; | |
27 node = next; | |
28 } | |
29 fHead = nullptr; | |
30 fTail = nullptr; | |
31 } | |
32 T* back() { return fTail ? &fTail->fData : nullptr; } | |
33 T* front() { return fHead ? &fHead->fData : nullptr; } | |
34 #ifdef SK_DEBUG | |
35 int count() { // O(n), debug only. | |
36 int count = 0; | |
37 for (Node* node = fHead; node; node = node->fNext) { | |
38 ++count; | |
39 } | |
40 return count; | |
41 } | |
42 #endif | |
43 void pop_front() { | |
44 if (Node* node = fHead) { | |
45 fHead = node->fNext; | |
46 delete node; | |
47 if (fHead == nullptr) { | |
48 fTail = nullptr; | |
49 } | |
50 } | |
51 } | |
52 template <class... Args> T* emplace_front(Args&&... args) { | |
53 Node* n = new Node(std::forward<Args>(args)...); | |
54 n->fNext = fHead; | |
55 if (!fTail) { | |
56 fTail = n; | |
57 SkASSERT(!fHead); | |
58 } | |
59 fHead = n; | |
60 return &n->fData; | |
61 } | |
62 template <class... Args> T* emplace_back(Args&&... args) { | |
63 Node* n = new Node(std::forward<Args>(args)...); | |
64 if (fTail) { | |
65 fTail->fNext = n; | |
66 } else { | |
67 fHead = n; | |
68 } | |
69 fTail = n; | |
70 return &n->fData; | |
71 } | |
72 class ConstIter { | |
73 public: | |
74 void operator++() { fNode = fNode->fNext; } | |
75 const T& operator*() const { return fNode->fData; } | |
76 bool operator!=(const ConstIter& rhs) const { return fNode != rhs.fNode;
} | |
77 ConstIter(const Node* n) : fNode(n) {} | |
78 private: | |
79 const Node* fNode; | |
80 }; | |
81 ConstIter begin() const { return ConstIter(fHead); } | |
82 ConstIter end() const { return ConstIter(nullptr); } | |
83 | |
84 private: | |
85 struct Node { | |
86 T fData; | |
87 Node* fNext; | |
88 template <class... Args> | |
89 Node(Args&&... args) : fData(std::forward<Args>(args)...), fNext(nullptr
) {} | |
90 }; | |
91 Node* fHead; | |
92 Node* fTail; | |
93 SkSinglyLinkedList(const SkSinglyLinkedList<T>&) = delete; | |
94 SkSinglyLinkedList& operator=(const SkSinglyLinkedList<T>&) = delete; | |
95 }; | |
96 #endif // SkSinglyLinkedList_DEFINED | |
OLD | NEW |