[llvm] [ADT] Add `llvm::conditionally_reverse()` iterator (PR #171040)

Benjamin Maxwell via llvm-commits llvm-commits at lists.llvm.org
Sun Dec 7 11:05:36 PST 2025


https://github.com/MacDue updated https://github.com/llvm/llvm-project/pull/171040

>From 3b1a5867390fef585445f2e69203ecd9cde66d60 Mon Sep 17 00:00:00 2001
From: MacDue <macdue at dueutil.tech>
Date: Sun, 7 Dec 2025 19:05:13 +0000
Subject: [PATCH] Rework

---
 llvm/include/llvm/ADT/STLExtras.h    | 12 ++++++++++++
 llvm/unittests/ADT/STLExtrasTest.cpp | 24 ++++++++++++++++++++++++
 2 files changed, 36 insertions(+)

diff --git a/llvm/include/llvm/ADT/STLExtras.h b/llvm/include/llvm/ADT/STLExtras.h
index af0e4a36be1b1..cac429830d9ed 100644
--- a/llvm/include/llvm/ADT/STLExtras.h
+++ b/llvm/include/llvm/ADT/STLExtras.h
@@ -1415,6 +1415,18 @@ template <typename ContainerTy> auto make_second_range(ContainerTy &&c) {
       });
 }
 
+/// Return a range that conditionally reverses \p C. The collection is iterated
+/// in reverse if \p ShouldReverse is true (otherwise, it is iterated forwards).
+template <typename ContainerTy>
+[[nodiscard]] auto reverse_conditionally(ContainerTy &&C, bool ShouldReverse) {
+  using ForwardIteratorT = decltype(C.begin());
+  return map_range(zip_equal(reverse(C), C),
+                   [ShouldReverse](auto I) ->
+                   typename std::iterator_traits<ForwardIteratorT>::reference {
+                     return ShouldReverse ? std::get<0>(I) : std::get<1>(I);
+                   });
+}
+
 //===----------------------------------------------------------------------===//
 //     Extra additions to <utility>
 //===----------------------------------------------------------------------===//
diff --git a/llvm/unittests/ADT/STLExtrasTest.cpp b/llvm/unittests/ADT/STLExtrasTest.cpp
index 85567775e4ebd..e356f6b540568 100644
--- a/llvm/unittests/ADT/STLExtrasTest.cpp
+++ b/llvm/unittests/ADT/STLExtrasTest.cpp
@@ -1693,6 +1693,30 @@ TEST(STLExtrasTest, ProductOf) {
   EXPECT_EQ(product_of(V3), 2.0f);
 }
 
+TEST(STLExtrasTest, ReverseConditionally) {
+  std::vector<char> foo = {'a', 'b', 'c'};
+
+  // Test backwards.
+  std::vector<char> ReverseResults;
+  for (char Value : llvm::reverse_conditionally(foo, /*ShouldReverse=*/true)) {
+    ReverseResults.emplace_back(Value);
+  }
+  EXPECT_THAT(ReverseResults, ElementsAre('c', 'b', 'a'));
+
+  // Test forwards.
+  std::vector<char> ForwardResults;
+  for (char Value : llvm::reverse_conditionally(foo, /*ShouldReverse=*/false)) {
+    ForwardResults.emplace_back(Value);
+  }
+  EXPECT_THAT(ForwardResults, ElementsAre('a', 'b', 'c'));
+
+  // Test modifying collection.
+  for (char &Value : llvm::reverse_conditionally(foo, /*ShouldReverse=*/true)) {
+    ++Value;
+  }
+  EXPECT_THAT(foo, ElementsAre('b', 'c', 'd'));
+}
+
 struct Foo;
 struct Bar {};
 



More information about the llvm-commits mailing list