ranges_clamp.h 2.1 KB

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