Path: blob/main/contrib/llvm-project/libcxx/include/__numeric/midpoint.h
35233 views
// -*- C++ -*-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-exception6//7//===----------------------------------------------------------------------===//89#ifndef _LIBCPP___NUMERIC_MIDPOINT_H10#define _LIBCPP___NUMERIC_MIDPOINT_H1112#include <__config>13#include <__type_traits/enable_if.h>14#include <__type_traits/is_floating_point.h>15#include <__type_traits/is_integral.h>16#include <__type_traits/is_null_pointer.h>17#include <__type_traits/is_object.h>18#include <__type_traits/is_pointer.h>19#include <__type_traits/is_same.h>20#include <__type_traits/is_void.h>21#include <__type_traits/make_unsigned.h>22#include <__type_traits/remove_pointer.h>23#include <cstddef>24#include <limits>2526#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)27# pragma GCC system_header28#endif2930_LIBCPP_PUSH_MACROS31#include <__undef_macros>3233_LIBCPP_BEGIN_NAMESPACE_STD3435#if _LIBCPP_STD_VER >= 2036template <class _Tp>37_LIBCPP_HIDE_FROM_ABI constexpr enable_if_t<is_integral_v<_Tp> && !is_same_v<bool, _Tp> && !is_null_pointer_v<_Tp>, _Tp>38midpoint(_Tp __a, _Tp __b) noexcept _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK {39using _Up = make_unsigned_t<_Tp>;40constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;4142_Up __diff = _Up(__b) - _Up(__a);43_Up __sign_bit = __b < __a;4445_Up __half_diff = (__diff / 2) + (__sign_bit << __bitshift) + (__sign_bit & __diff);4647return __a + __half_diff;48}4950template <class _Tp, enable_if_t<is_object_v<_Tp> && !is_void_v<_Tp> && (sizeof(_Tp) > 0), int> = 0>51_LIBCPP_HIDE_FROM_ABI constexpr _Tp* midpoint(_Tp* __a, _Tp* __b) noexcept {52return __a + std::midpoint(ptrdiff_t(0), __b - __a);53}5455template <typename _Tp>56_LIBCPP_HIDE_FROM_ABI constexpr int __sign(_Tp __val) {57return (_Tp(0) < __val) - (__val < _Tp(0));58}5960template <typename _Fp>61_LIBCPP_HIDE_FROM_ABI constexpr _Fp __fp_abs(_Fp __f) {62return __f >= 0 ? __f : -__f;63}6465template <class _Fp>66_LIBCPP_HIDE_FROM_ABI constexpr enable_if_t<is_floating_point_v<_Fp>, _Fp> midpoint(_Fp __a, _Fp __b) noexcept {67constexpr _Fp __lo = numeric_limits<_Fp>::min() * 2;68constexpr _Fp __hi = numeric_limits<_Fp>::max() / 2;6970// typical case: overflow is impossible71if (std::__fp_abs(__a) <= __hi && std::__fp_abs(__b) <= __hi)72return (__a + __b) / 2; // always correctly rounded73if (std::__fp_abs(__a) < __lo)74return __a + __b / 2; // not safe to halve a75if (std::__fp_abs(__b) < __lo)76return __a / 2 + __b; // not safe to halve b7778return __a / 2 + __b / 2; // otherwise correctly rounded79}8081#endif // _LIBCPP_STD_VER >= 208283_LIBCPP_END_NAMESPACE_STD8485_LIBCPP_POP_MACROS8687#endif // _LIBCPP___NUMERIC_MIDPOINT_H888990