[NFC] Introduce llvm::to_vector_of to allow creation of SmallVector<T> from range of items convertible to type T

It's https://reviews.llvm.org/D129565 follow-up.

Differential Revision: https://reviews.llvm.org/D129781
This commit is contained in:
Dawid Jurczak 2022-08-12 15:19:31 +02:00
parent 82d6e77048
commit 8a17e74ca9
2 changed files with 49 additions and 6 deletions

View File

@ -1287,6 +1287,15 @@ SmallVector<ValueTypeFromRangeType<R>> to_vector(R &&Range) {
return {std::begin(Range), std::end(Range)};
}
template <typename Out, unsigned Size, typename R>
SmallVector<Out, Size> to_vector_of(R &&Range) {
return {std::begin(Range), std::end(Range)};
}
template <typename Out, typename R> SmallVector<Out> to_vector_of(R &&Range) {
return {std::begin(Range), std::end(Range)};
}
} // end namespace llvm
namespace std {

View File

@ -203,7 +203,7 @@ template <typename VectorT> void makeSequence(VectorT &v, int start, int end) {
}
template <typename T, unsigned N>
static unsigned NumBuiltinElts(const SmallVector<T, N> &) {
constexpr static unsigned NumBuiltinElts(const SmallVector<T, N> &) {
return N;
}
@ -1142,6 +1142,25 @@ TEST(SmallVectorTest, InitializerList) {
EXPECT_TRUE(makeArrayRef(V2).equals({4, 5, 3, 2}));
}
TEST(SmallVectorTest, ToVector) {
{
std::vector<char> v = {'a', 'b', 'c'};
auto Vector = to_vector<4>(v);
static_assert(NumBuiltinElts(Vector) == 4u);
ASSERT_EQ(3u, Vector.size());
for (size_t I = 0; I < v.size(); ++I)
EXPECT_EQ(v[I], Vector[I]);
}
{
std::vector<char> v = {'a', 'b', 'c'};
auto Vector = to_vector(v);
static_assert(NumBuiltinElts(Vector) != 4u);
ASSERT_EQ(3u, Vector.size());
for (size_t I = 0; I < v.size(); ++I)
EXPECT_EQ(v[I], Vector[I]);
}
}
struct To {
int Content;
friend bool operator==(const To &LHS, const To &RHS) {
@ -1180,6 +1199,26 @@ TEST(SmallVectorTest, ConstructFromArrayRefOfConvertibleType) {
}
}
TEST(SmallVectorTest, ToVectorOf) {
To to1{1}, to2{2}, to3{3};
std::vector<From> StdVector = {From(to1), From(to2), From(to3)};
{
llvm::SmallVector<To> Vector = llvm::to_vector_of<To>(StdVector);
ASSERT_EQ(StdVector.size(), Vector.size());
for (size_t I = 0; I < StdVector.size(); ++I)
EXPECT_EQ(StdVector[I], Vector[I]);
}
{
auto Vector = llvm::to_vector_of<To, 4>(StdVector);
ASSERT_EQ(StdVector.size(), Vector.size());
static_assert(NumBuiltinElts(Vector) == 4u);
for (size_t I = 0; I < StdVector.size(); ++I)
EXPECT_EQ(StdVector[I], Vector[I]);
}
}
template <class VectorT>
class SmallVectorReferenceInvalidationTest : public SmallVectorTestBase {
protected:
@ -1476,11 +1515,6 @@ protected:
VectorT V;
template <typename T, unsigned N>
static unsigned NumBuiltinElts(const SmallVector<T, N> &) {
return N;
}
void SetUp() override {
SmallVectorTestBase::SetUp();