File indexing completed on 2026-05-03 08:13:36
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010 #ifndef _LIBCPP___CXX03___NUMERIC_MIDPOINT_H
0011 #define _LIBCPP___CXX03___NUMERIC_MIDPOINT_H
0012
0013 #include <__cxx03/__config>
0014 #include <__cxx03/__type_traits/enable_if.h>
0015 #include <__cxx03/__type_traits/is_floating_point.h>
0016 #include <__cxx03/__type_traits/is_integral.h>
0017 #include <__cxx03/__type_traits/is_null_pointer.h>
0018 #include <__cxx03/__type_traits/is_object.h>
0019 #include <__cxx03/__type_traits/is_pointer.h>
0020 #include <__cxx03/__type_traits/is_same.h>
0021 #include <__cxx03/__type_traits/is_void.h>
0022 #include <__cxx03/__type_traits/make_unsigned.h>
0023 #include <__cxx03/__type_traits/remove_pointer.h>
0024 #include <__cxx03/cstddef>
0025 #include <__cxx03/limits>
0026
0027 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
0028 # pragma GCC system_header
0029 #endif
0030
0031 _LIBCPP_PUSH_MACROS
0032 #include <__cxx03/__undef_macros>
0033
0034 _LIBCPP_BEGIN_NAMESPACE_STD
0035
0036 #if _LIBCPP_STD_VER >= 20
0037 template <class _Tp>
0038 _LIBCPP_HIDE_FROM_ABI constexpr enable_if_t<is_integral_v<_Tp> && !is_same_v<bool, _Tp> && !is_null_pointer_v<_Tp>, _Tp>
0039 midpoint(_Tp __a, _Tp __b) noexcept _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK {
0040 using _Up = make_unsigned_t<_Tp>;
0041 constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;
0042
0043 _Up __diff = _Up(__b) - _Up(__a);
0044 _Up __sign_bit = __b < __a;
0045
0046 _Up __half_diff = (__diff / 2) + (__sign_bit << __bitshift) + (__sign_bit & __diff);
0047
0048 return __a + __half_diff;
0049 }
0050
0051 template <class _Tp, enable_if_t<is_object_v<_Tp> && !is_void_v<_Tp> && (sizeof(_Tp) > 0), int> = 0>
0052 _LIBCPP_HIDE_FROM_ABI constexpr _Tp* midpoint(_Tp* __a, _Tp* __b) noexcept {
0053 return __a + std::midpoint(ptrdiff_t(0), __b - __a);
0054 }
0055
0056 template <typename _Tp>
0057 _LIBCPP_HIDE_FROM_ABI constexpr int __sign(_Tp __val) {
0058 return (_Tp(0) < __val) - (__val < _Tp(0));
0059 }
0060
0061 template <typename _Fp>
0062 _LIBCPP_HIDE_FROM_ABI constexpr _Fp __fp_abs(_Fp __f) {
0063 return __f >= 0 ? __f : -__f;
0064 }
0065
0066 template <class _Fp>
0067 _LIBCPP_HIDE_FROM_ABI constexpr enable_if_t<is_floating_point_v<_Fp>, _Fp> midpoint(_Fp __a, _Fp __b) noexcept {
0068 constexpr _Fp __lo = numeric_limits<_Fp>::min() * 2;
0069 constexpr _Fp __hi = numeric_limits<_Fp>::max() / 2;
0070
0071
0072 if (std::__fp_abs(__a) <= __hi && std::__fp_abs(__b) <= __hi)
0073 return (__a + __b) / 2;
0074 if (std::__fp_abs(__a) < __lo)
0075 return __a + __b / 2;
0076 if (std::__fp_abs(__b) < __lo)
0077 return __a / 2 + __b;
0078
0079 return __a / 2 + __b / 2;
0080 }
0081
0082 #endif
0083
0084 _LIBCPP_END_NAMESPACE_STD
0085
0086 _LIBCPP_POP_MACROS
0087
0088 #endif