From b39f437757967687dd60d9d5a657cc3b421cf83d Mon Sep 17 00:00:00 2001 From: Chris Bieneman Date: Mon, 28 Mar 2022 16:33:16 -0500 Subject: [PATCH] [ADT] add initializer list specialization for is_contained Adding an initializer list specialization for is_contained allows for compile-time evaluation when called with a constant or runtime evaluation for non-constant values. This patch doesn't add any uses of this template, but that is coming in a subsequent patch. Reviewed By: pete Differential Revision: https://reviews.llvm.org/D122079 --- llvm/include/llvm/ADT/STLExtras.h | 9 +++++++++ llvm/unittests/ADT/STLExtrasTest.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/llvm/include/llvm/ADT/STLExtras.h b/llvm/include/llvm/ADT/STLExtras.h index ff2145e6861e..75d717545358 100644 --- a/llvm/include/llvm/ADT/STLExtras.h +++ b/llvm/include/llvm/ADT/STLExtras.h @@ -1657,6 +1657,15 @@ bool is_contained(R &&Range, const E &Element) { return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range); } +template +constexpr bool is_contained(std::initializer_list Set, T Value) { + // TODO: Use std::find when we switch to C++20. + for (T V : Set) + if (V == Value) + return true; + return false; +} + /// Wrapper function around std::is_sorted to check if elements in a range \p R /// are sorted with respect to a comparator \p C. template bool is_sorted(R &&Range, Compare C) { diff --git a/llvm/unittests/ADT/STLExtrasTest.cpp b/llvm/unittests/ADT/STLExtrasTest.cpp index 6d4325e49f36..09ff556f3ea1 100644 --- a/llvm/unittests/ADT/STLExtrasTest.cpp +++ b/llvm/unittests/ADT/STLExtrasTest.cpp @@ -964,4 +964,29 @@ TEST(STLExtrasTest, TypeAtIndex) { (std::is_same>::value)); } +enum Doggos { + Floofer, + Woofer, + SubWoofer, + Pupper, + Pupperino, + Longboi, +}; + +TEST(STLExtrasTest, IsContainedInitializerList) { + EXPECT_TRUE(is_contained({Woofer, SubWoofer}, Woofer)); + EXPECT_TRUE(is_contained({Woofer, SubWoofer}, SubWoofer)); + EXPECT_FALSE(is_contained({Woofer, SubWoofer}, Pupper)); + EXPECT_FALSE(is_contained({}, Longboi)); + + static_assert(is_contained({Woofer, SubWoofer}, SubWoofer), "SubWoofer!"); + static_assert(!is_contained({Woofer, SubWoofer}, Pupper), "Missing Pupper!"); + + EXPECT_TRUE(is_contained({1, 2, 3, 4}, 3)); + EXPECT_FALSE(is_contained({1, 2, 3, 4}, 5)); + + static_assert(is_contained({1, 2, 3, 4}, 3), "It's there!"); + static_assert(!is_contained({1, 2, 3, 4}, 5), "It's not there :("); +} + } // namespace