| 1 | //===----------------------------------------------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #ifndef _LIBCPP___ALGORITHM_FIND_SEGMENT_IF_H |
| 10 | #define _LIBCPP___ALGORITHM_FIND_SEGMENT_IF_H |
| 11 | |
| 12 | #include <__config> |
| 13 | #include <__iterator/segmented_iterator.h> |
| 14 | |
| 15 | #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) |
| 16 | # pragma GCC system_header |
| 17 | #endif |
| 18 | |
| 19 | _LIBCPP_BEGIN_NAMESPACE_STD |
| 20 | |
| 21 | // __find_segment_if is a utility function for optimizing iteration over segmented iterators linearly. |
| 22 | // [__first, __last) has to be a segmented range. __pred is expected to take a range of local iterators. |
| 23 | // It returns an iterator to the first element that satisfies the predicate, or a one-past-the-end iterator if there was |
| 24 | // no match. |
| 25 | |
| 26 | template <class _SegmentedIterator, class _Pred> |
| 27 | _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _SegmentedIterator |
| 28 | __find_segment_if(_SegmentedIterator __first, _SegmentedIterator __last, _Pred __pred) { |
| 29 | using _Traits = __segmented_iterator_traits<_SegmentedIterator>; |
| 30 | |
| 31 | auto __sfirst = _Traits::__segment(__first); |
| 32 | auto __slast = _Traits::__segment(__last); |
| 33 | |
| 34 | // We are in a single segment, so we might not be at the beginning or end |
| 35 | if (__sfirst == __slast) |
| 36 | return _Traits::__compose(__sfirst, __pred(_Traits::__local(__first), _Traits::__local(__last))); |
| 37 | |
| 38 | { // We have more than one segment. Iterate over the first segment, since we might not start at the beginning |
| 39 | auto __llast = _Traits::__end(__sfirst); |
| 40 | auto __liter = __pred(_Traits::__local(__first), __llast); |
| 41 | if (__liter != __llast) |
| 42 | return _Traits::__compose(__sfirst, __liter); |
| 43 | } |
| 44 | ++__sfirst; |
| 45 | |
| 46 | // Iterate over the segments which are guaranteed to be completely in the range |
| 47 | while (__sfirst != __slast) { |
| 48 | auto __llast = _Traits::__end(__sfirst); |
| 49 | auto __liter = __pred(_Traits::__begin(__sfirst), _Traits::__end(__sfirst)); |
| 50 | if (__liter != __llast) |
| 51 | return _Traits::__compose(__sfirst, __liter); |
| 52 | ++__sfirst; |
| 53 | } |
| 54 | |
| 55 | // Iterate over the last segment |
| 56 | return _Traits::__compose(__sfirst, __pred(_Traits::__begin(__sfirst), _Traits::__local(__last))); |
| 57 | } |
| 58 | |
| 59 | _LIBCPP_END_NAMESPACE_STD |
| 60 | |
| 61 | #endif // _LIBCPP___ALGORITHM_FIND_SEGMENT_IF_H |
| 62 | |