Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ad5b3e0

Browse files
[ADT]Add helper function to return a ArrayRef of MapVector's underlying vector (#138726)
SetVector currently has a [similar method](https://github.com/llvm/llvm-project/blob/c956ed06dc1c1b340d0c589c472c438b9220b36d/llvm/include/llvm/ADT/SetVector.h#L90), and #138170 has a use case to get an ArrayRef of MapVector's underlying vector.
1 parent 282af2d commit ad5b3e0

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

llvm/include/llvm/ADT/MapVector.h

+3
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ class MapVector {
5757
return std::move(Vector);
5858
}
5959

60+
/// Returns an array reference of the underlying vector.
61+
ArrayRef<value_type> getArrayRef() const { return Vector; }
62+
6063
size_type size() const { return Vector.size(); }
6164

6265
/// Grow the MapVector so that it can contain at least \p NumEntries items

llvm/unittests/ADT/MapVectorTest.cpp

+25
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
//===----------------------------------------------------------------------===//
88

99
#include "llvm/ADT/MapVector.h"
10+
#include "llvm/ADT/ArrayRef.h"
1011
#include "llvm/ADT/iterator_range.h"
12+
#include "gmock/gmock.h"
1113
#include "gtest/gtest.h"
1214
#include <memory>
1315
#include <utility>
@@ -267,6 +269,29 @@ TEST(MapVectorTest, NonCopyable) {
267269
ASSERT_EQ(*MV.find(2)->second, 2);
268270
}
269271

272+
TEST(MapVectorTest, GetArrayRef) {
273+
MapVector<int, int> MV;
274+
275+
// The underlying vector is empty to begin with.
276+
EXPECT_TRUE(MV.getArrayRef().empty());
277+
278+
// Test inserted element.
279+
MV.insert(std::make_pair(100, 99));
280+
EXPECT_TRUE(MV.getArrayRef().equals({std::pair(100, 99)}));
281+
282+
// Inserting a different element for an existing key won't change the
283+
// underlying vector.
284+
auto [Iter, Inserted] = MV.try_emplace(100, 98);
285+
EXPECT_FALSE(Inserted);
286+
EXPECT_EQ(Iter->second, 99);
287+
EXPECT_TRUE(MV.getArrayRef().equals({std::pair(100, 99)}));
288+
289+
// Inserting a new element. Tests that elements are in order in the underlying
290+
// array.
291+
MV.insert(std::make_pair(99, 98));
292+
EXPECT_TRUE(MV.getArrayRef().equals({std::pair(100, 99), std::pair(99, 98)}));
293+
}
294+
270295
template <class IntType> struct MapVectorMappedTypeTest : ::testing::Test {
271296
using int_type = IntType;
272297
};

0 commit comments

Comments
 (0)