ranges_clamp.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. #if _LIBCPP_STD_VER >= 20
  22. _LIBCPP_BEGIN_NAMESPACE_STD
  23. namespace ranges {
  24. namespace __clamp {
  25. struct __fn {
  26. template <class _Type,
  27. class _Proj = identity,
  28. indirect_strict_weak_order<projected<const _Type*, _Proj>> _Comp = ranges::less>
  29. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr const _Type& operator()(
  30. const _Type& __value, const _Type& __low, const _Type& __high, _Comp __comp = {}, _Proj __proj = {}) const {
  31. _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, __high), std::invoke(__proj, __low))),
  32. "Bad bounds passed to std::ranges::clamp");
  33. if (std::invoke(__comp, std::invoke(__proj, __value), std::invoke(__proj, __low)))
  34. return __low;
  35. else if (std::invoke(__comp, std::invoke(__proj, __high), std::invoke(__proj, __value)))
  36. return __high;
  37. else
  38. return __value;
  39. }
  40. };
  41. } // namespace __clamp
  42. inline namespace __cpo {
  43. inline constexpr auto clamp = __clamp::__fn{};
  44. } // namespace __cpo
  45. } // namespace ranges
  46. _LIBCPP_END_NAMESPACE_STD
  47. #endif // _LIBCPP_STD_VER >= 20
  48. #endif // _LIBCPP___ALGORITHM_RANGES_CLAMP_H