clamp_to_integral.h 2.2 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___RANDOM_CLAMP_TO_INTEGRAL_H
  9. #define _LIBCPP___RANDOM_CLAMP_TO_INTEGRAL_H
  10. #include <__config>
  11. #include <cmath>
  12. #include <limits>
  13. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  14. # pragma GCC system_header
  15. #endif
  16. _LIBCPP_PUSH_MACROS
  17. #include <__undef_macros>
  18. _LIBCPP_BEGIN_NAMESPACE_STD
  19. template <class _IntT, class _FloatT,
  20. bool _FloatBigger = (numeric_limits<_FloatT>::digits > numeric_limits<_IntT>::digits),
  21. int _Bits = (numeric_limits<_IntT>::digits - numeric_limits<_FloatT>::digits)>
  22. _LIBCPP_INLINE_VISIBILITY
  23. _LIBCPP_CONSTEXPR _IntT __max_representable_int_for_float() _NOEXCEPT {
  24. static_assert(is_floating_point<_FloatT>::value, "must be a floating point type");
  25. static_assert(is_integral<_IntT>::value, "must be an integral type");
  26. static_assert(numeric_limits<_FloatT>::radix == 2, "FloatT has incorrect radix");
  27. static_assert((_IsSame<_FloatT, float>::value || _IsSame<_FloatT, double>::value
  28. || _IsSame<_FloatT,long double>::value), "unsupported floating point type");
  29. return _FloatBigger ? numeric_limits<_IntT>::max() : (numeric_limits<_IntT>::max() >> _Bits << _Bits);
  30. }
  31. // Convert a floating point number to the specified integral type after
  32. // clamping to the integral type's representable range.
  33. //
  34. // The behavior is undefined if `__r` is NaN.
  35. template <class _IntT, class _RealT>
  36. _LIBCPP_INLINE_VISIBILITY
  37. _IntT __clamp_to_integral(_RealT __r) _NOEXCEPT {
  38. using _Lim = numeric_limits<_IntT>;
  39. const _IntT __max_val = __max_representable_int_for_float<_IntT, _RealT>();
  40. if (__r >= ::nextafter(static_cast<_RealT>(__max_val), INFINITY)) {
  41. return _Lim::max();
  42. } else if (__r <= _Lim::lowest()) {
  43. return _Lim::min();
  44. }
  45. return static_cast<_IntT>(__r);
  46. }
  47. _LIBCPP_END_NAMESPACE_STD
  48. _LIBCPP_POP_MACROS
  49. #endif // _LIBCPP___RANDOM_CLAMP_TO_INTEGRAL_H