Path: blob/main/contrib/llvm-project/libcxx/include/__random/clamp_to_integral.h
35233 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#ifndef _LIBCPP___RANDOM_CLAMP_TO_INTEGRAL_H9#define _LIBCPP___RANDOM_CLAMP_TO_INTEGRAL_H1011#include <__config>12#include <cmath>13#include <limits>1415#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)16# pragma GCC system_header17#endif1819_LIBCPP_PUSH_MACROS20#include <__undef_macros>2122_LIBCPP_BEGIN_NAMESPACE_STD2324template <class _IntT,25class _FloatT,26bool _FloatBigger = (numeric_limits<_FloatT>::digits > numeric_limits<_IntT>::digits),27int _Bits = (numeric_limits<_IntT>::digits - numeric_limits<_FloatT>::digits)>28_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR _IntT __max_representable_int_for_float() _NOEXCEPT {29static_assert(is_floating_point<_FloatT>::value, "must be a floating point type");30static_assert(is_integral<_IntT>::value, "must be an integral type");31static_assert(numeric_limits<_FloatT>::radix == 2, "FloatT has incorrect radix");32static_assert(33(_IsSame<_FloatT, float>::value || _IsSame<_FloatT, double>::value || _IsSame<_FloatT, long double>::value),34"unsupported floating point type");35return _FloatBigger ? numeric_limits<_IntT>::max() : (numeric_limits<_IntT>::max() >> _Bits << _Bits);36}3738// Convert a floating point number to the specified integral type after39// clamping to the integral type's representable range.40//41// The behavior is undefined if `__r` is NaN.42template <class _IntT, class _RealT>43_LIBCPP_HIDE_FROM_ABI _IntT __clamp_to_integral(_RealT __r) _NOEXCEPT {44using _Lim = numeric_limits<_IntT>;45const _IntT __max_val = __max_representable_int_for_float<_IntT, _RealT>();46if (__r >= ::nextafter(static_cast<_RealT>(__max_val), INFINITY)) {47return _Lim::max();48} else if (__r <= _Lim::lowest()) {49return _Lim::min();50}51return static_cast<_IntT>(__r);52}5354_LIBCPP_END_NAMESPACE_STD5556_LIBCPP_POP_MACROS5758#endif // _LIBCPP___RANDOM_CLAMP_TO_INTEGRAL_H596061