trunc.hpp 1.8 KB

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