Skip to content

[ADT]Add helper function to return a ArrayRef of MapVector's underlying vector #138726

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions llvm/include/llvm/ADT/MapVector.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ class MapVector {
return std::move(Vector);
}

/// Returns an array reference of the underlying vector.
ArrayRef<value_type> getArrayRef() const { return Vector; }

size_type size() const { return Vector.size(); }

/// Grow the MapVector so that it can contain at least \p NumEntries items
Expand Down
25 changes: 25 additions & 0 deletions llvm/unittests/ADT/MapVectorTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 <memory>
#include <utility>
Expand Down Expand Up @@ -267,6 +269,29 @@ TEST(MapVectorTest, NonCopyable) {
ASSERT_EQ(*MV.find(2)->second, 2);
}

TEST(MapVectorTest, GetArrayRef) {
MapVector<int, int> 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 <class IntType> struct MapVectorMappedTypeTest : ::testing::Test {
using int_type = IntType;
};
Expand Down
Loading