Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions include/bitcoin/system/impl/math/cast.ipp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#ifndef LIBBITCOIN_SYSTEM_MATH_CAST_IPP
#define LIBBITCOIN_SYSTEM_MATH_CAST_IPP

#include <cmath>
#include <bitcoin/system/define.hpp>

namespace libbitcoin {
Expand Down Expand Up @@ -209,6 +210,30 @@ constexpr Unsigned to_unsigned(Unsigned value) NOEXCEPT
// Floating point casts.
// ----------------------------------------------------------------------------

template <typename Integer, typename Float,
if_integral_integer<Integer>,
if_floating_point<Float>>
constexpr bool to_integer(Integer& out, Float value) NOEXCEPT
{
if (!std::isfinite(value))
return false;

Float integer{};
const Float fractional = std::modf(value, &integer);
if (fractional != 0.0)
return false;

if (integer > static_cast<Float>(std::numeric_limits<Integer>::max()) ||
integer < static_cast<Float>(std::numeric_limits<Integer>::min()))
return false;

// Floating point conversion in c++ requires explicit or implicit cast.
BC_PUSH_WARNING(NO_CASTS_FOR_ARITHMETIC_CONVERSION)
out = static_cast<Integer>(integer);
BC_POP_WARNING()
return true;
}

template <typename Integer, typename Float,
if_integral_integer<Integer>,
if_floating_point<Float>>
Expand Down
6 changes: 6 additions & 0 deletions include/bitcoin/system/math/cast.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,12 @@ constexpr Unsigned to_unsigned(Unsigned value) NOEXCEPT;
/// Floating point casts.
/// ---------------------------------------------------------------------------

/// Cast floating point to integral integer, overflow guarded.
template <typename Integer = size_t, typename Float,
if_integral_integer<Integer> = true,
if_floating_point<Float> = true>
constexpr bool to_integer(Integer& out, Float value) NOEXCEPT;

/// Cast floating point to integral integer, overflow unguarded.
template <typename Integer = size_t, typename Float,
if_integral_integer<Integer> = true,
Expand Down
Loading