1//===-- A self contained equivalent of <algorithm> --------------*- C++ -*-===//
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// This file is minimalist on purpose but can receive a few more function if
9// they prove useful.
10//===----------------------------------------------------------------------===//
11
12#ifndef LLVM_LIBC_SRC___SUPPORT_CPP_ALGORITHM_H
13#define LLVM_LIBC_SRC___SUPPORT_CPP_ALGORITHM_H
14
15#include "src/__support/macros/attributes.h" // LIBC_INLINE
16#include "src/__support/macros/config.h"
17
18namespace LIBC_NAMESPACE_DECL {
19namespace cpp {
20
21template <class T = void> struct plus {};
22template <class T = void> struct multiplies {};
23template <class T = void> struct bit_and {};
24template <class T = void> struct bit_or {};
25template <class T = void> struct bit_xor {};
26
27template <class T> LIBC_INLINE constexpr const T &max(const T &a, const T &b) {
28 return (a < b) ? b : a;
29}
30
31template <class T> LIBC_INLINE constexpr const T &min(const T &a, const T &b) {
32 return (a < b) ? a : b;
33}
34
35template <class T> LIBC_INLINE constexpr T abs(T a) { return a < 0 ? -a : a; }
36
37template <class InputIt, class UnaryPred>
38LIBC_INLINE constexpr InputIt find_if_not(InputIt first, InputIt last,
39 UnaryPred q) {
40 for (; first != last; ++first)
41 if (!q(*first))
42 return first;
43
44 return last;
45}
46
47template <class InputIt, class UnaryPred>
48LIBC_INLINE constexpr bool all_of(InputIt first, InputIt last, UnaryPred p) {
49 return find_if_not(first, last, p) == last;
50}
51
52template <typename It, typename T, typename Comp>
53LIBC_INLINE constexpr It lower_bound(It first, It last, const T &value,
54 Comp comp) {
55 auto count = last - first;
56
57 while (count > 0) {
58 It it = first;
59 auto step = count / 2;
60 it += step;
61
62 if (comp(*it, value)) {
63 first = ++it;
64 count -= step + 1;
65 } else {
66 count = step;
67 }
68 }
69 return first;
70}
71
72} // namespace cpp
73} // namespace LIBC_NAMESPACE_DECL
74
75#endif // LLVM_LIBC_SRC___SUPPORT_CPP_ALGORITHM_H
76