Skip to content

Commit c92de29

Browse files
committed
[NFC] Add size inference to to_vector
A default calculated size for SmallVector was added in https://reviews.llvm.org/D92522 after discussion in https://groups.google.com/g/llvm-dev/c/Z-VwNCTRGSg, but to_vector still requires an explicit size. This patch adds the default size to to_vector as well, so that this case doesn't unnecessarily force users to pick an arbitrary size. Reviewed By: silvas, dblaikie Differential Revision: https://reviews.llvm.org/D112968
1 parent 26ec5da commit c92de29

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

llvm/include/llvm/ADT/SmallVector.h

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1239,13 +1239,22 @@ inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
12391239
return X.capacity_in_bytes();
12401240
}
12411241

1242+
template <typename RangeType>
1243+
using ValueTypeFromRangeType =
1244+
typename std::remove_const<typename std::remove_reference<
1245+
decltype(*std::begin(std::declval<RangeType &>()))>::type>::type;
1246+
12421247
/// Given a range of type R, iterate the entire range and return a
12431248
/// SmallVector with elements of the vector. This is useful, for example,
12441249
/// when you want to iterate a range and then sort the results.
12451250
template <unsigned Size, typename R>
1246-
SmallVector<typename std::remove_const<typename std::remove_reference<
1247-
decltype(*std::begin(std::declval<R &>()))>::type>::type,
1248-
Size>
1251+
SmallVector<ValueTypeFromRangeType<R>, Size> to_vector(R &&Range) {
1252+
return {std::begin(Range), std::end(Range)};
1253+
}
1254+
template <typename R>
1255+
SmallVector<ValueTypeFromRangeType<R>,
1256+
CalculateSmallVectorDefaultInlinedElements<
1257+
ValueTypeFromRangeType<R>>::value>
12491258
to_vector(R &&Range) {
12501259
return {std::begin(Range), std::end(Range)};
12511260
}

llvm/unittests/ADT/STLExtrasTest.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,13 @@ TEST(STLExtrasTest, ToVector) {
307307
EXPECT_EQ(I, Enumerated[I].index());
308308
EXPECT_EQ(v[I], Enumerated[I].value());
309309
}
310+
311+
auto EnumeratedImplicitSize = to_vector(enumerate(v));
312+
ASSERT_EQ(3u, EnumeratedImplicitSize.size());
313+
for (size_t I = 0; I < v.size(); ++I) {
314+
EXPECT_EQ(I, EnumeratedImplicitSize[I].index());
315+
EXPECT_EQ(v[I], EnumeratedImplicitSize[I].value());
316+
}
310317
}
311318

312319
TEST(STLExtrasTest, ConcatRange) {

0 commit comments

Comments
 (0)