From c92de29f8d39729678dfe2c915035e453dd83142 Mon Sep 17 00:00:00 2001 From: Geoffrey Martin-Noble Date: Mon, 1 Nov 2021 16:41:44 -0700 Subject: [PATCH] [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 --- llvm/include/llvm/ADT/SmallVector.h | 15 ++++++++++++--- llvm/unittests/ADT/STLExtrasTest.cpp | 7 +++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/llvm/include/llvm/ADT/SmallVector.h b/llvm/include/llvm/ADT/SmallVector.h index b8a1103..0d13524 100644 --- a/llvm/include/llvm/ADT/SmallVector.h +++ b/llvm/include/llvm/ADT/SmallVector.h @@ -1239,13 +1239,22 @@ inline size_t capacity_in_bytes(const SmallVector &X) { return X.capacity_in_bytes(); } +template +using ValueTypeFromRangeType = + typename std::remove_const()))>::type>::type; + /// Given a range of type R, iterate the entire range and return a /// SmallVector with elements of the vector. This is useful, for example, /// when you want to iterate a range and then sort the results. template -SmallVector()))>::type>::type, - Size> +SmallVector, Size> to_vector(R &&Range) { + return {std::begin(Range), std::end(Range)}; +} +template +SmallVector, + CalculateSmallVectorDefaultInlinedElements< + ValueTypeFromRangeType>::value> to_vector(R &&Range) { return {std::begin(Range), std::end(Range)}; } diff --git a/llvm/unittests/ADT/STLExtrasTest.cpp b/llvm/unittests/ADT/STLExtrasTest.cpp index de2c896..c286cd5 100644 --- a/llvm/unittests/ADT/STLExtrasTest.cpp +++ b/llvm/unittests/ADT/STLExtrasTest.cpp @@ -307,6 +307,13 @@ TEST(STLExtrasTest, ToVector) { EXPECT_EQ(I, Enumerated[I].index()); EXPECT_EQ(v[I], Enumerated[I].value()); } + + auto EnumeratedImplicitSize = to_vector(enumerate(v)); + ASSERT_EQ(3u, EnumeratedImplicitSize.size()); + for (size_t I = 0; I < v.size(); ++I) { + EXPECT_EQ(I, EnumeratedImplicitSize[I].index()); + EXPECT_EQ(v[I], EnumeratedImplicitSize[I].value()); + } } TEST(STLExtrasTest, ConcatRange) { -- 2.7.4