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_RANGES_CLAMP_H
10 #define _LIBCPP___ALGORITHM_RANGES_CLAMP_H
11 
12 #include <__assert>
13 #include <__config>
14 #include <__functional/identity.h>
15 #include <__functional/invoke.h>
16 #include <__functional/ranges_operations.h>
17 #include <__iterator/concepts.h>
18 #include <__iterator/projected.h>
19 #include <__utility/forward.h>
20 
21 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
22 #  pragma GCC system_header
23 #endif
24 
25 #if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
26 
27 _LIBCPP_BEGIN_NAMESPACE_STD
28 
29 namespace ranges {
30 namespace __clamp {
31 struct __fn {
32 
33   template <class _Type,
34             class _Proj = identity,
35             indirect_strict_weak_order<projected<const _Type*, _Proj>> _Comp = ranges::less>
36   _LIBCPP_HIDE_FROM_ABI constexpr
37   const _Type& operator()(const _Type& __value,
38                           const _Type& __low,
39                           const _Type& __high,
40                           _Comp __comp = {},
41                           _Proj __proj = {}) const {
42     _LIBCPP_ASSERT(!bool(std::invoke(__comp, std::invoke(__proj, __high), std::invoke(__proj, __low))),
43                    "Bad bounds passed to std::ranges::clamp");
44 
45     if (std::invoke(__comp, std::invoke(__proj, __value), std::invoke(__proj, __low)))
46       return __low;
47     else if (std::invoke(__comp, std::invoke(__proj, __high), std::invoke(__proj, __value)))
48       return __high;
49     else
50       return __value;
51   }
52 
53 };
54 } // namespace __clamp
55 
56 inline namespace __cpo {
57   inline constexpr auto clamp = __clamp::__fn{};
58 } // namespace __cpo
59 } // namespace ranges
60 
61 _LIBCPP_END_NAMESPACE_STD
62 
63 #endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
64 
65 #endif // _LIBCPP___ALGORITHM_RANGES_CLAMP_H
66