| 14519 | */ |
| 14520 | template<typename FloatType> |
| 14521 | boundaries compute_boundaries(FloatType value) |
| 14522 | { |
| 14523 | JSON_ASSERT(std::isfinite(value)); |
| 14524 | JSON_ASSERT(value > 0); |
| 14525 | |
| 14526 | // Convert the IEEE representation into a diyfp. |
| 14527 | // |
| 14528 | // If v is denormal: |
| 14529 | // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) |
| 14530 | // If v is normalized: |
| 14531 | // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) |
| 14532 | |
| 14533 | static_assert(std::numeric_limits<FloatType>::is_iec559, |
| 14534 | "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); |
| 14535 | |
| 14536 | constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit) |
| 14537 | constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1); |
| 14538 | constexpr int kMinExp = 1 - kBias; |
| 14539 | constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) |
| 14540 | |
| 14541 | using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type; |
| 14542 | |
| 14543 | const std::uint64_t bits = reinterpret_bits<bits_type>(value); |
| 14544 | const std::uint64_t E = bits >> (kPrecision - 1); |
| 14545 | const std::uint64_t F = bits & (kHiddenBit - 1); |
| 14546 | |
| 14547 | const bool is_denormal = E == 0; |
| 14548 | const diyfp v = is_denormal |
| 14549 | ? diyfp(F, kMinExp) |
| 14550 | : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias); |
| 14551 | |
| 14552 | // Compute the boundaries m- and m+ of the floating-point value |
| 14553 | // v = f * 2^e. |
| 14554 | // |
| 14555 | // Determine v- and v+, the floating-point predecessor and successor if v, |
| 14556 | // respectively. |
| 14557 | // |
| 14558 | // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) |
| 14559 | // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) |
| 14560 | // |
| 14561 | // v+ = v + 2^e |
| 14562 | // |
| 14563 | // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ |
| 14564 | // between m- and m+ round to v, regardless of how the input rounding |
| 14565 | // algorithm breaks ties. |
| 14566 | // |
| 14567 | // ---+-------------+-------------+-------------+-------------+--- (A) |
| 14568 | // v- m- v m+ v+ |
| 14569 | // |
| 14570 | // -----------------+------+------+-------------+-------------+--- (B) |
| 14571 | // v- m- v m+ v+ |
| 14572 | |
| 14573 | const bool lower_boundary_is_closer = F == 0 && E > 1; |
| 14574 | const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); |
| 14575 | const diyfp m_minus = lower_boundary_is_closer |
| 14576 | ? diyfp(4 * v.f - 1, v.e - 2) // (B) |
| 14577 | : diyfp(2 * v.f - 1, v.e - 1); // (A) |
| 14578 | |