abs.hpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. #ifndef BOOST_MATH_CCMATH_ABS
  8. #define BOOST_MATH_CCMATH_ABS
  9. #include <cmath>
  10. #include <type_traits>
  11. #include <limits>
  12. #include <boost/math/tools/is_constant_evaluated.hpp>
  13. #include <boost/math/tools/assert.hpp>
  14. #include <boost/math/ccmath/isnan.hpp>
  15. #include <boost/math/ccmath/isinf.hpp>
  16. #include <boost/math/tools/is_standalone.hpp>
  17. #ifndef BOOST_MATH_STANDALONE
  18. #include <boost/config.hpp>
  19. #ifdef BOOST_NO_CXX17_IF_CONSTEXPR
  20. #error "The header <boost/math/norms.hpp> can only be used in C++17 and later."
  21. #endif
  22. #endif
  23. namespace boost::math::ccmath {
  24. namespace detail {
  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. if constexpr (std::is_integral_v<T>)
  37. {
  38. BOOST_MATH_ASSERT(x != (std::numeric_limits<T>::min)());
  39. }
  40. return x >= 0 ? x : -x;
  41. }
  42. } // Namespace detail
  43. template <typename T, std::enable_if_t<!std::is_unsigned_v<T>, bool> = true>
  44. constexpr T abs(T x) noexcept
  45. {
  46. if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))
  47. {
  48. return detail::abs_impl<T>(x);
  49. }
  50. else
  51. {
  52. using std::abs;
  53. return abs(x);
  54. }
  55. }
  56. // If abs() is called with an argument of type X for which is_unsigned_v<X> is true and if X
  57. // cannot be converted to int by integral promotion (7.3.7), the program is ill-formed.
  58. template <typename T, std::enable_if_t<std::is_unsigned_v<T>, bool> = true>
  59. constexpr T abs(T x) noexcept
  60. {
  61. if constexpr (std::is_convertible_v<T, int>)
  62. {
  63. return detail::abs_impl<int>(static_cast<int>(x));
  64. }
  65. else
  66. {
  67. static_assert(sizeof(T) == 0, "Taking the absolute value of an unsigned value not convertible to int is UB.");
  68. return T(0); // Unreachable, but suppresses warnings
  69. }
  70. }
  71. constexpr long int labs(long int j) noexcept
  72. {
  73. return boost::math::ccmath::abs(j);
  74. }
  75. constexpr long long int llabs(long long int j) noexcept
  76. {
  77. return boost::math::ccmath::abs(j);
  78. }
  79. } // Namespaces
  80. #endif // BOOST_MATH_CCMATH_ABS