From bb9909548b3cb7e26e2b3f0e30249f779bcd3128 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Thu, 8 Aug 2019 13:39:40 +0200 Subject: [PATCH] AK: Add an iterator class for InlineLinkedList This makes it possible to iterate over these with range-for. :^) --- AK/InlineLinkedList.h | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/AK/InlineLinkedList.h b/AK/InlineLinkedList.h index 08e4fbdb26..87962372f2 100644 --- a/AK/InlineLinkedList.h +++ b/AK/InlineLinkedList.h @@ -5,6 +5,33 @@ namespace AK { +template +class InlineLinkedList; + +template +class InlineLinkedListIterator { +public: + bool operator!=(const InlineLinkedListIterator& other) const { return m_node != other.m_node; } + bool operator==(const InlineLinkedListIterator& other) const { return m_node == other.m_node; } + InlineLinkedListIterator& operator++() + { + m_node = m_node->next(); + return *this; + } + T& operator*() { return *m_node; } + T* operator->() { return &m_node; } + bool is_end() const { return !m_node; } + static InlineLinkedListIterator universal_end() { return InlineLinkedListIterator(nullptr); } + +private: + friend InlineLinkedList; + explicit InlineLinkedListIterator(T* node) + : m_node(node) + { + } + T* m_node; +}; + template class InlineLinkedListNode { public: @@ -77,6 +104,16 @@ public: return false; } + using Iterator = InlineLinkedListIterator; + friend Iterator; + Iterator begin() { return Iterator(m_head); } + Iterator end() { return Iterator::universal_end(); } + + using ConstIterator = InlineLinkedListIterator; + friend ConstIterator; + ConstIterator begin() const { return ConstIterator(m_head); } + ConstIterator end() const { return ConstIterator::universal_end(); } + private: T* m_head { nullptr }; T* m_tail { nullptr };