clamp_to_integral.h 2.2 KB

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