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//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___NUMERIC_MIDPOINT_H
11#define _LIBCPP___NUMERIC_MIDPOINT_H
12
13#include <__config>
14#include <__cstddef/ptrdiff_t.h>
15#include <__type_traits/is_floating_point.h>
16#include <__type_traits/is_integral.h>
17#include <__type_traits/is_object.h>
18#include <__type_traits/is_same.h>
19#include <__type_traits/is_void.h>
20#include <__type_traits/make_unsigned.h>
21#include <__type_traits/remove_cv.h>
22#include <limits>
23
24#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
25# pragma GCC system_header
26#endif
27
28_LIBCPP_PUSH_MACROS
29#include <__undef_macros>
30
31_LIBCPP_BEGIN_NAMESPACE_STD
32
33#if _LIBCPP_STD_VER >= 20
34template <class _Tp>
35 requires(is_integral_v<_Tp> && !is_same_v<remove_cv_t<_Tp>, bool>)
36[[nodiscard]]
37_LIBCPP_HIDE_FROM_ABI constexpr _Tp midpoint(_Tp __a, _Tp __b) noexcept _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK {
38 using _Up = make_unsigned_t<_Tp>;
39 constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;
40
41 _Up __diff = _Up(__b) - _Up(__a);
42 _Up __sign_bit = __b < __a;
43
44 _Up __half_diff = (__diff / 2) + (__sign_bit << __bitshift) + (__sign_bit & __diff);
45
46 return __a + __half_diff;
47}
48
49template <class _Tp>
50 requires(is_object_v<_Tp> && (sizeof(_Tp) > 0))
51[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp* midpoint(_Tp* __a, _Tp* __b) noexcept {
52 return __a + std::midpoint(ptrdiff_t(0), __b - __a);
53}
54
55template <typename _Fp>
56_LIBCPP_HIDE_FROM_ABI constexpr _Fp __fp_abs(_Fp __f) {
57 return __f >= 0 ? __f : -__f;
58}
59
60template <class _Fp>
61 requires(is_floating_point_v<_Fp>)
62[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Fp midpoint(_Fp __a, _Fp __b) noexcept {
63 constexpr _Fp __lo = numeric_limits<_Fp>::min() * 2;
64 constexpr _Fp __hi = numeric_limits<_Fp>::max() / 2;
65
66 // typical case: overflow is impossible
67 if (std::__fp_abs(__a) <= __hi && std::__fp_abs(__b) <= __hi)
68 return (__a + __b) / 2; // always correctly rounded
69 if (std::__fp_abs(__a) < __lo)
70 return __a + __b / 2; // not safe to halve a
71 if (std::__fp_abs(__b) < __lo)
72 return __a / 2 + __b; // not safe to halve b
73
74 return __a / 2 + __b / 2; // otherwise correctly rounded
75}
76
77#endif // _LIBCPP_STD_VER >= 20
78
79_LIBCPP_END_NAMESPACE_STD
80
81_LIBCPP_POP_MACROS
82
83#endif // _LIBCPP___NUMERIC_MIDPOINT_H
84