clamp.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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_CLAMP_H
  9. #define _LIBCPP___ALGORITHM_CLAMP_H
  10. #include <__algorithm/comp.h>
  11. #include <__assert>
  12. #include <__config>
  13. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  14. # pragma GCC system_header
  15. #endif
  16. _LIBCPP_BEGIN_NAMESPACE_STD
  17. #if _LIBCPP_STD_VER >= 17
  18. template <class _Tp, class _Compare>
  19. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI constexpr const _Tp&
  20. clamp(_LIBCPP_LIFETIMEBOUND const _Tp& __v,
  21. _LIBCPP_LIFETIMEBOUND const _Tp& __lo,
  22. _LIBCPP_LIFETIMEBOUND const _Tp& __hi,
  23. _Compare __comp) {
  24. _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(!__comp(__hi, __lo), "Bad bounds passed to std::clamp");
  25. return __comp(__v, __lo) ? __lo : __comp(__hi, __v) ? __hi : __v;
  26. }
  27. template <class _Tp>
  28. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI constexpr const _Tp&
  29. clamp(_LIBCPP_LIFETIMEBOUND const _Tp& __v,
  30. _LIBCPP_LIFETIMEBOUND const _Tp& __lo,
  31. _LIBCPP_LIFETIMEBOUND const _Tp& __hi) {
  32. return std::clamp(__v, __lo, __hi, __less<>());
  33. }
  34. #endif
  35. _LIBCPP_END_NAMESPACE_STD
  36. #endif // _LIBCPP___ALGORITHM_CLAMP_H