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_IS_HEAP_UNTIL_H
10#define _LIBCPP___ALGORITHM_IS_HEAP_UNTIL_H
11
12#include <__algorithm/comp.h>
13#include <__algorithm/comp_ref_type.h>
14#include <__config>
15
16#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
17# pragma GCC system_header
18#endif
19
20_LIBCPP_BEGIN_NAMESPACE_STD
21
22template <class _Compare, class _Iter>
23_LIBCPP_CONSTEXPR_SINCE_CXX20 _Iter __is_heap_until(_Iter __first, _Iter __last, _Compare&& __comp) {
24 auto __count = __last - __first;
25
26 if (__count < 2)
27 return __last;
28
29 // This points to one past the last parent that has two children.
30 // Integer division handles the case where the last parent has a single child.
31 auto __parent_last = __first + (__count - 1) / 2;
32 auto __child = __first;
33 ++__child;
34 for (; __first != __parent_last; ++__first) {
35 if (__comp(*__first, *__child))
36 return __child;
37 ++__child;
38
39 if (__comp(*__first, *__child))
40 return __child;
41 ++__child;
42 }
43
44 // If the heap is even-sized, the last parent has a single child, handled here.
45 if (__count % 2 == 0) {
46 if (__comp(*__first, *__child))
47 return __child;
48 ++__child;
49 }
50
51 return __child;
52}
53
54template <class _RandomAccessIterator, class _Compare>
55[[__nodiscard__]] inline _LIBCPP_CONSTEXPR_SINCE_CXX20 _RandomAccessIterator
56is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) {
57 return std::__is_heap_until(__first, __last, static_cast<__comp_ref_type<_Compare> >(__comp));
58}
59
60template <class _RandomAccessIterator>
61[[__nodiscard__]] inline _LIBCPP_CONSTEXPR_SINCE_CXX20 _RandomAccessIterator
62is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last) {
63 return std::__is_heap_until(__first, __last, __less<>());
64}
65
66_LIBCPP_END_NAMESPACE_STD
67
68#endif // _LIBCPP___ALGORITHM_IS_HEAP_UNTIL_H
69