diff options
-rw-r--r-- | AK/ReverseIterator.h | 18 | ||||
-rw-r--r-- | Tests/AK/TestVector.cpp | 11 |
2 files changed, 28 insertions, 1 deletions
diff --git a/AK/ReverseIterator.h b/AK/ReverseIterator.h index cd62c21c4c..566a098df1 100644 --- a/AK/ReverseIterator.h +++ b/AK/ReverseIterator.h @@ -87,4 +87,22 @@ private: int m_index { 0 }; }; +namespace ReverseWrapper { + +template<typename Container> +struct ReverseWrapper { + Container& container; +}; + +template<typename Container> +auto begin(ReverseWrapper<Container> wrapper) { return wrapper.container.rbegin(); } + +template<typename Container> +auto end(ReverseWrapper<Container> wrapper) { return wrapper.container.rend(); } + +template<typename Container> +ReverseWrapper<Container> in_reverse(Container&& container) { return { container }; } + +} + } diff --git a/Tests/AK/TestVector.cpp b/Tests/AK/TestVector.cpp index 4cfa6da98d..fe10b017cf 100644 --- a/Tests/AK/TestVector.cpp +++ b/Tests/AK/TestVector.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include "AK/ReverseIterator.h" #include <LibTest/TestCase.h> #include <AK/NonnullOwnPtrVector.h> @@ -552,10 +553,18 @@ TEST_CASE(rend) EXPECT_EQ(*expected, *expected_in_reverse); } -TEST_CASE(reverse_loop) +TEST_CASE(reverse_iterator_for_loop) { Vector<int> v { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int index = 9; for (auto rev = v.rbegin(); rev != v.rend(); ++rev) EXPECT_EQ(*rev, index--); } + +TEST_CASE(reverse_range_for_loop) +{ + Vector<int> v { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + int index = 9; + for (auto item : AK::ReverseWrapper::in_reverse(v)) + EXPECT_EQ(item, index--); +} |