Skip to content

Commit c02c2bc

Browse files
committed
[NFC] Add an iterator template for walking singly-linked lists.
1 parent 8bc6f83 commit c02c2bc

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

include/swift/Basic/STLExtras.h

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,47 @@ inline Iterator prev_or_begin(Iterator it, Iterator begin) {
217217

218218
/// @}
219219

220+
/// An iterator that walks a linked list of objects until it reaches
221+
/// a null pointer.
222+
template <class T, T* (&getNext)(T*)>
223+
class LinkedListIterator {
224+
T *Pointer;
225+
public:
226+
using iterator_category = std::forward_iterator_tag;
227+
using value_type = T *;
228+
using reference = T *;
229+
using pointer = void;
230+
231+
/// Returns an iterator range starting from the given pointer and
232+
/// running until it reaches a null pointer.
233+
static llvm::iterator_range<LinkedListIterator> rangeBeginning(T *pointer) {
234+
return {pointer, nullptr};
235+
}
236+
237+
constexpr LinkedListIterator(T *pointer) : Pointer(pointer) {}
238+
239+
T *operator*() const {
240+
assert(Pointer && "dereferencing a null iterator");
241+
return Pointer;
242+
}
243+
244+
LinkedListIterator &operator++() {
245+
Pointer = getNext(Pointer);
246+
return *this;
247+
}
248+
LinkedListIterator operator++(int) {
249+
auto copy = *this;
250+
Pointer = getNext(Pointer);
251+
return copy;
252+
}
253+
254+
friend bool operator==(LinkedListIterator lhs, LinkedListIterator rhs) {
255+
return lhs.Pointer == rhs.Pointer;
256+
}
257+
friend bool operator!=(LinkedListIterator lhs, LinkedListIterator rhs) {
258+
return lhs.Pointer != rhs.Pointer;
259+
}
260+
};
220261

221262
/// An iterator that transforms the result of an underlying bidirectional
222263
/// iterator with a given operation.

0 commit comments

Comments
 (0)