diff --git a/llvm/include/llvm/ADT/MapVector.h b/llvm/include/llvm/ADT/MapVector.h index c11617a81c97d..adbcda116dd56 100644 --- a/llvm/include/llvm/ADT/MapVector.h +++ b/llvm/include/llvm/ADT/MapVector.h @@ -57,6 +57,9 @@ class MapVector { return std::move(Vector); } + /// Returns an array reference of the underlying vector. + ArrayRef getArrayRef() const { return Vector; } + size_type size() const { return Vector.size(); } /// Grow the MapVector so that it can contain at least \p NumEntries items diff --git a/llvm/unittests/ADT/MapVectorTest.cpp b/llvm/unittests/ADT/MapVectorTest.cpp index e0f11b60a0223..639e1a14e8178 100644 --- a/llvm/unittests/ADT/MapVectorTest.cpp +++ b/llvm/unittests/ADT/MapVectorTest.cpp @@ -7,7 +7,9 @@ //===----------------------------------------------------------------------===// #include "llvm/ADT/MapVector.h" +#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/iterator_range.h" +#include "gmock/gmock.h" #include "gtest/gtest.h" #include #include @@ -267,6 +269,29 @@ TEST(MapVectorTest, NonCopyable) { ASSERT_EQ(*MV.find(2)->second, 2); } +TEST(MapVectorTest, GetArrayRef) { + MapVector MV; + + // The underlying vector is empty to begin with. + EXPECT_TRUE(MV.getArrayRef().empty()); + + // Test inserted element. + MV.insert(std::make_pair(100, 99)); + EXPECT_TRUE(MV.getArrayRef().equals({std::pair(100, 99)})); + + // Inserting a different element for an existing key won't change the + // underlying vector. + auto [Iter, Inserted] = MV.try_emplace(100, 98); + EXPECT_FALSE(Inserted); + EXPECT_EQ(Iter->second, 99); + EXPECT_TRUE(MV.getArrayRef().equals({std::pair(100, 99)})); + + // Inserting a new element. Tests that elements are in order in the underlying + // array. + MV.insert(std::make_pair(99, 98)); + EXPECT_TRUE(MV.getArrayRef().equals({std::pair(100, 99), std::pair(99, 98)})); +} + template struct MapVectorMappedTypeTest : ::testing::Test { using int_type = IntType; };