[lld][WebAssembly] Reinstate mistakenly disabled test. NFC
[llvm-project.git] / libcxx / include / __numeric / midpoint.h
blob668030c46bcbacc5acc7cf3f255eebefde45fc45
1 // -*- C++ -*-
2 //===----------------------------------------------------------------------===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
10 #ifndef _LIBCPP___NUMERIC_MIDPOINT_H
11 #define _LIBCPP___NUMERIC_MIDPOINT_H
13 #include <__config>
14 #include <limits>
15 #include <type_traits>
17 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
18 # pragma GCC system_header
19 #endif
21 _LIBCPP_PUSH_MACROS
22 #include <__undef_macros>
24 _LIBCPP_BEGIN_NAMESPACE_STD
26 #if _LIBCPP_STD_VER > 17
27 template <class _Tp>
28 _LIBCPP_INLINE_VISIBILITY constexpr
29 enable_if_t<is_integral_v<_Tp> && !is_same_v<bool, _Tp> && !is_null_pointer_v<_Tp>, _Tp>
30 midpoint(_Tp __a, _Tp __b) noexcept
31 _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
33 using _Up = make_unsigned_t<_Tp>;
34 constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;
36 _Up __diff = _Up(__b) - _Up(__a);
37 _Up __sign_bit = __b < __a;
39 _Up __half_diff = (__diff / 2) + (__sign_bit << __bitshift) + (__sign_bit & __diff);
41 return __a + __half_diff;
45 template <class _TPtr>
46 _LIBCPP_INLINE_VISIBILITY constexpr
47 enable_if_t<is_pointer_v<_TPtr>
48 && is_object_v<remove_pointer_t<_TPtr>>
49 && ! is_void_v<remove_pointer_t<_TPtr>>
50 && (sizeof(remove_pointer_t<_TPtr>) > 0), _TPtr>
51 midpoint(_TPtr __a, _TPtr __b) noexcept
53 return __a + _VSTD::midpoint(ptrdiff_t(0), __b - __a);
57 template <typename _Tp>
58 constexpr int __sign(_Tp __val) {
59 return (_Tp(0) < __val) - (__val < _Tp(0));
62 template <typename _Fp>
63 constexpr _Fp __fp_abs(_Fp __f) { return __f >= 0 ? __f : -__f; }
65 template <class _Fp>
66 _LIBCPP_INLINE_VISIBILITY constexpr
67 enable_if_t<is_floating_point_v<_Fp>, _Fp>
68 midpoint(_Fp __a, _Fp __b) noexcept
70 constexpr _Fp __lo = numeric_limits<_Fp>::min()*2;
71 constexpr _Fp __hi = numeric_limits<_Fp>::max()/2;
72 return __fp_abs(__a) <= __hi && __fp_abs(__b) <= __hi ? // typical case: overflow is impossible
73 (__a + __b)/2 : // always correctly rounded
74 __fp_abs(__a) < __lo ? __a + __b/2 : // not safe to halve a
75 __fp_abs(__b) < __lo ? __a/2 + __b : // not safe to halve b
76 __a/2 + __b/2; // otherwise correctly rounded
79 #endif // _LIBCPP_STD_VER > 17
81 _LIBCPP_END_NAMESPACE_STD
83 _LIBCPP_POP_MACROS
85 #endif // _LIBCPP___NUMERIC_MIDPOINT_H