trunc.hpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. #ifndef BOOST_MATH_CCMATH_TRUNC_HPP
  6. #define BOOST_MATH_CCMATH_TRUNC_HPP
  7. #include <boost/math/ccmath/detail/config.hpp>
  8. #ifdef BOOST_MATH_NO_CCMATH
  9. #error "The header <boost/math/trunc.hpp> can only be used in C++17 and later."
  10. #endif
  11. #include <boost/math/ccmath/abs.hpp>
  12. #include <boost/math/ccmath/isinf.hpp>
  13. #include <boost/math/ccmath/isnan.hpp>
  14. #include <boost/math/ccmath/floor.hpp>
  15. #include <boost/math/ccmath/ceil.hpp>
  16. namespace boost::math::ccmath {
  17. namespace detail {
  18. template <typename T>
  19. inline constexpr T trunc_impl(T arg) noexcept
  20. {
  21. return (arg > 0) ? boost::math::ccmath::floor(arg) : boost::math::ccmath::ceil(arg);
  22. }
  23. } // Namespace detail
  24. template <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>
  25. inline constexpr Real trunc(Real arg) noexcept
  26. {
  27. if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))
  28. {
  29. return boost::math::ccmath::abs(arg) == Real(0) ? arg :
  30. boost::math::ccmath::isinf(arg) ? arg :
  31. boost::math::ccmath::isnan(arg) ? arg :
  32. boost::math::ccmath::detail::trunc_impl(arg);
  33. }
  34. else
  35. {
  36. using std::trunc;
  37. return trunc(arg);
  38. }
  39. }
  40. template <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>
  41. inline constexpr double trunc(Z arg) noexcept
  42. {
  43. return boost::math::ccmath::trunc(static_cast<double>(arg));
  44. }
  45. inline constexpr float truncf(float arg) noexcept
  46. {
  47. return boost::math::ccmath::trunc(arg);
  48. }
  49. #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
  50. inline constexpr long double truncl(long double arg) noexcept
  51. {
  52. return boost::math::ccmath::trunc(arg);
  53. }
  54. #endif
  55. } // Namespaces
  56. #endif // BOOST_MATH_CCMATH_TRUNC_HPP