diff --git a/llvm/include/llvm/ADT/SmallVectorExtras.h b/llvm/include/llvm/ADT/SmallVectorExtras.h index eea91ca81ca61..061293fae0830 100644 --- a/llvm/include/llvm/ADT/SmallVectorExtras.h +++ b/llvm/include/llvm/ADT/SmallVectorExtras.h @@ -19,12 +19,28 @@ namespace llvm { +/// Filter a range to a SmallVector with the element types deduced. +template +auto filter_to_vector(ContainerTy &&C, PredicateFn &&Pred) { + return to_vector(make_filter_range(std::forward(C), + std::forward(Pred))); +} + +/// Filter a range to a SmallVector with the element types deduced. +template +auto filter_to_vector(ContainerTy &&C, PredicateFn &&Pred) { + return to_vector(make_filter_range(std::forward(C), + std::forward(Pred))); +} + /// Map a range to a SmallVector with element types deduced from the mapping. template auto map_to_vector(ContainerTy &&C, FuncTy &&F) { return to_vector( map_range(std::forward(C), std::forward(F))); } + +/// Map a range to a SmallVector with element types deduced from the mapping. template auto map_to_vector(ContainerTy &&C, FuncTy &&F) { return to_vector( diff --git a/llvm/unittests/ADT/CMakeLists.txt b/llvm/unittests/ADT/CMakeLists.txt index b0077d5b54a3e..c9bc58f45f08c 100644 --- a/llvm/unittests/ADT/CMakeLists.txt +++ b/llvm/unittests/ADT/CMakeLists.txt @@ -75,6 +75,7 @@ add_llvm_unittest(ADTTests SmallPtrSetTest.cpp SmallSetTest.cpp SmallStringTest.cpp + SmallVectorExtrasTest.cpp SmallVectorTest.cpp SparseBitVectorTest.cpp SparseMultiSetTest.cpp diff --git a/llvm/unittests/ADT/SmallVectorExtrasTest.cpp b/llvm/unittests/ADT/SmallVectorExtrasTest.cpp new file mode 100644 index 0000000000000..467eb13ac390b --- /dev/null +++ b/llvm/unittests/ADT/SmallVectorExtrasTest.cpp @@ -0,0 +1,37 @@ +//===- llvm/unittest/ADT/SmallVectorExtrasTest.cpp ------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// SmallVectorExtras unit tests. +// +//===----------------------------------------------------------------------===// + +#include "llvm/ADT/SmallVectorExtras.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include +#include + +using testing::ElementsAre; + +namespace llvm { +namespace { + +TEST(SmallVectorExtrasTest, FilterToVector) { + std::vector Numbers = {0, 1, 2, 3, 4}; + auto Odd = filter_to_vector<2>(Numbers, [](int X) { return (X % 2) != 0; }); + static_assert(std::is_same_v>); + EXPECT_THAT(Odd, ElementsAre(1, 3)); + + auto Even = filter_to_vector(Numbers, [](int X) { return (X % 2) == 0; }); + static_assert(std::is_same_v>); + EXPECT_THAT(Even, ElementsAre(0, 2, 4)); +} + +} // end namespace +} // namespace llvm