[libc++] Implement ranges::contains (#65148)

Differential Revision: https://reviews.llvm.org/D159232
```
Running ./ranges_contains.libcxx.out
Run on (10 X 24.121 MHz CPU s)
CPU Caches:
  L1 Data 64 KiB (x10)
  L1 Instruction 128 KiB (x10)
  L2 Unified 4096 KiB (x5)
Load Average: 3.37, 6.77, 5.27
--------------------------------------------------------------------
Benchmark                          Time             CPU   Iterations
--------------------------------------------------------------------
bm_contains_char/16             1.88 ns         1.87 ns    371607095
bm_contains_char/256            7.48 ns         7.47 ns     93292285
bm_contains_char/4096           99.7 ns         99.6 ns      7013185
bm_contains_char/65536          1296 ns         1294 ns       540436
bm_contains_char/1048576       23887 ns        23860 ns        29302
bm_contains_char/16777216     389420 ns       389095 ns         1796
bm_contains_int/16              7.14 ns         7.14 ns     97776288
bm_contains_int/256             90.4 ns         90.3 ns      7558089
bm_contains_int/4096            1294 ns         1290 ns       543052
bm_contains_int/65536          20482 ns        20443 ns        34334
bm_contains_int/1048576       328817 ns       327965 ns         2147
bm_contains_int/16777216     5246279 ns      5239361 ns          133
bm_contains_bool/16             2.19 ns         2.19 ns    322565780
bm_contains_bool/256            3.42 ns         3.41 ns    205025467
bm_contains_bool/4096           22.1 ns         22.1 ns     31780479
bm_contains_bool/65536           333 ns          332 ns      2106606
bm_contains_bool/1048576        5126 ns         5119 ns       135901
bm_contains_bool/16777216      81656 ns        81574 ns         8569
```

---------

Co-authored-by: Nathan Gauër <brioche@google.com>
This commit is contained in:
ZijunZhaoCCK 2023-12-19 16:34:19 -08:00 committed by GitHub
parent 22764918b5
commit fdd089b500
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 450 additions and 2 deletions

View File

@ -185,6 +185,7 @@ set(BENCHMARK_TESTS
algorithms/pop_heap.bench.cpp
algorithms/pstl.stable_sort.bench.cpp
algorithms/push_heap.bench.cpp
algorithms/ranges_contains.bench.cpp
algorithms/ranges_ends_with.bench.cpp
algorithms/ranges_make_heap.bench.cpp
algorithms/ranges_make_heap_then_sort_heap.bench.cpp

View File

@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include <algorithm>
#include <benchmark/benchmark.h>
#include <iterator>
#include <vector>
#include "test_iterators.h"
static void bm_contains_char(benchmark::State& state) {
std::vector<char> a(state.range(), 'a');
for (auto _ : state) {
benchmark::DoNotOptimize(a);
benchmark::DoNotOptimize(std::ranges::contains(a.begin(), a.end(), 'B'));
}
}
BENCHMARK(bm_contains_char)->RangeMultiplier(16)->Range(16, 16 << 20);
static void bm_contains_int(benchmark::State& state) {
std::vector<int> a(state.range(), 1);
for (auto _ : state) {
benchmark::DoNotOptimize(a);
benchmark::DoNotOptimize(std::ranges::contains(a.begin(), a.end(), 2));
}
}
BENCHMARK(bm_contains_int)->RangeMultiplier(16)->Range(16, 16 << 20);
static void bm_contains_bool(benchmark::State& state) {
std::vector<bool> a(state.range(), true);
for (auto _ : state) {
benchmark::DoNotOptimize(a);
benchmark::DoNotOptimize(std::ranges::contains(a.begin(), a.end(), false));
}
}
BENCHMARK(bm_contains_bool)->RangeMultiplier(16)->Range(16, 16 << 20);
BENCHMARK_MAIN();

View File

@ -108,6 +108,7 @@ set(files
__algorithm/ranges_any_of.h
__algorithm/ranges_binary_search.h
__algorithm/ranges_clamp.h
__algorithm/ranges_contains.h
__algorithm/ranges_copy.h
__algorithm/ranges_copy_backward.h
__algorithm/ranges_copy_if.h

View File

@ -0,0 +1,61 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
#define _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
#include <__algorithm/ranges_find.h>
#include <__config>
#include <__functional/identity.h>
#include <__functional/ranges_operations.h>
#include <__functional/reference_wrapper.h>
#include <__iterator/concepts.h>
#include <__iterator/indirectly_comparable.h>
#include <__iterator/projected.h>
#include <__ranges/access.h>
#include <__ranges/concepts.h>
#include <__utility/move.h>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
# pragma GCC system_header
#endif
#if _LIBCPP_STD_VER >= 23
_LIBCPP_BEGIN_NAMESPACE_STD
namespace ranges {
namespace __contains {
struct __fn {
template <input_iterator _Iter, sentinel_for<_Iter> _Sent, class _Type, class _Proj = identity>
requires indirect_binary_predicate<ranges::equal_to, projected<_Iter, _Proj>, const _Type*>
_LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr bool static
operator()(_Iter __first, _Sent __last, const _Type& __value, _Proj __proj = {}) {
return ranges::find(std::move(__first), __last, __value, std::ref(__proj)) != __last;
}
template <input_range _Range, class _Type, class _Proj = identity>
requires indirect_binary_predicate<ranges::equal_to, projected<iterator_t<_Range>, _Proj>, const _Type*>
_LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr bool static
operator()(_Range&& __range, const _Type& __value, _Proj __proj = {}) {
return ranges::find(ranges::begin(__range), ranges::end(__range), __value, std::ref(__proj)) !=
ranges::end(__range);
}
};
} // namespace __contains
inline namespace __cpo {
inline constexpr auto contains = __contains::__fn{};
} // namespace __cpo
} // namespace ranges
_LIBCPP_END_NAMESPACE_STD
#endif // _LIBCPP_STD_VER >= 23
#endif // _LIBCPP___ALGORITHM_RANGES_CONTAINS_H

View File

@ -11,6 +11,7 @@
#define _LIBCPP___FUNCTIONAL_IDENTITY_H
#include <__config>
#include <__functional/reference_wrapper.h>
#include <__type_traits/integral_constant.h>
#include <__utility/forward.h>
@ -34,6 +35,10 @@ struct __identity {
template <>
struct __is_identity<__identity> : true_type {};
template <>
struct __is_identity<reference_wrapper<__identity> > : true_type {};
template <>
struct __is_identity<reference_wrapper<const __identity> > : true_type {};
#if _LIBCPP_STD_VER >= 20
@ -48,6 +53,10 @@ struct identity {
template <>
struct __is_identity<identity> : true_type {};
template <>
struct __is_identity<reference_wrapper<identity> > : true_type {};
template <>
struct __is_identity<reference_wrapper<const identity> > : true_type {};
#endif // _LIBCPP_STD_VER >= 20

View File

@ -226,6 +226,14 @@ namespace ranges {
template<class I1, class I2>
using copy_backward_result = in_out_result<I1, I2>; // since C++20
template<input_iterator I, sentinel_for<I> S, class T, class Proj = identity>
requires indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T*>
constexpr bool ranges::contains(I first, S last, const T& value, Proj proj = {}); // since C++23
template<input_range R, class T, class Proj = identity>
requires indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T*>
constexpr bool ranges::contains(R&& r, const T& value, Proj proj = {}); // since C++23
template<input_iterator I, sentinel_for<I> S, weakly_incrementable O>
requires indirectly_copyable<I, O>
constexpr ranges::copy_result<I, O> ranges::copy(I first, S last, O result); // since C++20
@ -1845,6 +1853,7 @@ template <class BidirectionalIterator, class Compare>
#include <__algorithm/ranges_any_of.h>
#include <__algorithm/ranges_binary_search.h>
#include <__algorithm/ranges_clamp.h>
#include <__algorithm/ranges_contains.h>
#include <__algorithm/ranges_copy.h>
#include <__algorithm/ranges_copy_backward.h>
#include <__algorithm/ranges_copy_if.h>

View File

@ -787,6 +787,7 @@ module std_private_algorithm_ranges_clamp [system
header "__algorithm/ranges_clamp.h"
export std_private_functional_ranges_operations
}
module std_private_algorithm_ranges_contains [system] { header "__algorithm/ranges_contains.h" }
module std_private_algorithm_ranges_copy [system] {
header "__algorithm/ranges_copy.h"
export std_private_algorithm_in_out_result

View File

@ -41,12 +41,12 @@ export namespace std {
}
// [alg.contains], contains
#if 0
namespace ranges {
using std::ranges::contains;
#if 0
using std::ranges::contains_subrange;
} // namespace ranges
#endif
} // namespace ranges
// [alg.foreach], for each
using std::for_each;

View File

@ -81,6 +81,12 @@ constexpr bool all_the_algorithms()
(void)std::ranges::binary_search(first, last, value, Less(), Proj(&copies)); assert(copies == 0);
(void)std::ranges::binary_search(a, value, Less(), Proj(&copies)); assert(copies == 0);
(void)std::ranges::clamp(T(), T(), T(), Less(), Proj(&copies)); assert(copies == 0);
#if TEST_STD_VER >= 23
(void)std::ranges::contains(first, last, value, Proj(&copies));
assert(copies == 0);
(void)std::ranges::contains(a, value, Proj(&copies));
assert(copies == 0);
#endif
(void)std::ranges::count(first, last, value, Proj(&copies)); assert(copies == 0);
(void)std::ranges::count(a, value, Proj(&copies)); assert(copies == 0);
(void)std::ranges::count_if(first, last, UnaryTrue(), Proj(&copies)); assert(copies == 0);

View File

@ -45,6 +45,9 @@ void test_algorithms() {
#if TEST_STD_VER >= 17
std::clamp(2, 1, 3);
std::clamp(2, 3, 1, std::greater<int>());
#endif
#if TEST_STD_VER >= 23
std::ranges::contains(arr, arr + 1, 1);
#endif
std::count_if(std::begin(arr), std::end(arr), P());
std::count(std::begin(arr), std::end(arr), 1);

View File

@ -60,6 +60,11 @@ void test_algorithms() {
std::clamp(2, 1, 3, std::greater<int>());
#endif
#if TEST_STD_VER >= 23
// expected-warning@+1 {{ignoring return value of function declared with 'nodiscard' attribute}}
std::ranges::contains(arr, arr + 1, 1);
#endif
// expected-warning@+1 {{ignoring return value of function declared with 'nodiscard' attribute}}
std::count_if(std::begin(arr), std::end(arr), P());

View File

@ -0,0 +1,298 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <algorithm>
// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
// template<input_iterator I, sentinel_for<I> S, class T, class Proj = identity>
// requires indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T*>
// constexpr bool ranges::contains(I first, S last, const T& value, Proj proj = {}); // since C++23
// template<input_range R, class T, class Proj = identity>
// requires indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T*>
// constexpr bool ranges::contains(R&& r, const T& value, Proj proj = {}); // since C++23
#include <algorithm>
#include <cassert>
#include <list>
#include <ranges>
#include <string>
#include <vector>
#include "almost_satisfies_types.h"
#include "boolean_testable.h"
#include "test_iterators.h"
struct NotEqualityComparable {};
template <class Iter, class Sent = Iter>
concept HasContainsIt = requires(Iter iter, Sent sent) { std::ranges::contains(iter, sent, *iter); };
static_assert(HasContainsIt<int*>);
static_assert(HasContainsIt<int*, int*>);
static_assert(!HasContainsIt<NotEqualityComparable*>);
static_assert(!HasContainsIt<InputIteratorNotDerivedFrom>);
static_assert(!HasContainsIt<InputIteratorNotIndirectlyReadable>);
static_assert(!HasContainsIt<InputIteratorNotInputOrOutputIterator>);
static_assert(!HasContainsIt<cpp20_input_iterator<int*>, SentinelForNotSemiregular>);
static_assert(!HasContainsIt<cpp20_input_iterator<int*>, InputRangeNotSentinelEqualityComparableWith>);
static_assert(!HasContainsIt<cpp20_input_iterator<int*>, sentinel_wrapper<cpp20_input_iterator<int*>>>);
static_assert(!HasContainsIt<int*, int>);
static_assert(!HasContainsIt<int, int*>);
template <class Range, class ValT>
concept HasContainsR = requires(Range&& range) { std::ranges::contains(std::forward<Range>(range), ValT{}); };
static_assert(!HasContainsR<int, int>);
static_assert(HasContainsR<int[1], int>);
static_assert(!HasContainsR<NotEqualityComparable[1], NotEqualityComparable>);
static_assert(!HasContainsR<InputRangeNotDerivedFrom, int>);
static_assert(!HasContainsR<InputRangeNotIndirectlyReadable, int>);
static_assert(!HasContainsR<InputRangeNotInputOrOutputIterator, int>);
static_assert(!HasContainsR<InputRangeNotSentinelSemiregular, int>);
static_assert(!HasContainsR<InputRangeNotSentinelEqualityComparableWith, int>);
template <class Iter, class Sent = Iter>
constexpr void test_iterators() {
using ValueT = std::iter_value_t<Iter>;
{ // simple tests
ValueT a[] = {1, 2, 3, 4, 5, 6};
auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 6)));
{
std::same_as<bool> decltype(auto) ret = std::ranges::contains(whole.begin(), whole.end(), 3);
assert(ret);
}
{
std::same_as<bool> decltype(auto) ret = std::ranges::contains(whole, 3);
assert(ret);
}
}
{ // check that a range with a single element works
ValueT a[] = {32};
auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 1)));
{
bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
assert(ret);
}
{
bool ret = std::ranges::contains(whole, 32);
assert(ret);
}
}
{ // check that an empty range works
ValueT a[] = {};
auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a)));
{
bool ret = std::ranges::contains(whole.begin(), whole.end(), 1);
assert(!ret);
}
{
bool ret = std::ranges::contains(whole, 1);
assert(!ret);
}
}
{ // check that the first element matches
ValueT a[] = {32, 3, 2, 1, 0, 23, 21, 9, 40, 100};
auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 10)));
{
bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
assert(ret);
}
{
bool ret = std::ranges::contains(whole, 32);
assert(ret);
}
}
{ // check that the last element matches
ValueT a[] = {3, 22, 1, 43, 99, 0, 56, 100, 32};
auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 9)));
{
bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
assert(ret);
}
{
bool ret = std::ranges::contains(whole, 32);
assert(ret);
}
}
{ // no match
ValueT a[] = {13, 1, 21, 4, 5};
auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 5)));
{
bool ret = std::ranges::contains(whole.begin(), whole.end(), 10);
assert(!ret);
}
{
bool ret = std::ranges::contains(whole, 10);
assert(!ret);
}
}
{ // check that the projections are used
int a[] = {1, 9, 0, 13, 25};
{
bool ret = std::ranges::contains(a, a + 5, -13, [&](int i) { return i * -1; });
assert(ret);
}
{
auto range = std::ranges::subrange(a, a + 5);
bool ret = std::ranges::contains(range, -13, [&](int i) { return i * -1; });
assert(ret);
}
}
}
constexpr bool test() {
types::for_each(types::type_list<char, long long>{}, []<class T> {
types::for_each(types::cpp20_input_iterator_list<T*>{}, []<class Iter> {
if constexpr (std::forward_iterator<Iter>)
test_iterators<Iter>();
test_iterators<Iter, sentinel_wrapper<Iter>>();
test_iterators<Iter, sized_sentinel<Iter>>();
});
});
{ // count invocations of the projection for continuous iterators
int a[] = {1, 9, 0, 13, 25};
int projection_count = 0;
{
bool ret = std::ranges::contains(a, a + 5, 0, [&](int i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 3);
projection_count = 0;
}
{
bool ret = std::ranges::contains(a, 0, [&](int i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 3);
}
}
{ // check invocations of the projection for std::string
const std::string str{"hello world"};
const std::string str1{"hi world"};
int projection_count = 0;
{
std::string a[] = {str1, str1, str, str1, str1};
auto whole =
std::ranges::subrange(forward_iterator(std::move_iterator(a)), forward_iterator(std::move_iterator(a + 5)));
bool ret = std::ranges::contains(whole.begin(), whole.end(), "hello world", [&](const std::string i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 3);
projection_count = 0;
}
{
std::string a[] = {str1, str1, str, str1, str1};
auto whole =
std::ranges::subrange(forward_iterator(std::move_iterator(a)), forward_iterator(std::move_iterator(a + 5)));
bool ret = std::ranges::contains(whole, "hello world", [&](const std::string i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 3);
}
}
{ // check invocations of the projection for non-continuous iterators
std::vector<bool> whole{false, false, true, false};
int projection_count = 0;
{
bool ret = std::ranges::contains(whole.begin(), whole.end(), true, [&](int i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 3);
projection_count = 0;
}
{
bool ret = std::ranges::contains(whole, true, [&](int i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 3);
}
}
{ // check invocations of the projection for views::transform
int a[] = {1, 2, 3, 4, 5};
int projection_count = 0;
auto square_number = a | std::views::transform([](int x) { return x * x; });
{
bool ret = std::ranges::contains(square_number.begin(), square_number.end(), 16, [&](int i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 4);
projection_count = 0;
}
{
bool ret = std::ranges::contains(square_number, 16, [&](int i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 4);
}
}
return true;
}
// test for non-contiguous containers
bool test_nonconstexpr() {
std::list<int> a = {7, 5, 0, 16, 8};
int projection_count = 0;
{
bool ret = std::ranges::contains(a.begin(), a.end(), 0, [&](int i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 3);
projection_count = 0;
}
{
bool ret = std::ranges::contains(a, 0, [&](int i) {
++projection_count;
return i;
});
assert(ret);
assert(projection_count == 3);
}
return true;
}
int main(int, char**) {
test();
static_assert(test());
assert(test_nonconstexpr());
return 0;
}

View File

@ -75,6 +75,7 @@ constexpr bool test_all() {
test(std::ranges::any_of, in, &Foo::unary_pred, &Bar::val);
test(std::ranges::all_of, in, &Foo::unary_pred, &Bar::val);
#if TEST_STD_VER >= 23
test(std::ranges::contains, in, x, &Bar::val);
test(std::ranges::ends_with, in, in2, &Foo::binary_pred, &Bar::val, &Bar::val);
#endif
test(std::ranges::none_of, in, &Foo::unary_pred, &Bar::val);

View File

@ -75,6 +75,7 @@ constexpr void run_tests() {
test(std::ranges::any_of, in, unary_pred);
test(std::ranges::all_of, in, unary_pred);
#if TEST_STD_VER >= 23
test(std::ranges::contains, in, x);
test(std::ranges::ends_with, in, in2);
#endif
test(std::ranges::none_of, in, unary_pred);

View File

@ -65,6 +65,9 @@ static_assert(test(std::ranges::all_of, a, odd));
static_assert(test(std::ranges::any_of, a, odd));
static_assert(test(std::ranges::binary_search, a, 42));
static_assert(test(std::ranges::clamp, 42, 42, 42));
#if TEST_STD_VER >= 23
static_assert(test(std::ranges::contains, a, 42));
#endif
static_assert(test(std::ranges::copy, a, a));
static_assert(test(std::ranges::copy_backward, a, a));
static_assert(test(std::ranges::copy_if, a, a, odd));