d2s.ipp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. // Copyright 2018 Ulf Adams
  2. //
  3. // The contents of this file may be used under the terms of the Apache License,
  4. // Version 2.0.
  5. //
  6. // (See accompanying file LICENSE-Apache or copy at
  7. // http://www.apache.org/licenses/LICENSE-2.0)
  8. //
  9. // Alternatively, the contents of this file may be used under the terms of
  10. // the Boost Software License, Version 1.0.
  11. // (See accompanying file LICENSE-Boost or copy at
  12. // https://www.boost.org/LICENSE_1_0.txt)
  13. //
  14. // Unless required by applicable law or agreed to in writing, this software
  15. // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. // KIND, either express or implied.
  17. // Runtime compiler options:
  18. // -DRYU_DEBUG Generate verbose debugging output to stdout.
  19. //
  20. // -DRYU_ONLY_64_BIT_OPS Avoid using uint128_t or 64-bit intrinsics. Slower,
  21. // depending on your compiler.
  22. //
  23. // -DRYU_OPTIMIZE_SIZE Use smaller lookup tables. Instead of storing every
  24. // required power of 5, only store every 26th entry, and compute
  25. // intermediate values with a multiplication. This reduces the lookup table
  26. // size by about 10x (only one case, and only double) at the cost of some
  27. // performance. Currently requires MSVC intrinsics.
  28. /*
  29. This is a derivative work
  30. */
  31. #ifndef BOOST_JSON_DETAIL_RYU_IMPL_D2S_IPP
  32. #define BOOST_JSON_DETAIL_RYU_IMPL_D2S_IPP
  33. #include <boost/json/detail/ryu/ryu.hpp>
  34. #include <cstdlib>
  35. #include <cstring>
  36. #ifdef RYU_DEBUG
  37. #include <stdio.h>
  38. #endif
  39. // ABSL avoids uint128_t on Win32 even if __SIZEOF_INT128__ is defined.
  40. // Let's do the same for now.
  41. #if defined(__SIZEOF_INT128__) && !defined(_MSC_VER) && !defined(RYU_ONLY_64_BIT_OPS)
  42. #define BOOST_JSON_RYU_HAS_UINT128
  43. #elif defined(_MSC_VER) && !defined(RYU_ONLY_64_BIT_OPS) && defined(_M_X64)
  44. #define BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS
  45. #endif
  46. #include <boost/json/detail/ryu/detail/common.hpp>
  47. #include <boost/json/detail/ryu/detail/digit_table.hpp>
  48. #include <boost/json/detail/ryu/detail/d2s.hpp>
  49. #include <boost/json/detail/ryu/detail/d2s_intrinsics.hpp>
  50. namespace boost {
  51. namespace json {
  52. namespace detail {
  53. namespace ryu {
  54. namespace detail {
  55. // We need a 64x128-bit multiplication and a subsequent 128-bit shift.
  56. // Multiplication:
  57. // The 64-bit factor is variable and passed in, the 128-bit factor comes
  58. // from a lookup table. We know that the 64-bit factor only has 55
  59. // significant bits (i.e., the 9 topmost bits are zeros). The 128-bit
  60. // factor only has 124 significant bits (i.e., the 4 topmost bits are
  61. // zeros).
  62. // Shift:
  63. // In principle, the multiplication result requires 55 + 124 = 179 bits to
  64. // represent. However, we then shift this value to the right by j, which is
  65. // at least j >= 115, so the result is guaranteed to fit into 179 - 115 = 64
  66. // bits. This means that we only need the topmost 64 significant bits of
  67. // the 64x128-bit multiplication.
  68. //
  69. // There are several ways to do this:
  70. // 1. Best case: the compiler exposes a 128-bit type.
  71. // We perform two 64x64-bit multiplications, add the higher 64 bits of the
  72. // lower result to the higher result, and shift by j - 64 bits.
  73. //
  74. // We explicitly cast from 64-bit to 128-bit, so the compiler can tell
  75. // that these are only 64-bit inputs, and can map these to the best
  76. // possible sequence of assembly instructions.
  77. // x64 machines happen to have matching assembly instructions for
  78. // 64x64-bit multiplications and 128-bit shifts.
  79. //
  80. // 2. Second best case: the compiler exposes intrinsics for the x64 assembly
  81. // instructions mentioned in 1.
  82. //
  83. // 3. We only have 64x64 bit instructions that return the lower 64 bits of
  84. // the result, i.e., we have to use plain C.
  85. // Our inputs are less than the full width, so we have three options:
  86. // a. Ignore this fact and just implement the intrinsics manually.
  87. // b. Split both into 31-bit pieces, which guarantees no internal overflow,
  88. // but requires extra work upfront (unless we change the lookup table).
  89. // c. Split only the first factor into 31-bit pieces, which also guarantees
  90. // no internal overflow, but requires extra work since the intermediate
  91. // results are not perfectly aligned.
  92. #if defined(BOOST_JSON_RYU_HAS_UINT128)
  93. // Best case: use 128-bit type.
  94. inline
  95. std::uint64_t
  96. mulShift(
  97. const std::uint64_t m,
  98. const std::uint64_t* const mul,
  99. const std::int32_t j) noexcept
  100. {
  101. const uint128_t b0 = ((uint128_t) m) * mul[0];
  102. const uint128_t b2 = ((uint128_t) m) * mul[1];
  103. return (std::uint64_t) (((b0 >> 64) + b2) >> (j - 64));
  104. }
  105. inline
  106. uint64_t
  107. mulShiftAll(
  108. const std::uint64_t m,
  109. const std::uint64_t* const mul,
  110. std::int32_t const j,
  111. std::uint64_t* const vp,
  112. std::uint64_t* const vm,
  113. const std::uint32_t mmShift) noexcept
  114. {
  115. // m <<= 2;
  116. // uint128_t b0 = ((uint128_t) m) * mul[0]; // 0
  117. // uint128_t b2 = ((uint128_t) m) * mul[1]; // 64
  118. //
  119. // uint128_t hi = (b0 >> 64) + b2;
  120. // uint128_t lo = b0 & 0xffffffffffffffffull;
  121. // uint128_t factor = (((uint128_t) mul[1]) << 64) + mul[0];
  122. // uint128_t vpLo = lo + (factor << 1);
  123. // *vp = (std::uint64_t) ((hi + (vpLo >> 64)) >> (j - 64));
  124. // uint128_t vmLo = lo - (factor << mmShift);
  125. // *vm = (std::uint64_t) ((hi + (vmLo >> 64) - (((uint128_t) 1ull) << 64)) >> (j - 64));
  126. // return (std::uint64_t) (hi >> (j - 64));
  127. *vp = mulShift(4 * m + 2, mul, j);
  128. *vm = mulShift(4 * m - 1 - mmShift, mul, j);
  129. return mulShift(4 * m, mul, j);
  130. }
  131. #elif defined(BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS)
  132. inline
  133. std::uint64_t
  134. mulShift(
  135. const std::uint64_t m,
  136. const std::uint64_t* const mul,
  137. const std::int32_t j) noexcept
  138. {
  139. // m is maximum 55 bits
  140. std::uint64_t high1; // 128
  141. std::uint64_t const low1 = umul128(m, mul[1], &high1); // 64
  142. std::uint64_t high0; // 64
  143. umul128(m, mul[0], &high0); // 0
  144. std::uint64_t const sum = high0 + low1;
  145. if (sum < high0)
  146. ++high1; // overflow into high1
  147. return shiftright128(sum, high1, j - 64);
  148. }
  149. inline
  150. std::uint64_t
  151. mulShiftAll(
  152. const std::uint64_t m,
  153. const std::uint64_t* const mul,
  154. const std::int32_t j,
  155. std::uint64_t* const vp,
  156. std::uint64_t* const vm,
  157. const std::uint32_t mmShift) noexcept
  158. {
  159. *vp = mulShift(4 * m + 2, mul, j);
  160. *vm = mulShift(4 * m - 1 - mmShift, mul, j);
  161. return mulShift(4 * m, mul, j);
  162. }
  163. #else // !defined(BOOST_JSON_RYU_HAS_UINT128) && !defined(BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS)
  164. inline
  165. std::uint64_t
  166. mulShiftAll(
  167. std::uint64_t m,
  168. const std::uint64_t* const mul,
  169. const std::int32_t j,
  170. std::uint64_t* const vp,
  171. std::uint64_t* const vm,
  172. const std::uint32_t mmShift)
  173. {
  174. m <<= 1;
  175. // m is maximum 55 bits
  176. std::uint64_t tmp;
  177. std::uint64_t const lo = umul128(m, mul[0], &tmp);
  178. std::uint64_t hi;
  179. std::uint64_t const mid = tmp + umul128(m, mul[1], &hi);
  180. hi += mid < tmp; // overflow into hi
  181. const std::uint64_t lo2 = lo + mul[0];
  182. const std::uint64_t mid2 = mid + mul[1] + (lo2 < lo);
  183. const std::uint64_t hi2 = hi + (mid2 < mid);
  184. *vp = shiftright128(mid2, hi2, (std::uint32_t)(j - 64 - 1));
  185. if (mmShift == 1)
  186. {
  187. const std::uint64_t lo3 = lo - mul[0];
  188. const std::uint64_t mid3 = mid - mul[1] - (lo3 > lo);
  189. const std::uint64_t hi3 = hi - (mid3 > mid);
  190. *vm = shiftright128(mid3, hi3, (std::uint32_t)(j - 64 - 1));
  191. }
  192. else
  193. {
  194. const std::uint64_t lo3 = lo + lo;
  195. const std::uint64_t mid3 = mid + mid + (lo3 < lo);
  196. const std::uint64_t hi3 = hi + hi + (mid3 < mid);
  197. const std::uint64_t lo4 = lo3 - mul[0];
  198. const std::uint64_t mid4 = mid3 - mul[1] - (lo4 > lo3);
  199. const std::uint64_t hi4 = hi3 - (mid4 > mid3);
  200. *vm = shiftright128(mid4, hi4, (std::uint32_t)(j - 64));
  201. }
  202. return shiftright128(mid, hi, (std::uint32_t)(j - 64 - 1));
  203. }
  204. #endif // BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS
  205. inline
  206. std::uint32_t
  207. decimalLength17(
  208. const std::uint64_t v)
  209. {
  210. // This is slightly faster than a loop.
  211. // The average output length is 16.38 digits, so we check high-to-low.
  212. // Function precondition: v is not an 18, 19, or 20-digit number.
  213. // (17 digits are sufficient for round-tripping.)
  214. BOOST_ASSERT(v < 100000000000000000L);
  215. if (v >= 10000000000000000L) { return 17; }
  216. if (v >= 1000000000000000L) { return 16; }
  217. if (v >= 100000000000000L) { return 15; }
  218. if (v >= 10000000000000L) { return 14; }
  219. if (v >= 1000000000000L) { return 13; }
  220. if (v >= 100000000000L) { return 12; }
  221. if (v >= 10000000000L) { return 11; }
  222. if (v >= 1000000000L) { return 10; }
  223. if (v >= 100000000L) { return 9; }
  224. if (v >= 10000000L) { return 8; }
  225. if (v >= 1000000L) { return 7; }
  226. if (v >= 100000L) { return 6; }
  227. if (v >= 10000L) { return 5; }
  228. if (v >= 1000L) { return 4; }
  229. if (v >= 100L) { return 3; }
  230. if (v >= 10L) { return 2; }
  231. return 1;
  232. }
  233. // A floating decimal representing m * 10^e.
  234. struct floating_decimal_64
  235. {
  236. std::uint64_t mantissa;
  237. // Decimal exponent's range is -324 to 308
  238. // inclusive, and can fit in a short if needed.
  239. std::int32_t exponent;
  240. };
  241. inline
  242. floating_decimal_64
  243. d2d(
  244. const std::uint64_t ieeeMantissa,
  245. const std::uint32_t ieeeExponent)
  246. {
  247. std::int32_t e2;
  248. std::uint64_t m2;
  249. if (ieeeExponent == 0)
  250. {
  251. // We subtract 2 so that the bounds computation has 2 additional bits.
  252. e2 = 1 - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2;
  253. m2 = ieeeMantissa;
  254. }
  255. else
  256. {
  257. e2 = (std::int32_t)ieeeExponent - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2;
  258. m2 = (1ull << DOUBLE_MANTISSA_BITS) | ieeeMantissa;
  259. }
  260. const bool even = (m2 & 1) == 0;
  261. const bool acceptBounds = even;
  262. #ifdef RYU_DEBUG
  263. printf("-> %" PRIu64 " * 2^%d\n", m2, e2 + 2);
  264. #endif
  265. // Step 2: Determine the interval of valid decimal representations.
  266. const std::uint64_t mv = 4 * m2;
  267. // Implicit bool -> int conversion. True is 1, false is 0.
  268. const std::uint32_t mmShift = ieeeMantissa != 0 || ieeeExponent <= 1;
  269. // We would compute mp and mm like this:
  270. // uint64_t mp = 4 * m2 + 2;
  271. // uint64_t mm = mv - 1 - mmShift;
  272. // Step 3: Convert to a decimal power base using 128-bit arithmetic.
  273. std::uint64_t vr, vp, vm;
  274. std::int32_t e10;
  275. bool vmIsTrailingZeros = false;
  276. bool vrIsTrailingZeros = false;
  277. if (e2 >= 0) {
  278. // I tried special-casing q == 0, but there was no effect on performance.
  279. // This expression is slightly faster than max(0, log10Pow2(e2) - 1).
  280. const std::uint32_t q = log10Pow2(e2) - (e2 > 3);
  281. e10 = (std::int32_t)q;
  282. const std::int32_t k = DOUBLE_POW5_INV_BITCOUNT + pow5bits((int32_t)q) - 1;
  283. const std::int32_t i = -e2 + (std::int32_t)q + k;
  284. #if defined(BOOST_JSON_RYU_OPTIMIZE_SIZE)
  285. uint64_t pow5[2];
  286. double_computeInvPow5(q, pow5);
  287. vr = mulShiftAll(m2, pow5, i, &vp, &vm, mmShift);
  288. #else
  289. vr = mulShiftAll(m2, DOUBLE_POW5_INV_SPLIT()[q], i, &vp, &vm, mmShift);
  290. #endif
  291. #ifdef RYU_DEBUG
  292. printf("%" PRIu64 " * 2^%d / 10^%u\n", mv, e2, q);
  293. printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
  294. #endif
  295. if (q <= 21)
  296. {
  297. // This should use q <= 22, but I think 21 is also safe. Smaller values
  298. // may still be safe, but it's more difficult to reason about them.
  299. // Only one of mp, mv, and mm can be a multiple of 5, if any.
  300. const std::uint32_t mvMod5 = ((std::uint32_t)mv) - 5 * ((std::uint32_t)div5(mv));
  301. if (mvMod5 == 0)
  302. {
  303. vrIsTrailingZeros = multipleOfPowerOf5(mv, q);
  304. }
  305. else if (acceptBounds)
  306. {
  307. // Same as min(e2 + (~mm & 1), pow5Factor(mm)) >= q
  308. // <=> e2 + (~mm & 1) >= q && pow5Factor(mm) >= q
  309. // <=> true && pow5Factor(mm) >= q, since e2 >= q.
  310. vmIsTrailingZeros = multipleOfPowerOf5(mv - 1 - mmShift, q);
  311. }
  312. else
  313. {
  314. // Same as min(e2 + 1, pow5Factor(mp)) >= q.
  315. vp -= multipleOfPowerOf5(mv + 2, q);
  316. }
  317. }
  318. }
  319. else
  320. {
  321. // This expression is slightly faster than max(0, log10Pow5(-e2) - 1).
  322. const std::uint32_t q = log10Pow5(-e2) - (-e2 > 1);
  323. e10 = (std::int32_t)q + e2;
  324. const std::int32_t i = -e2 - (std::int32_t)q;
  325. const std::int32_t k = pow5bits(i) - DOUBLE_POW5_BITCOUNT;
  326. const std::int32_t j = (std::int32_t)q - k;
  327. #if defined(BOOST_JSON_RYU_OPTIMIZE_SIZE)
  328. std::uint64_t pow5[2];
  329. double_computePow5(i, pow5);
  330. vr = mulShiftAll(m2, pow5, j, &vp, &vm, mmShift);
  331. #else
  332. vr = mulShiftAll(m2, DOUBLE_POW5_SPLIT()[i], j, &vp, &vm, mmShift);
  333. #endif
  334. #ifdef RYU_DEBUG
  335. printf("%" PRIu64 " * 5^%d / 10^%u\n", mv, -e2, q);
  336. printf("%u %d %d %d\n", q, i, k, j);
  337. printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
  338. #endif
  339. if (q <= 1)
  340. {
  341. // {vr,vp,vm} is trailing zeros if {mv,mp,mm} has at least q trailing 0 bits.
  342. // mv = 4 * m2, so it always has at least two trailing 0 bits.
  343. vrIsTrailingZeros = true;
  344. if (acceptBounds)
  345. {
  346. // mm = mv - 1 - mmShift, so it has 1 trailing 0 bit iff mmShift == 1.
  347. vmIsTrailingZeros = mmShift == 1;
  348. }
  349. else
  350. {
  351. // mp = mv + 2, so it always has at least one trailing 0 bit.
  352. --vp;
  353. }
  354. }
  355. else if (q < 63)
  356. {
  357. // TODO(ulfjack): Use a tighter bound here.
  358. // We want to know if the full product has at least q trailing zeros.
  359. // We need to compute min(p2(mv), p5(mv) - e2) >= q
  360. // <=> p2(mv) >= q && p5(mv) - e2 >= q
  361. // <=> p2(mv) >= q (because -e2 >= q)
  362. vrIsTrailingZeros = multipleOfPowerOf2(mv, q);
  363. #ifdef RYU_DEBUG
  364. printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
  365. #endif
  366. }
  367. }
  368. #ifdef RYU_DEBUG
  369. printf("e10=%d\n", e10);
  370. printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
  371. printf("vm is trailing zeros=%s\n", vmIsTrailingZeros ? "true" : "false");
  372. printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
  373. #endif
  374. // Step 4: Find the shortest decimal representation in the interval of valid representations.
  375. std::int32_t removed = 0;
  376. std::uint8_t lastRemovedDigit = 0;
  377. std::uint64_t output;
  378. // On average, we remove ~2 digits.
  379. if (vmIsTrailingZeros || vrIsTrailingZeros)
  380. {
  381. // General case, which happens rarely (~0.7%).
  382. for (;;)
  383. {
  384. const std::uint64_t vpDiv10 = div10(vp);
  385. const std::uint64_t vmDiv10 = div10(vm);
  386. if (vpDiv10 <= vmDiv10)
  387. break;
  388. const std::uint32_t vmMod10 = ((std::uint32_t)vm) - 10 * ((std::uint32_t)vmDiv10);
  389. const std::uint64_t vrDiv10 = div10(vr);
  390. const std::uint32_t vrMod10 = ((std::uint32_t)vr) - 10 * ((std::uint32_t)vrDiv10);
  391. vmIsTrailingZeros &= vmMod10 == 0;
  392. vrIsTrailingZeros &= lastRemovedDigit == 0;
  393. lastRemovedDigit = (uint8_t)vrMod10;
  394. vr = vrDiv10;
  395. vp = vpDiv10;
  396. vm = vmDiv10;
  397. ++removed;
  398. }
  399. #ifdef RYU_DEBUG
  400. printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
  401. printf("d-10=%s\n", vmIsTrailingZeros ? "true" : "false");
  402. #endif
  403. if (vmIsTrailingZeros)
  404. {
  405. for (;;)
  406. {
  407. const std::uint64_t vmDiv10 = div10(vm);
  408. const std::uint32_t vmMod10 = ((std::uint32_t)vm) - 10 * ((std::uint32_t)vmDiv10);
  409. if (vmMod10 != 0)
  410. break;
  411. const std::uint64_t vpDiv10 = div10(vp);
  412. const std::uint64_t vrDiv10 = div10(vr);
  413. const std::uint32_t vrMod10 = ((std::uint32_t)vr) - 10 * ((std::uint32_t)vrDiv10);
  414. vrIsTrailingZeros &= lastRemovedDigit == 0;
  415. lastRemovedDigit = (uint8_t)vrMod10;
  416. vr = vrDiv10;
  417. vp = vpDiv10;
  418. vm = vmDiv10;
  419. ++removed;
  420. }
  421. }
  422. #ifdef RYU_DEBUG
  423. printf("%" PRIu64 " %d\n", vr, lastRemovedDigit);
  424. printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
  425. #endif
  426. if (vrIsTrailingZeros && lastRemovedDigit == 5 && vr % 2 == 0)
  427. {
  428. // Round even if the exact number is .....50..0.
  429. lastRemovedDigit = 4;
  430. }
  431. // We need to take vr + 1 if vr is outside bounds or we need to round up.
  432. output = vr + ((vr == vm && (!acceptBounds || !vmIsTrailingZeros)) || lastRemovedDigit >= 5);
  433. }
  434. else
  435. {
  436. // Specialized for the common case (~99.3%). Percentages below are relative to this.
  437. bool roundUp = false;
  438. const std::uint64_t vpDiv100 = div100(vp);
  439. const std::uint64_t vmDiv100 = div100(vm);
  440. if (vpDiv100 > vmDiv100)
  441. {
  442. // Optimization: remove two digits at a time (~86.2%).
  443. const std::uint64_t vrDiv100 = div100(vr);
  444. const std::uint32_t vrMod100 = ((std::uint32_t)vr) - 100 * ((std::uint32_t)vrDiv100);
  445. roundUp = vrMod100 >= 50;
  446. vr = vrDiv100;
  447. vp = vpDiv100;
  448. vm = vmDiv100;
  449. removed += 2;
  450. }
  451. // Loop iterations below (approximately), without optimization above:
  452. // 0: 0.03%, 1: 13.8%, 2: 70.6%, 3: 14.0%, 4: 1.40%, 5: 0.14%, 6+: 0.02%
  453. // Loop iterations below (approximately), with optimization above:
  454. // 0: 70.6%, 1: 27.8%, 2: 1.40%, 3: 0.14%, 4+: 0.02%
  455. for (;;)
  456. {
  457. const std::uint64_t vpDiv10 = div10(vp);
  458. const std::uint64_t vmDiv10 = div10(vm);
  459. if (vpDiv10 <= vmDiv10)
  460. break;
  461. const std::uint64_t vrDiv10 = div10(vr);
  462. const std::uint32_t vrMod10 = ((std::uint32_t)vr) - 10 * ((std::uint32_t)vrDiv10);
  463. roundUp = vrMod10 >= 5;
  464. vr = vrDiv10;
  465. vp = vpDiv10;
  466. vm = vmDiv10;
  467. ++removed;
  468. }
  469. #ifdef RYU_DEBUG
  470. printf("%" PRIu64 " roundUp=%s\n", vr, roundUp ? "true" : "false");
  471. printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
  472. #endif
  473. // We need to take vr + 1 if vr is outside bounds or we need to round up.
  474. output = vr + (vr == vm || roundUp);
  475. }
  476. const std::int32_t exp = e10 + removed;
  477. #ifdef RYU_DEBUG
  478. printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
  479. printf("O=%" PRIu64 "\n", output);
  480. printf("EXP=%d\n", exp);
  481. #endif
  482. floating_decimal_64 fd;
  483. fd.exponent = exp;
  484. fd.mantissa = output;
  485. return fd;
  486. }
  487. inline
  488. int
  489. to_chars(
  490. const floating_decimal_64 v,
  491. const bool sign,
  492. char* const result)
  493. {
  494. // Step 5: Print the decimal representation.
  495. int index = 0;
  496. if (sign)
  497. result[index++] = '-';
  498. std::uint64_t output = v.mantissa;
  499. std::uint32_t const olength = decimalLength17(output);
  500. #ifdef RYU_DEBUG
  501. printf("DIGITS=%" PRIu64 "\n", v.mantissa);
  502. printf("OLEN=%u\n", olength);
  503. printf("EXP=%u\n", v.exponent + olength);
  504. #endif
  505. // Print the decimal digits.
  506. // The following code is equivalent to:
  507. // for (uint32_t i = 0; i < olength - 1; ++i) {
  508. // const uint32_t c = output % 10; output /= 10;
  509. // result[index + olength - i] = (char) ('0' + c);
  510. // }
  511. // result[index] = '0' + output % 10;
  512. std::uint32_t i = 0;
  513. // We prefer 32-bit operations, even on 64-bit platforms.
  514. // We have at most 17 digits, and uint32_t can store 9 digits.
  515. // If output doesn't fit into uint32_t, we cut off 8 digits,
  516. // so the rest will fit into uint32_t.
  517. if ((output >> 32) != 0)
  518. {
  519. // Expensive 64-bit division.
  520. std::uint64_t const q = div1e8(output);
  521. std::uint32_t output2 = ((std::uint32_t)output) - 100000000 * ((std::uint32_t)q);
  522. output = q;
  523. const std::uint32_t c = output2 % 10000;
  524. output2 /= 10000;
  525. const std::uint32_t d = output2 % 10000;
  526. const std::uint32_t c0 = (c % 100) << 1;
  527. const std::uint32_t c1 = (c / 100) << 1;
  528. const std::uint32_t d0 = (d % 100) << 1;
  529. const std::uint32_t d1 = (d / 100) << 1;
  530. std::memcpy(result + index + olength - i - 1, DIGIT_TABLE() + c0, 2);
  531. std::memcpy(result + index + olength - i - 3, DIGIT_TABLE() + c1, 2);
  532. std::memcpy(result + index + olength - i - 5, DIGIT_TABLE() + d0, 2);
  533. std::memcpy(result + index + olength - i - 7, DIGIT_TABLE() + d1, 2);
  534. i += 8;
  535. }
  536. uint32_t output2 = (std::uint32_t)output;
  537. while (output2 >= 10000)
  538. {
  539. #ifdef __clang__ // https://bugs.llvm.org/show_bug.cgi?id=38217
  540. const uint32_t c = output2 - 10000 * (output2 / 10000);
  541. #else
  542. const uint32_t c = output2 % 10000;
  543. #endif
  544. output2 /= 10000;
  545. const uint32_t c0 = (c % 100) << 1;
  546. const uint32_t c1 = (c / 100) << 1;
  547. memcpy(result + index + olength - i - 1, DIGIT_TABLE() + c0, 2);
  548. memcpy(result + index + olength - i - 3, DIGIT_TABLE() + c1, 2);
  549. i += 4;
  550. }
  551. if (output2 >= 100) {
  552. const uint32_t c = (output2 % 100) << 1;
  553. output2 /= 100;
  554. memcpy(result + index + olength - i - 1, DIGIT_TABLE() + c, 2);
  555. i += 2;
  556. }
  557. if (output2 >= 10) {
  558. const uint32_t c = output2 << 1;
  559. // We can't use memcpy here: the decimal dot goes between these two digits.
  560. result[index + olength - i] = DIGIT_TABLE()[c + 1];
  561. result[index] = DIGIT_TABLE()[c];
  562. }
  563. else {
  564. result[index] = (char)('0' + output2);
  565. }
  566. // Print decimal point if needed.
  567. if (olength > 1) {
  568. result[index + 1] = '.';
  569. index += olength + 1;
  570. }
  571. else {
  572. ++index;
  573. }
  574. // Print the exponent.
  575. result[index++] = 'E';
  576. int32_t exp = v.exponent + (int32_t)olength - 1;
  577. if (exp < 0) {
  578. result[index++] = '-';
  579. exp = -exp;
  580. }
  581. if (exp >= 100) {
  582. const int32_t c = exp % 10;
  583. memcpy(result + index, DIGIT_TABLE() + 2 * (exp / 10), 2);
  584. result[index + 2] = (char)('0' + c);
  585. index += 3;
  586. }
  587. else if (exp >= 10) {
  588. memcpy(result + index, DIGIT_TABLE() + 2 * exp, 2);
  589. index += 2;
  590. }
  591. else {
  592. result[index++] = (char)('0' + exp);
  593. }
  594. return index;
  595. }
  596. static inline bool d2d_small_int(const uint64_t ieeeMantissa, const uint32_t ieeeExponent,
  597. floating_decimal_64* const v) {
  598. const uint64_t m2 = (1ull << DOUBLE_MANTISSA_BITS) | ieeeMantissa;
  599. const int32_t e2 = (int32_t) ieeeExponent - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS;
  600. if (e2 > 0) {
  601. // f = m2 * 2^e2 >= 2^53 is an integer.
  602. // Ignore this case for now.
  603. return false;
  604. }
  605. if (e2 < -52) {
  606. // f < 1.
  607. return false;
  608. }
  609. // Since 2^52 <= m2 < 2^53 and 0 <= -e2 <= 52: 1 <= f = m2 / 2^-e2 < 2^53.
  610. // Test if the lower -e2 bits of the significand are 0, i.e. whether the fraction is 0.
  611. const uint64_t mask = (1ull << -e2) - 1;
  612. const uint64_t fraction = m2 & mask;
  613. if (fraction != 0) {
  614. return false;
  615. }
  616. // f is an integer in the range [1, 2^53).
  617. // Note: mantissa might contain trailing (decimal) 0's.
  618. // Note: since 2^53 < 10^16, there is no need to adjust decimalLength17().
  619. v->mantissa = m2 >> -e2;
  620. v->exponent = 0;
  621. return true;
  622. }
  623. } // detail
  624. int
  625. d2s_buffered_n(
  626. double f,
  627. char* result,
  628. bool allow_infinity_and_nan) noexcept
  629. {
  630. using namespace detail;
  631. // Step 1: Decode the floating-point number, and unify normalized and subnormal cases.
  632. std::uint64_t const bits = double_to_bits(f);
  633. #ifdef RYU_DEBUG
  634. printf("IN=");
  635. for (std::int32_t bit = 63; bit >= 0; --bit) {
  636. printf("%d", (int)((bits >> bit) & 1));
  637. }
  638. printf("\n");
  639. #endif
  640. // Decode bits into sign, mantissa, and exponent.
  641. const bool ieeeSign = ((bits >> (DOUBLE_MANTISSA_BITS + DOUBLE_EXPONENT_BITS)) & 1) != 0;
  642. const std::uint64_t ieeeMantissa = bits & ((1ull << DOUBLE_MANTISSA_BITS) - 1);
  643. const std::uint32_t ieeeExponent = (std::uint32_t)((bits >> DOUBLE_MANTISSA_BITS) & ((1u << DOUBLE_EXPONENT_BITS) - 1));
  644. // Case distinction; exit early for the easy cases.
  645. if (ieeeExponent == ((1u << DOUBLE_EXPONENT_BITS) - 1u) || (ieeeExponent == 0 && ieeeMantissa == 0)) {
  646. // We changed how special numbers are output by default
  647. if (allow_infinity_and_nan)
  648. return copy_special_str(result, ieeeSign, ieeeExponent != 0, ieeeMantissa != 0);
  649. else
  650. return copy_special_str_conforming(result, ieeeSign, ieeeExponent != 0, ieeeMantissa != 0);
  651. }
  652. floating_decimal_64 v;
  653. const bool isSmallInt = d2d_small_int(ieeeMantissa, ieeeExponent, &v);
  654. if (isSmallInt) {
  655. // For small integers in the range [1, 2^53), v.mantissa might contain trailing (decimal) zeros.
  656. // For scientific notation we need to move these zeros into the exponent.
  657. // (This is not needed for fixed-point notation, so it might be beneficial to trim
  658. // trailing zeros in to_chars only if needed - once fixed-point notation output is implemented.)
  659. for (;;) {
  660. std::uint64_t const q = div10(v.mantissa);
  661. std::uint32_t const r = ((std::uint32_t) v.mantissa) - 10 * ((std::uint32_t) q);
  662. if (r != 0)
  663. break;
  664. v.mantissa = q;
  665. ++v.exponent;
  666. }
  667. }
  668. else {
  669. v = d2d(ieeeMantissa, ieeeExponent);
  670. }
  671. return to_chars(v, ieeeSign, result);
  672. }
  673. } // ryu
  674. } // detail
  675. } // namespace json
  676. } // namespace boost
  677. #endif