Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:38:58

0001 // Copyright 2018 Ulf Adams
0002 //
0003 // The contents of this file may be used under the terms of the Apache License,
0004 // Version 2.0.
0005 //
0006 //    (See accompanying file LICENSE-Apache or copy at
0007 //     http://www.apache.org/licenses/LICENSE-2.0)
0008 //
0009 // Alternatively, the contents of this file may be used under the terms of
0010 // the Boost Software License, Version 1.0.
0011 //    (See accompanying file LICENSE-Boost or copy at
0012 //     https://www.boost.org/LICENSE_1_0.txt)
0013 //
0014 // Unless required by applicable law or agreed to in writing, this software
0015 // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
0016 // KIND, either express or implied.
0017 
0018 // Runtime compiler options:
0019 // -DRYU_DEBUG Generate verbose debugging output to stdout.
0020 //
0021 // -DRYU_ONLY_64_BIT_OPS Avoid using uint128_t or 64-bit intrinsics. Slower,
0022 //     depending on your compiler.
0023 //
0024 // -DRYU_OPTIMIZE_SIZE Use smaller lookup tables. Instead of storing every
0025 //     required power of 5, only store every 26th entry, and compute
0026 //     intermediate values with a multiplication. This reduces the lookup table
0027 //     size by about 10x (only one case, and only double) at the cost of some
0028 //     performance. Currently requires MSVC intrinsics.
0029 
0030 /*
0031     This is a derivative work
0032 */
0033 
0034 #ifndef BOOST_JSON_DETAIL_RYU_IMPL_D2S_IPP
0035 #define BOOST_JSON_DETAIL_RYU_IMPL_D2S_IPP
0036 
0037 #include <boost/json/detail/ryu/ryu.hpp>
0038 #include <cstdlib>
0039 #include <cstring>
0040 
0041 #ifdef RYU_DEBUG
0042 #include <stdio.h>
0043 #endif
0044 
0045 // ABSL avoids uint128_t on Win32 even if __SIZEOF_INT128__ is defined.
0046 // Let's do the same for now.
0047 #if defined(__SIZEOF_INT128__) && !defined(_MSC_VER) && !defined(RYU_ONLY_64_BIT_OPS)
0048 #define BOOST_JSON_RYU_HAS_UINT128
0049 #elif defined(_MSC_VER) && !defined(RYU_ONLY_64_BIT_OPS) && defined(_M_X64)
0050 #define BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS
0051 #endif
0052 
0053 #include <boost/json/detail/ryu/detail/common.hpp>
0054 #include <boost/json/detail/ryu/detail/digit_table.hpp>
0055 #include <boost/json/detail/ryu/detail/d2s.hpp>
0056 #include <boost/json/detail/ryu/detail/d2s_intrinsics.hpp>
0057 
0058 namespace boost {
0059 namespace json {
0060 namespace detail {
0061 
0062 namespace ryu {
0063 namespace detail {
0064 
0065 // We need a 64x128-bit multiplication and a subsequent 128-bit shift.
0066 // Multiplication:
0067 //   The 64-bit factor is variable and passed in, the 128-bit factor comes
0068 //   from a lookup table. We know that the 64-bit factor only has 55
0069 //   significant bits (i.e., the 9 topmost bits are zeros). The 128-bit
0070 //   factor only has 124 significant bits (i.e., the 4 topmost bits are
0071 //   zeros).
0072 // Shift:
0073 //   In principle, the multiplication result requires 55 + 124 = 179 bits to
0074 //   represent. However, we then shift this value to the right by j, which is
0075 //   at least j >= 115, so the result is guaranteed to fit into 179 - 115 = 64
0076 //   bits. This means that we only need the topmost 64 significant bits of
0077 //   the 64x128-bit multiplication.
0078 //
0079 // There are several ways to do this:
0080 // 1. Best case: the compiler exposes a 128-bit type.
0081 //    We perform two 64x64-bit multiplications, add the higher 64 bits of the
0082 //    lower result to the higher result, and shift by j - 64 bits.
0083 //
0084 //    We explicitly cast from 64-bit to 128-bit, so the compiler can tell
0085 //    that these are only 64-bit inputs, and can map these to the best
0086 //    possible sequence of assembly instructions.
0087 //    x64 machines happen to have matching assembly instructions for
0088 //    64x64-bit multiplications and 128-bit shifts.
0089 //
0090 // 2. Second best case: the compiler exposes intrinsics for the x64 assembly
0091 //    instructions mentioned in 1.
0092 //
0093 // 3. We only have 64x64 bit instructions that return the lower 64 bits of
0094 //    the result, i.e., we have to use plain C.
0095 //    Our inputs are less than the full width, so we have three options:
0096 //    a. Ignore this fact and just implement the intrinsics manually.
0097 //    b. Split both into 31-bit pieces, which guarantees no internal overflow,
0098 //       but requires extra work upfront (unless we change the lookup table).
0099 //    c. Split only the first factor into 31-bit pieces, which also guarantees
0100 //       no internal overflow, but requires extra work since the intermediate
0101 //       results are not perfectly aligned.
0102 #if defined(BOOST_JSON_RYU_HAS_UINT128)
0103 
0104 // Best case: use 128-bit type.
0105 inline
0106 std::uint64_t
0107     mulShift(
0108     const std::uint64_t m,
0109     const std::uint64_t* const mul,
0110     const std::int32_t j) noexcept
0111 {
0112     const uint128_t b0 = ((uint128_t) m) * mul[0];
0113     const uint128_t b2 = ((uint128_t) m) * mul[1];
0114     return (std::uint64_t) (((b0 >> 64) + b2) >> (j - 64));
0115 }
0116 
0117 inline
0118 uint64_t
0119 mulShiftAll(
0120     const std::uint64_t m,
0121     const std::uint64_t* const mul,
0122     std::int32_t const j,
0123     std::uint64_t* const vp,
0124     std::uint64_t* const vm,
0125     const std::uint32_t mmShift) noexcept
0126 {
0127 //  m <<= 2;
0128 //  uint128_t b0 = ((uint128_t) m) * mul[0]; // 0
0129 //  uint128_t b2 = ((uint128_t) m) * mul[1]; // 64
0130 //
0131 //  uint128_t hi = (b0 >> 64) + b2;
0132 //  uint128_t lo = b0 & 0xffffffffffffffffull;
0133 //  uint128_t factor = (((uint128_t) mul[1]) << 64) + mul[0];
0134 //  uint128_t vpLo = lo + (factor << 1);
0135 //  *vp = (std::uint64_t) ((hi + (vpLo >> 64)) >> (j - 64));
0136 //  uint128_t vmLo = lo - (factor << mmShift);
0137 //  *vm = (std::uint64_t) ((hi + (vmLo >> 64) - (((uint128_t) 1ull) << 64)) >> (j - 64));
0138 //  return (std::uint64_t) (hi >> (j - 64));
0139     *vp = mulShift(4 * m + 2, mul, j);
0140     *vm = mulShift(4 * m - 1 - mmShift, mul, j);
0141     return mulShift(4 * m, mul, j);
0142 }
0143 
0144 #elif defined(BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS)
0145 
0146 inline
0147 std::uint64_t
0148 mulShift(
0149     const std::uint64_t m,
0150     const std::uint64_t* const mul,
0151     const std::int32_t j) noexcept
0152 {
0153     // m is maximum 55 bits
0154     std::uint64_t high1;                                   // 128
0155     std::uint64_t const low1 = umul128(m, mul[1], &high1); // 64
0156     std::uint64_t high0;                                   // 64
0157     umul128(m, mul[0], &high0);                            // 0
0158     std::uint64_t const sum = high0 + low1;
0159     if (sum < high0)
0160         ++high1; // overflow into high1
0161     return shiftright128(sum, high1, j - 64);
0162 }
0163 
0164 inline
0165 std::uint64_t
0166 mulShiftAll(
0167     const std::uint64_t m,
0168     const std::uint64_t* const mul,
0169     const std::int32_t j,
0170     std::uint64_t* const vp,
0171     std::uint64_t* const vm,
0172     const std::uint32_t mmShift) noexcept
0173 {
0174     *vp = mulShift(4 * m + 2, mul, j);
0175     *vm = mulShift(4 * m - 1 - mmShift, mul, j);
0176     return mulShift(4 * m, mul, j);
0177 }
0178 
0179 #else // !defined(BOOST_JSON_RYU_HAS_UINT128) && !defined(BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS)
0180 
0181 inline
0182 std::uint64_t
0183 mulShiftAll(
0184     std::uint64_t m,
0185     const std::uint64_t* const mul,
0186     const std::int32_t j,
0187     std::uint64_t* const vp,
0188     std::uint64_t* const vm,
0189     const std::uint32_t mmShift)
0190 {
0191     m <<= 1;
0192     // m is maximum 55 bits
0193     std::uint64_t tmp;
0194     std::uint64_t const lo = umul128(m, mul[0], &tmp);
0195     std::uint64_t hi;
0196     std::uint64_t const mid = tmp + umul128(m, mul[1], &hi);
0197     hi += mid < tmp; // overflow into hi
0198 
0199     const std::uint64_t lo2 = lo + mul[0];
0200     const std::uint64_t mid2 = mid + mul[1] + (lo2 < lo);
0201     const std::uint64_t hi2 = hi + (mid2 < mid);
0202     *vp = shiftright128(mid2, hi2, (std::uint32_t)(j - 64 - 1));
0203 
0204     if (mmShift == 1)
0205     {
0206         const std::uint64_t lo3 = lo - mul[0];
0207         const std::uint64_t mid3 = mid - mul[1] - (lo3 > lo);
0208         const std::uint64_t hi3 = hi - (mid3 > mid);
0209         *vm = shiftright128(mid3, hi3, (std::uint32_t)(j - 64 - 1));
0210     }
0211     else
0212     {
0213         const std::uint64_t lo3 = lo + lo;
0214         const std::uint64_t mid3 = mid + mid + (lo3 < lo);
0215         const std::uint64_t hi3 = hi + hi + (mid3 < mid);
0216         const std::uint64_t lo4 = lo3 - mul[0];
0217         const std::uint64_t mid4 = mid3 - mul[1] - (lo4 > lo3);
0218         const std::uint64_t hi4 = hi3 - (mid4 > mid3);
0219         *vm = shiftright128(mid4, hi4, (std::uint32_t)(j - 64));
0220     }
0221 
0222     return shiftright128(mid, hi, (std::uint32_t)(j - 64 - 1));
0223 }
0224 
0225 #endif // BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS
0226 
0227 inline
0228 std::uint32_t
0229 decimalLength17(
0230     const std::uint64_t v)
0231 {
0232     // This is slightly faster than a loop.
0233     // The average output length is 16.38 digits, so we check high-to-low.
0234     // Function precondition: v is not an 18, 19, or 20-digit number.
0235     // (17 digits are sufficient for round-tripping.)
0236     BOOST_ASSERT(v < 100000000000000000L);
0237     if (v >= 10000000000000000L) { return 17; }
0238     if (v >= 1000000000000000L) { return 16; }
0239     if (v >= 100000000000000L) { return 15; }
0240     if (v >= 10000000000000L) { return 14; }
0241     if (v >= 1000000000000L) { return 13; }
0242     if (v >= 100000000000L) { return 12; }
0243     if (v >= 10000000000L) { return 11; }
0244     if (v >= 1000000000L) { return 10; }
0245     if (v >= 100000000L) { return 9; }
0246     if (v >= 10000000L) { return 8; }
0247     if (v >= 1000000L) { return 7; }
0248     if (v >= 100000L) { return 6; }
0249     if (v >= 10000L) { return 5; }
0250     if (v >= 1000L) { return 4; }
0251     if (v >= 100L) { return 3; }
0252     if (v >= 10L) { return 2; }
0253     return 1;
0254 }
0255 
0256 // A floating decimal representing m * 10^e.
0257 struct floating_decimal_64
0258 {
0259     std::uint64_t mantissa;
0260     // Decimal exponent's range is -324 to 308
0261     // inclusive, and can fit in a short if needed.
0262     std::int32_t exponent;
0263 };
0264 
0265 inline
0266 floating_decimal_64
0267 d2d(
0268     const std::uint64_t ieeeMantissa,
0269     const std::uint32_t ieeeExponent)
0270 {
0271     std::int32_t e2;
0272     std::uint64_t m2;
0273     if (ieeeExponent == 0)
0274     {
0275         // We subtract 2 so that the bounds computation has 2 additional bits.
0276         e2 = 1 - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2;
0277         m2 = ieeeMantissa;
0278     }
0279     else
0280     {
0281         e2 = (std::int32_t)ieeeExponent - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2;
0282         m2 = (1ull << DOUBLE_MANTISSA_BITS) | ieeeMantissa;
0283     }
0284     const bool even = (m2 & 1) == 0;
0285     const bool acceptBounds = even;
0286 
0287 #ifdef RYU_DEBUG
0288     printf("-> %" PRIu64 " * 2^%d\n", m2, e2 + 2);
0289 #endif
0290 
0291     // Step 2: Determine the interval of valid decimal representations.
0292     const std::uint64_t mv = 4 * m2;
0293     // Implicit bool -> int conversion. True is 1, false is 0.
0294     const std::uint32_t mmShift = ieeeMantissa != 0 || ieeeExponent <= 1;
0295     // We would compute mp and mm like this:
0296     // uint64_t mp = 4 * m2 + 2;
0297     // uint64_t mm = mv - 1 - mmShift;
0298 
0299     // Step 3: Convert to a decimal power base using 128-bit arithmetic.
0300     std::uint64_t vr, vp, vm;
0301     std::int32_t e10;
0302     bool vmIsTrailingZeros = false;
0303     bool vrIsTrailingZeros = false;
0304     if (e2 >= 0) {
0305         // I tried special-casing q == 0, but there was no effect on performance.
0306         // This expression is slightly faster than max(0, log10Pow2(e2) - 1).
0307         const std::uint32_t q = log10Pow2(e2) - (e2 > 3);
0308         e10 = (std::int32_t)q;
0309         const std::int32_t k = DOUBLE_POW5_INV_BITCOUNT + pow5bits((int32_t)q) - 1;
0310         const std::int32_t i = -e2 + (std::int32_t)q + k;
0311 #if defined(BOOST_JSON_RYU_OPTIMIZE_SIZE)
0312         uint64_t pow5[2];
0313         double_computeInvPow5(q, pow5);
0314         vr = mulShiftAll(m2, pow5, i, &vp, &vm, mmShift);
0315 #else
0316         vr = mulShiftAll(m2, DOUBLE_POW5_INV_SPLIT()[q], i, &vp, &vm, mmShift);
0317 #endif
0318 #ifdef RYU_DEBUG
0319         printf("%" PRIu64 " * 2^%d / 10^%u\n", mv, e2, q);
0320         printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
0321 #endif
0322         if (q <= 21)
0323         {
0324             // This should use q <= 22, but I think 21 is also safe. Smaller values
0325             // may still be safe, but it's more difficult to reason about them.
0326             // Only one of mp, mv, and mm can be a multiple of 5, if any.
0327             const std::uint32_t mvMod5 = ((std::uint32_t)mv) - 5 * ((std::uint32_t)div5(mv));
0328             if (mvMod5 == 0)
0329             {
0330                 vrIsTrailingZeros = multipleOfPowerOf5(mv, q);
0331             }
0332             else if (acceptBounds)
0333             {
0334                 // Same as min(e2 + (~mm & 1), pow5Factor(mm)) >= q
0335                 // <=> e2 + (~mm & 1) >= q && pow5Factor(mm) >= q
0336                 // <=> true && pow5Factor(mm) >= q, since e2 >= q.
0337                 vmIsTrailingZeros = multipleOfPowerOf5(mv - 1 - mmShift, q);
0338             }
0339             else
0340             {
0341                 // Same as min(e2 + 1, pow5Factor(mp)) >= q.
0342                 vp -= multipleOfPowerOf5(mv + 2, q);
0343             }
0344         }
0345     }
0346     else
0347     {
0348         // This expression is slightly faster than max(0, log10Pow5(-e2) - 1).
0349         const std::uint32_t q = log10Pow5(-e2) - (-e2 > 1);
0350         e10 = (std::int32_t)q + e2;
0351         const std::int32_t i = -e2 - (std::int32_t)q;
0352         const std::int32_t k = pow5bits(i) - DOUBLE_POW5_BITCOUNT;
0353         const std::int32_t j = (std::int32_t)q - k;
0354 #if defined(BOOST_JSON_RYU_OPTIMIZE_SIZE)
0355         std::uint64_t pow5[2];
0356         double_computePow5(i, pow5);
0357         vr = mulShiftAll(m2, pow5, j, &vp, &vm, mmShift);
0358 #else
0359         vr = mulShiftAll(m2, DOUBLE_POW5_SPLIT()[i], j, &vp, &vm, mmShift);
0360 #endif
0361 #ifdef RYU_DEBUG
0362         printf("%" PRIu64 " * 5^%d / 10^%u\n", mv, -e2, q);
0363         printf("%u %d %d %d\n", q, i, k, j);
0364         printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
0365 #endif
0366         if (q <= 1)
0367         {
0368             // {vr,vp,vm} is trailing zeros if {mv,mp,mm} has at least q trailing 0 bits.
0369             // mv = 4 * m2, so it always has at least two trailing 0 bits.
0370             vrIsTrailingZeros = true;
0371             if (acceptBounds)
0372             {
0373                 // mm = mv - 1 - mmShift, so it has 1 trailing 0 bit iff mmShift == 1.
0374                 vmIsTrailingZeros = mmShift == 1;
0375             }
0376             else
0377             {
0378                 // mp = mv + 2, so it always has at least one trailing 0 bit.
0379                 --vp;
0380             }
0381         }
0382         else if (q < 63)
0383         {
0384             // TODO(ulfjack): Use a tighter bound here.
0385             // We want to know if the full product has at least q trailing zeros.
0386             // We need to compute min(p2(mv), p5(mv) - e2) >= q
0387             // <=> p2(mv) >= q && p5(mv) - e2 >= q
0388             // <=> p2(mv) >= q (because -e2 >= q)
0389             vrIsTrailingZeros = multipleOfPowerOf2(mv, q);
0390 #ifdef RYU_DEBUG
0391             printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
0392 #endif
0393         }
0394     }
0395 #ifdef RYU_DEBUG
0396     printf("e10=%d\n", e10);
0397     printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
0398     printf("vm is trailing zeros=%s\n", vmIsTrailingZeros ? "true" : "false");
0399     printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
0400 #endif
0401 
0402     // Step 4: Find the shortest decimal representation in the interval of valid representations.
0403     std::int32_t removed = 0;
0404     std::uint8_t lastRemovedDigit = 0;
0405     std::uint64_t output;
0406     // On average, we remove ~2 digits.
0407     if (vmIsTrailingZeros || vrIsTrailingZeros)
0408     {
0409         // General case, which happens rarely (~0.7%).
0410         for (;;)
0411         {
0412             const std::uint64_t vpDiv10 = div10(vp);
0413             const std::uint64_t vmDiv10 = div10(vm);
0414             if (vpDiv10 <= vmDiv10)
0415                 break;
0416             const std::uint32_t vmMod10 = ((std::uint32_t)vm) - 10 * ((std::uint32_t)vmDiv10);
0417             const std::uint64_t vrDiv10 = div10(vr);
0418             const std::uint32_t vrMod10 = ((std::uint32_t)vr) - 10 * ((std::uint32_t)vrDiv10);
0419             vmIsTrailingZeros &= vmMod10 == 0;
0420             vrIsTrailingZeros &= lastRemovedDigit == 0;
0421             lastRemovedDigit = (uint8_t)vrMod10;
0422             vr = vrDiv10;
0423             vp = vpDiv10;
0424             vm = vmDiv10;
0425             ++removed;
0426         }
0427 #ifdef RYU_DEBUG
0428         printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
0429         printf("d-10=%s\n", vmIsTrailingZeros ? "true" : "false");
0430 #endif
0431         if (vmIsTrailingZeros)
0432         {
0433             for (;;)
0434             {
0435                 const std::uint64_t vmDiv10 = div10(vm);
0436                 const std::uint32_t vmMod10 = ((std::uint32_t)vm) - 10 * ((std::uint32_t)vmDiv10);
0437                 if (vmMod10 != 0)
0438                     break;
0439                 const std::uint64_t vpDiv10 = div10(vp);
0440                 const std::uint64_t vrDiv10 = div10(vr);
0441                 const std::uint32_t vrMod10 = ((std::uint32_t)vr) - 10 * ((std::uint32_t)vrDiv10);
0442                 vrIsTrailingZeros &= lastRemovedDigit == 0;
0443                 lastRemovedDigit = (uint8_t)vrMod10;
0444                 vr = vrDiv10;
0445                 vp = vpDiv10;
0446                 vm = vmDiv10;
0447                 ++removed;
0448             }
0449         }
0450 #ifdef RYU_DEBUG
0451         printf("%" PRIu64 " %d\n", vr, lastRemovedDigit);
0452         printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
0453 #endif
0454         if (vrIsTrailingZeros && lastRemovedDigit == 5 && vr % 2 == 0)
0455         {
0456             // Round even if the exact number is .....50..0.
0457             lastRemovedDigit = 4;
0458         }
0459         // We need to take vr + 1 if vr is outside bounds or we need to round up.
0460         output = vr + ((vr == vm && (!acceptBounds || !vmIsTrailingZeros)) || lastRemovedDigit >= 5);
0461     }
0462     else
0463     {
0464         // Specialized for the common case (~99.3%). Percentages below are relative to this.
0465         bool roundUp = false;
0466         const std::uint64_t vpDiv100 = div100(vp);
0467         const std::uint64_t vmDiv100 = div100(vm);
0468         if (vpDiv100 > vmDiv100)
0469         {
0470             // Optimization: remove two digits at a time (~86.2%).
0471             const std::uint64_t vrDiv100 = div100(vr);
0472             const std::uint32_t vrMod100 = ((std::uint32_t)vr) - 100 * ((std::uint32_t)vrDiv100);
0473             roundUp = vrMod100 >= 50;
0474             vr = vrDiv100;
0475             vp = vpDiv100;
0476             vm = vmDiv100;
0477             removed += 2;
0478         }
0479         // Loop iterations below (approximately), without optimization above:
0480         // 0: 0.03%, 1: 13.8%, 2: 70.6%, 3: 14.0%, 4: 1.40%, 5: 0.14%, 6+: 0.02%
0481         // Loop iterations below (approximately), with optimization above:
0482         // 0: 70.6%, 1: 27.8%, 2: 1.40%, 3: 0.14%, 4+: 0.02%
0483         for (;;)
0484         {
0485             const std::uint64_t vpDiv10 = div10(vp);
0486             const std::uint64_t vmDiv10 = div10(vm);
0487             if (vpDiv10 <= vmDiv10)
0488                 break;
0489             const std::uint64_t vrDiv10 = div10(vr);
0490             const std::uint32_t vrMod10 = ((std::uint32_t)vr) - 10 * ((std::uint32_t)vrDiv10);
0491             roundUp = vrMod10 >= 5;
0492             vr = vrDiv10;
0493             vp = vpDiv10;
0494             vm = vmDiv10;
0495             ++removed;
0496         }
0497 #ifdef RYU_DEBUG
0498         printf("%" PRIu64 " roundUp=%s\n", vr, roundUp ? "true" : "false");
0499         printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
0500 #endif
0501         // We need to take vr + 1 if vr is outside bounds or we need to round up.
0502         output = vr + (vr == vm || roundUp);
0503     }
0504     const std::int32_t exp = e10 + removed;
0505 
0506 #ifdef RYU_DEBUG
0507     printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
0508     printf("O=%" PRIu64 "\n", output);
0509     printf("EXP=%d\n", exp);
0510 #endif
0511 
0512     floating_decimal_64 fd;
0513     fd.exponent = exp;
0514     fd.mantissa = output;
0515     return fd;
0516 }
0517 
0518 inline
0519 int
0520 to_chars(
0521     const floating_decimal_64 v,
0522     const bool sign,
0523     char* const result)
0524 {
0525     // Step 5: Print the decimal representation.
0526     int index = 0;
0527     if (sign)
0528         result[index++] = '-';
0529 
0530     std::uint64_t output = v.mantissa;
0531     std::uint32_t const olength = decimalLength17(output);
0532 
0533 #ifdef RYU_DEBUG
0534     printf("DIGITS=%" PRIu64 "\n", v.mantissa);
0535     printf("OLEN=%u\n", olength);
0536     printf("EXP=%u\n", v.exponent + olength);
0537 #endif
0538 
0539     // Print the decimal digits.
0540     // The following code is equivalent to:
0541     // for (uint32_t i = 0; i < olength - 1; ++i) {
0542     //   const uint32_t c = output % 10; output /= 10;
0543     //   result[index + olength - i] = (char) ('0' + c);
0544     // }
0545     // result[index] = '0' + output % 10;
0546 
0547     std::uint32_t i = 0;
0548     // We prefer 32-bit operations, even on 64-bit platforms.
0549     // We have at most 17 digits, and uint32_t can store 9 digits.
0550     // If output doesn't fit into uint32_t, we cut off 8 digits,
0551     // so the rest will fit into uint32_t.
0552     if ((output >> 32) != 0)
0553     {
0554         // Expensive 64-bit division.
0555         std::uint64_t const q = div1e8(output);
0556         std::uint32_t output2 = ((std::uint32_t)output) - 100000000 * ((std::uint32_t)q);
0557         output = q;
0558 
0559         const std::uint32_t c = output2 % 10000;
0560         output2 /= 10000;
0561         const std::uint32_t d = output2 % 10000;
0562         const std::uint32_t c0 = (c % 100) << 1;
0563         const std::uint32_t c1 = (c / 100) << 1;
0564         const std::uint32_t d0 = (d % 100) << 1;
0565         const std::uint32_t d1 = (d / 100) << 1;
0566         std::memcpy(result + index + olength - i - 1, DIGIT_TABLE() + c0, 2);
0567         std::memcpy(result + index + olength - i - 3, DIGIT_TABLE() + c1, 2);
0568         std::memcpy(result + index + olength - i - 5, DIGIT_TABLE() + d0, 2);
0569         std::memcpy(result + index + olength - i - 7, DIGIT_TABLE() + d1, 2);
0570         i += 8;
0571     }
0572     uint32_t output2 = (std::uint32_t)output;
0573     while (output2 >= 10000)
0574     {
0575 #ifdef __clang__ // https://bugs.llvm.org/show_bug.cgi?id=38217
0576         const uint32_t c = output2 - 10000 * (output2 / 10000);
0577 #else
0578         const uint32_t c = output2 % 10000;
0579 #endif
0580         output2 /= 10000;
0581         const uint32_t c0 = (c % 100) << 1;
0582         const uint32_t c1 = (c / 100) << 1;
0583         memcpy(result + index + olength - i - 1, DIGIT_TABLE() + c0, 2);
0584         memcpy(result + index + olength - i - 3, DIGIT_TABLE() + c1, 2);
0585         i += 4;
0586     }
0587     if (output2 >= 100) {
0588         const uint32_t c = (output2 % 100) << 1;
0589         output2 /= 100;
0590         memcpy(result + index + olength - i - 1, DIGIT_TABLE() + c, 2);
0591         i += 2;
0592     }
0593     if (output2 >= 10) {
0594         const uint32_t c = output2 << 1;
0595         // We can't use memcpy here: the decimal dot goes between these two digits.
0596         result[index + olength - i] = DIGIT_TABLE()[c + 1];
0597         result[index] = DIGIT_TABLE()[c];
0598     }
0599     else {
0600         result[index] = (char)('0' + output2);
0601     }
0602 
0603     // Print decimal point if needed.
0604     if (olength > 1) {
0605         result[index + 1] = '.';
0606         index += olength + 1;
0607     }
0608     else {
0609         ++index;
0610     }
0611 
0612     // Print the exponent.
0613     result[index++] = 'E';
0614     int32_t exp = v.exponent + (int32_t)olength - 1;
0615     if (exp < 0) {
0616         result[index++] = '-';
0617         exp = -exp;
0618     }
0619 
0620     if (exp >= 100) {
0621         const int32_t c = exp % 10;
0622         memcpy(result + index, DIGIT_TABLE() + 2 * (exp / 10), 2);
0623         result[index + 2] = (char)('0' + c);
0624         index += 3;
0625     }
0626     else if (exp >= 10) {
0627         memcpy(result + index, DIGIT_TABLE() + 2 * exp, 2);
0628         index += 2;
0629     }
0630     else {
0631         result[index++] = (char)('0' + exp);
0632     }
0633 
0634     return index;
0635 }
0636 
0637 static inline bool d2d_small_int(const uint64_t ieeeMantissa, const uint32_t ieeeExponent,
0638   floating_decimal_64* const v) {
0639   const uint64_t m2 = (1ull << DOUBLE_MANTISSA_BITS) | ieeeMantissa;
0640   const int32_t e2 = (int32_t) ieeeExponent - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS;
0641 
0642   if (e2 > 0) {
0643     // f = m2 * 2^e2 >= 2^53 is an integer.
0644     // Ignore this case for now.
0645     return false;
0646   }
0647 
0648   if (e2 < -52) {
0649     // f < 1.
0650     return false;
0651   }
0652 
0653   // Since 2^52 <= m2 < 2^53 and 0 <= -e2 <= 52: 1 <= f = m2 / 2^-e2 < 2^53.
0654   // Test if the lower -e2 bits of the significand are 0, i.e. whether the fraction is 0.
0655   const uint64_t mask = (1ull << -e2) - 1;
0656   const uint64_t fraction = m2 & mask;
0657   if (fraction != 0) {
0658     return false;
0659   }
0660 
0661   // f is an integer in the range [1, 2^53).
0662   // Note: mantissa might contain trailing (decimal) 0's.
0663   // Note: since 2^53 < 10^16, there is no need to adjust decimalLength17().
0664   v->mantissa = m2 >> -e2;
0665   v->exponent = 0;
0666   return true;
0667 }
0668 
0669 } // detail
0670 
0671 int
0672 d2s_buffered_n(
0673     double f,
0674     char* result,
0675     bool allow_infinity_and_nan) noexcept
0676 {
0677     using namespace detail;
0678     // Step 1: Decode the floating-point number, and unify normalized and subnormal cases.
0679     std::uint64_t const bits = double_to_bits(f);
0680 
0681 #ifdef RYU_DEBUG
0682     printf("IN=");
0683     for (std::int32_t bit = 63; bit >= 0; --bit) {
0684         printf("%d", (int)((bits >> bit) & 1));
0685     }
0686     printf("\n");
0687 #endif
0688 
0689     // Decode bits into sign, mantissa, and exponent.
0690     const bool ieeeSign = ((bits >> (DOUBLE_MANTISSA_BITS + DOUBLE_EXPONENT_BITS)) & 1) != 0;
0691     const std::uint64_t ieeeMantissa = bits & ((1ull << DOUBLE_MANTISSA_BITS) - 1);
0692     const std::uint32_t ieeeExponent = (std::uint32_t)((bits >> DOUBLE_MANTISSA_BITS) & ((1u << DOUBLE_EXPONENT_BITS) - 1));
0693     // Case distinction; exit early for the easy cases.
0694     if (ieeeExponent == ((1u << DOUBLE_EXPONENT_BITS) - 1u) || (ieeeExponent == 0 && ieeeMantissa == 0)) {
0695         // We changed how special numbers are output by default
0696         if (allow_infinity_and_nan)
0697             return copy_special_str(result, ieeeSign, ieeeExponent != 0, ieeeMantissa != 0);
0698         else
0699             return copy_special_str_conforming(result, ieeeSign, ieeeExponent != 0, ieeeMantissa != 0);
0700 
0701     }
0702 
0703     floating_decimal_64 v;
0704     const bool isSmallInt = d2d_small_int(ieeeMantissa, ieeeExponent, &v);
0705     if (isSmallInt) {
0706         // For small integers in the range [1, 2^53), v.mantissa might contain trailing (decimal) zeros.
0707         // For scientific notation we need to move these zeros into the exponent.
0708         // (This is not needed for fixed-point notation, so it might be beneficial to trim
0709         // trailing zeros in to_chars only if needed - once fixed-point notation output is implemented.)
0710         for (;;) {
0711             std::uint64_t const q = div10(v.mantissa);
0712             std::uint32_t const r = ((std::uint32_t) v.mantissa) - 10 * ((std::uint32_t) q);
0713             if (r != 0)
0714                 break;
0715             v.mantissa = q;
0716             ++v.exponent;
0717         }
0718     }
0719     else {
0720         v = d2d(ieeeMantissa, ieeeExponent);
0721     }
0722 
0723     return to_chars(v, ieeeSign, result);
0724 }
0725 
0726 } // ryu
0727 
0728 } // detail
0729 } // namespace json
0730 } // namespace boost
0731 
0732 #endif