Debian Codegraph @

third-party/boost-math/include/boost/math/ccmath/abs.hpp

raw
1 // (C) Copyright Matt Borland 2021.
2 // Use, modification and distribution are subject to the
3 // Boost Software License, Version 1.0. (See accompanying file
4 // 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_ABS
9 #define BOOST_MATH_CCMATH_ABS
10
11 #include <boost/math/ccmath/detail/config.hpp>
12
13 #ifdef BOOST_MATH_NO_CCMATH
14 #error "The header <boost/math/abs.hpp> can only be used in C++17 and later."
15 #endif
16
17 #include <boost/math/tools/assert.hpp>
18 #include <boost/math/ccmath/isnan.hpp>
19 #include <boost/math/ccmath/isinf.hpp>
20
21 namespace boost::math::ccmath {
22
23 namespace detail {
24
25 template <typename T>
26 constexpr T abs_impl(T x) noexcept
27 {
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 detail
46
47 template <typename T, std::enable_if_t<!std::is_unsigned_v<T>, bool> = true>
48 constexpr T abs(T x) noexcept
49 {
50 if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))
51 {
52 return detail::abs_impl<T>(x);
53 }
54 else
55 {
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 X
62 // cannot be converted to int by integral promotion (7.3.7), the program is ill-formed.
63 template <typename T, std::enable_if_t<std::is_unsigned_v<T>, bool> = true>
64 constexpr T abs(T x) noexcept
65 {
66 if constexpr (std::is_convertible_v<T, int>)
67 {
68 return detail::abs_impl<int>(static_cast<int>(x));
69 }
70 else
71 {
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 warnings
74 }
75 }
76
77 constexpr long int labs(long int j) noexcept
78 {
79 return boost::math::ccmath::abs(j);
80 }
81
82 constexpr long long int llabs(long long int j) noexcept
83 {
84 return boost::math::ccmath::abs(j);
85 }
86
87 } // Namespaces
88
89 #endif // BOOST_MATH_CCMATH_ABS