From 38dbb0292df0468fedd0deb0a21d5d1720f8e2f5 Mon Sep 17 00:00:00 2001 From: David Majnemer Date: Sat, 5 Jul 2014 06:12:30 +0000 Subject: [PATCH] ADT: Add a drop_back() helper to ArrayRef The slice(N, M) interface is powerful but not concise when wanting to drop a few elements off of an ArrayRef, fix this by adding a drop_back method. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@212370 91177308-0d34-0410-b5e6-96231b3b80d8 --- include/llvm/ADT/ArrayRef.h | 6 ++++++ unittests/ADT/ArrayRefTest.cpp | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/include/llvm/ADT/ArrayRef.h b/include/llvm/ADT/ArrayRef.h index 1b64fee9a59..0fff505d8d0 100644 --- a/include/llvm/ADT/ArrayRef.h +++ b/include/llvm/ADT/ArrayRef.h @@ -147,6 +147,12 @@ namespace llvm { return ArrayRef(data()+N, M); } + // \brief Drop the last \p N elements of the array. + ArrayRef drop_back(unsigned N = 1) const { + assert(size() >= N && "Dropping more elements than exist"); + return slice(0, size() - N); + } + /// @} /// @name Operator Overloads /// @{ diff --git a/unittests/ADT/ArrayRefTest.cpp b/unittests/ADT/ArrayRefTest.cpp index 7133ca79c46..293afc6ea37 100644 --- a/unittests/ADT/ArrayRefTest.cpp +++ b/unittests/ADT/ArrayRefTest.cpp @@ -29,5 +29,12 @@ TEST(ArrayRefTest, AllocatorCopy) { EXPECT_NE(Array2.data(), Array2c.data()); } +TEST(ArrayRefTest, DropBack) { + static const int TheNumbers[] = {4, 8, 15, 16, 23, 42}; + ArrayRef AR1(TheNumbers); + ArrayRef AR2(TheNumbers, AR1.size() - 1); + EXPECT_TRUE(AR1.drop_back().equals(AR2)); +} + } // end anonymous namespace