[PATCH] D122009: [ADT] Add drop_end.

Marek Kurdej via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Fri Mar 18 08:19:08 PDT 2022


curdeius created this revision.
curdeius added a reviewer: dblaikie.
Herald added a subscriber: dexonsmith.
Herald added a project: All.
curdeius requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

This patch adds drop_end that is analogical to drop_begin.
It tries to fill the functional gap where one could drop first elements but not the last ones.
The need for it came in when refactoring clang-format.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122009

Files:
  llvm/include/llvm/ADT/STLExtras.h
  llvm/unittests/ADT/STLExtrasTest.cpp


Index: llvm/unittests/ADT/STLExtrasTest.cpp
===================================================================
--- llvm/unittests/ADT/STLExtrasTest.cpp
+++ llvm/unittests/ADT/STLExtrasTest.cpp
@@ -457,6 +457,30 @@
   EXPECT_EQ(i, 5);
 }
 
+TEST(STLExtrasTest, DropEndTest) {
+  SmallVector<int, 5> vec{0, 1, 2, 3, 4};
+
+  for (int n = 0; n < 5; ++n) {
+    int i = 0;
+    for (auto &v : drop_end(vec, n)) {
+      EXPECT_EQ(v, i);
+      i += 1;
+    }
+    EXPECT_EQ(i, 5 - n);
+  }
+}
+
+TEST(STLExtrasTest, DropEndDefaultTest) {
+  SmallVector<int, 5> vec{0, 1, 2, 3, 4};
+
+  int i = 0;
+  for (auto &v : drop_end(vec)) {
+    EXPECT_EQ(v, i);
+    i += 1;
+  }
+  EXPECT_EQ(i, 4);
+}
+
 TEST(STLExtrasTest, EarlyIncrementTest) {
   std::list<int> L = {1, 2, 3, 4};
 
Index: llvm/include/llvm/ADT/STLExtras.h
===================================================================
--- llvm/include/llvm/ADT/STLExtras.h
+++ llvm/include/llvm/ADT/STLExtras.h
@@ -268,6 +268,13 @@
                     adl_end(RangeOrContainer));
 }
 
+/// Return a range covering \p RangeOrContainer with the last N elements
+/// excluded.
+template <typename T> auto drop_end(T &&RangeOrContainer, size_t N = 1) {
+  return make_range(adl_begin(RangeOrContainer),
+                    std::prev(adl_end(RangeOrContainer), N));
+}
+
 // mapped_iterator - This is a simple iterator adapter that causes a function to
 // be applied whenever operator* is invoked on the iterator.
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D122009.416514.patch
Type: text/x-patch
Size: 1463 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20220318/1a526d4d/attachment.bin>


More information about the llvm-commits mailing list