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