brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.2 KiB · db59502 Raw
90 lines · plain
1//  (C) Copyright Matt Borland 2021.2//  Use, modification and distribution are subject to the3//  Boost Software License, Version 1.0. (See accompanying file4//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)5//6//  Constepxr implementation of abs (see c.math.abs secion 26.8.2 of the ISO standard)7 8#ifndef BOOST_MATH_CCMATH_ABS9#define BOOST_MATH_CCMATH_ABS10 11#include <boost/math/ccmath/detail/config.hpp>12 13#ifdef BOOST_MATH_NO_CCMATH14#error "The header <boost/math/abs.hpp> can only be used in C++17 and later."15#endif16 17#include <boost/math/tools/assert.hpp>18#include <boost/math/ccmath/isnan.hpp>19#include <boost/math/ccmath/isinf.hpp>20 21namespace boost::math::ccmath {22 23namespace detail {24 25template <typename T> 26constexpr T abs_impl(T x) noexcept27{28    if ((boost::math::ccmath::isnan)(x))29    {30        return std::numeric_limits<T>::quiet_NaN();31    }32    else if (x == static_cast<T>(-0))33    {34        return static_cast<T>(0);35    }36 37    if constexpr (std::is_integral_v<T>)38    {39        BOOST_MATH_ASSERT(x != (std::numeric_limits<T>::min)());40    }41    42    return x >= 0 ? x : -x;43}44 45} // Namespace detail46 47template <typename T, std::enable_if_t<!std::is_unsigned_v<T>, bool> = true>48constexpr T abs(T x) noexcept49{50    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))51    {52        return detail::abs_impl<T>(x);53    }54    else55    {56        using std::abs;57        return abs(x);58    }59}60 61// If abs() is called with an argument of type X for which is_unsigned_v<X> is true and if X62// cannot be converted to int by integral promotion (7.3.7), the program is ill-formed.63template <typename T, std::enable_if_t<std::is_unsigned_v<T>, bool> = true>64constexpr T abs(T x) noexcept65{66    if constexpr (std::is_convertible_v<T, int>)67    {68        return detail::abs_impl<int>(static_cast<int>(x));69    }70    else71    {72        static_assert(sizeof(T) == 0, "Taking the absolute value of an unsigned value not convertible to int is UB.");73        return T(0); // Unreachable, but suppresses warnings74    }75}76 77constexpr long int labs(long int j) noexcept78{79    return boost::math::ccmath::abs(j);80}81 82constexpr long long int llabs(long long int j) noexcept83{84    return boost::math::ccmath::abs(j);85}86 87} // Namespaces88 89#endif // BOOST_MATH_CCMATH_ABS90