Add makeArrayRef() overload for ArrayRef input (no-op/identity) NFC
authorMehdi Amini <mehdi.amini@apple.com>
Thu, 10 Sep 2015 00:05:04 +0000 (00:05 +0000)
committerMehdi Amini <mehdi.amini@apple.com>
Thu, 10 Sep 2015 00:05:04 +0000 (00:05 +0000)
The purpose is to allow templated wrapper to work with either
ArrayRef or any convertible operation:

template<typename Container>
void wrapper(const Container &Arr) {
  impl(makeArrayRef(Arr));
}

with Container being a std::vector, a SmallVector, or an ArrayRef.

From: Mehdi Amini <mehdi.amini@apple.com>

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@247214 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/ADT/ArrayRef.h
unittests/ADT/ArrayRefTest.cpp

index c28fdffae73dafeab2a890213e95664a6ad9c683..aaf32ff020ef12731abe6af17e76a909673392e7 100644 (file)
@@ -337,6 +337,16 @@ namespace llvm {
     return Vec;
   }
 
+  /// Construct an ArrayRef from an ArrayRef (no-op) (const)
+  template <typename T> ArrayRef<T> makeArrayRef(const ArrayRef<T> &Vec) {
+    return Vec;
+  }
+
+  /// Construct an ArrayRef from an ArrayRef (no-op)
+  template <typename T> ArrayRef<T> &makeArrayRef(ArrayRef<T> &Vec) {
+    return Vec;
+  }
+
   /// Construct an ArrayRef from a C array.
   template<typename T, size_t N>
   ArrayRef<T> makeArrayRef(const T (&Arr)[N]) {
index 3ab13a34829282e649db966ae9f2b59aaaa44237..6cbadd6bc228fa33df0cd1b2092162f9a1e99cb4 100644 (file)
@@ -124,4 +124,20 @@ TEST(ArrayRefTest, InitializerList) {
   ArgTest12({1, 2});
 }
 
+// Test that makeArrayRef works on ArrayRef (no-op)
+TEST(ArrayRefTest, makeArrayRef) {
+  static const int A1[] = {1, 2, 3, 4, 5, 6, 7, 8};
+
+  // No copy expected for non-const ArrayRef (true no-op)
+  ArrayRef<int> AR1(A1);
+  ArrayRef<int> &AR1Ref = makeArrayRef(AR1);
+  EXPECT_EQ(&AR1, &AR1Ref);
+
+  // A copy is expected for non-const ArrayRef (thin copy)
+  const ArrayRef<int> AR2(A1);
+  const ArrayRef<int> &AR2Ref = makeArrayRef(AR2);
+  EXPECT_NE(&AR2Ref, &AR2);
+  EXPECT_TRUE(AR2.equals(AR2Ref));
+}
+
 } // end anonymous namespace