Path: blob/main/contrib/llvm-project/libcxx/src/ryu/d2s.cpp
35231 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78// Copyright (c) Microsoft Corporation.9// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception1011// Copyright 2018 Ulf Adams12// Copyright (c) Microsoft Corporation. All rights reserved.1314// Boost Software License - Version 1.0 - August 17th, 20031516// Permission is hereby granted, free of charge, to any person or organization17// obtaining a copy of the software and accompanying documentation covered by18// this license (the "Software") to use, reproduce, display, distribute,19// execute, and transmit the Software, and to prepare derivative works of the20// Software, and to permit third-parties to whom the Software is furnished to21// do so, all subject to the following:2223// The copyright notices in the Software and this entire statement, including24// the above license grant, this restriction and the following disclaimer,25// must be included in all copies of the Software, in whole or in part, and26// all derivative works of the Software, unless such copies or derivative27// works are solely in the form of machine-executable object code generated by28// a source language processor.2930// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR31// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,32// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT33// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE34// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,35// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER36// DEALINGS IN THE SOFTWARE.3738// Avoid formatting to keep the changes with the original code minimal.39// clang-format off4041#include <__assert>42#include <__config>43#include <charconv>4445#include "include/ryu/common.h"46#include "include/ryu/d2fixed.h"47#include "include/ryu/d2s.h"48#include "include/ryu/d2s_full_table.h"49#include "include/ryu/d2s_intrinsics.h"50#include "include/ryu/digit_table.h"51#include "include/ryu/ryu.h"5253_LIBCPP_BEGIN_NAMESPACE_STD5455// 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 comes58// from a lookup table. We know that the 64-bit factor only has 5559// significant bits (i.e., the 9 topmost bits are zeros). The 128-bit60// factor only has 124 significant bits (i.e., the 4 topmost bits are61// zeros).62// Shift:63// In principle, the multiplication result requires 55 + 124 = 179 bits to64// represent. However, we then shift this value to the right by __j, which is65// at least __j >= 115, so the result is guaranteed to fit into 179 - 115 = 6466// bits. This means that we only need the topmost 64 significant bits of67// 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 the72// 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 tell75// that these are only 64-bit inputs, and can map these to the best76// possible sequence of assembly instructions.77// x64 machines happen to have matching assembly instructions for78// 64x64-bit multiplications and 128-bit shifts.79//80// 2. Second best case: the compiler exposes intrinsics for the x64 assembly81// instructions mentioned in 1.82//83// 3. We only have 64x64 bit instructions that return the lower 64 bits of84// 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 guarantees90// no internal overflow, but requires extra work since the intermediate91// results are not perfectly aligned.92#ifdef _LIBCPP_INTRINSIC1289394[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline uint64_t __mulShift(const uint64_t __m, const uint64_t* const __mul, const int32_t __j) {95// __m is maximum 55 bits96uint64_t __high1; // 12897const uint64_t __low1 = __ryu_umul128(__m, __mul[1], &__high1); // 6498uint64_t __high0; // 6499(void) __ryu_umul128(__m, __mul[0], &__high0); // 0100const uint64_t __sum = __high0 + __low1;101if (__sum < __high0) {102++__high1; // overflow into __high1103}104return __ryu_shiftright128(__sum, __high1, static_cast<uint32_t>(__j - 64));105}106107[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline uint64_t __mulShiftAll(const uint64_t __m, const uint64_t* const __mul, const int32_t __j,108uint64_t* const __vp, uint64_t* const __vm, const uint32_t __mmShift) {109*__vp = __mulShift(4 * __m + 2, __mul, __j);110*__vm = __mulShift(4 * __m - 1 - __mmShift, __mul, __j);111return __mulShift(4 * __m, __mul, __j);112}113114#else // ^^^ intrinsics available ^^^ / vvv intrinsics unavailable vvv115116[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline _LIBCPP_ALWAYS_INLINE uint64_t __mulShiftAll(uint64_t __m, const uint64_t* const __mul, const int32_t __j,117uint64_t* const __vp, uint64_t* const __vm, const uint32_t __mmShift) { // TRANSITION, VSO-634761118__m <<= 1;119// __m is maximum 55 bits120uint64_t __tmp;121const uint64_t __lo = __ryu_umul128(__m, __mul[0], &__tmp);122uint64_t __hi;123const uint64_t __mid = __tmp + __ryu_umul128(__m, __mul[1], &__hi);124__hi += __mid < __tmp; // overflow into __hi125126const uint64_t __lo2 = __lo + __mul[0];127const uint64_t __mid2 = __mid + __mul[1] + (__lo2 < __lo);128const uint64_t __hi2 = __hi + (__mid2 < __mid);129*__vp = __ryu_shiftright128(__mid2, __hi2, static_cast<uint32_t>(__j - 64 - 1));130131if (__mmShift == 1) {132const uint64_t __lo3 = __lo - __mul[0];133const uint64_t __mid3 = __mid - __mul[1] - (__lo3 > __lo);134const uint64_t __hi3 = __hi - (__mid3 > __mid);135*__vm = __ryu_shiftright128(__mid3, __hi3, static_cast<uint32_t>(__j - 64 - 1));136} else {137const uint64_t __lo3 = __lo + __lo;138const uint64_t __mid3 = __mid + __mid + (__lo3 < __lo);139const uint64_t __hi3 = __hi + __hi + (__mid3 < __mid);140const uint64_t __lo4 = __lo3 - __mul[0];141const uint64_t __mid4 = __mid3 - __mul[1] - (__lo4 > __lo3);142const uint64_t __hi4 = __hi3 - (__mid4 > __mid3);143*__vm = __ryu_shiftright128(__mid4, __hi4, static_cast<uint32_t>(__j - 64));144}145146return __ryu_shiftright128(__mid, __hi, static_cast<uint32_t>(__j - 64 - 1));147}148149#endif // ^^^ intrinsics unavailable ^^^150151[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline uint32_t __decimalLength17(const uint64_t __v) {152// This is slightly faster than a loop.153// The average output length is 16.38 digits, so we check high-to-low.154// Function precondition: __v is not an 18, 19, or 20-digit number.155// (17 digits are sufficient for round-tripping.)156_LIBCPP_ASSERT_INTERNAL(__v < 100000000000000000u, "");157if (__v >= 10000000000000000u) { return 17; }158if (__v >= 1000000000000000u) { return 16; }159if (__v >= 100000000000000u) { return 15; }160if (__v >= 10000000000000u) { return 14; }161if (__v >= 1000000000000u) { return 13; }162if (__v >= 100000000000u) { return 12; }163if (__v >= 10000000000u) { return 11; }164if (__v >= 1000000000u) { return 10; }165if (__v >= 100000000u) { return 9; }166if (__v >= 10000000u) { return 8; }167if (__v >= 1000000u) { return 7; }168if (__v >= 100000u) { return 6; }169if (__v >= 10000u) { return 5; }170if (__v >= 1000u) { return 4; }171if (__v >= 100u) { return 3; }172if (__v >= 10u) { return 2; }173return 1;174}175176// A floating decimal representing m * 10^e.177struct __floating_decimal_64 {178uint64_t __mantissa;179int32_t __exponent;180};181182[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline __floating_decimal_64 __d2d(const uint64_t __ieeeMantissa, const uint32_t __ieeeExponent) {183int32_t __e2;184uint64_t __m2;185if (__ieeeExponent == 0) {186// We subtract 2 so that the bounds computation has 2 additional bits.187__e2 = 1 - __DOUBLE_BIAS - __DOUBLE_MANTISSA_BITS - 2;188__m2 = __ieeeMantissa;189} else {190__e2 = static_cast<int32_t>(__ieeeExponent) - __DOUBLE_BIAS - __DOUBLE_MANTISSA_BITS - 2;191__m2 = (1ull << __DOUBLE_MANTISSA_BITS) | __ieeeMantissa;192}193const bool __even = (__m2 & 1) == 0;194const bool __acceptBounds = __even;195196// Step 2: Determine the interval of valid decimal representations.197const uint64_t __mv = 4 * __m2;198// Implicit bool -> int conversion. True is 1, false is 0.199const uint32_t __mmShift = __ieeeMantissa != 0 || __ieeeExponent <= 1;200// We would compute __mp and __mm like this:201// uint64_t __mp = 4 * __m2 + 2;202// uint64_t __mm = __mv - 1 - __mmShift;203204// Step 3: Convert to a decimal power base using 128-bit arithmetic.205uint64_t __vr, __vp, __vm;206int32_t __e10;207bool __vmIsTrailingZeros = false;208bool __vrIsTrailingZeros = false;209if (__e2 >= 0) {210// I tried special-casing __q == 0, but there was no effect on performance.211// This expression is slightly faster than max(0, __log10Pow2(__e2) - 1).212const uint32_t __q = __log10Pow2(__e2) - (__e2 > 3);213__e10 = static_cast<int32_t>(__q);214const int32_t __k = __DOUBLE_POW5_INV_BITCOUNT + __pow5bits(static_cast<int32_t>(__q)) - 1;215const int32_t __i = -__e2 + static_cast<int32_t>(__q) + __k;216__vr = __mulShiftAll(__m2, __DOUBLE_POW5_INV_SPLIT[__q], __i, &__vp, &__vm, __mmShift);217if (__q <= 21) {218// This should use __q <= 22, but I think 21 is also safe. Smaller values219// may still be safe, but it's more difficult to reason about them.220// Only one of __mp, __mv, and __mm can be a multiple of 5, if any.221const uint32_t __mvMod5 = static_cast<uint32_t>(__mv) - 5 * static_cast<uint32_t>(__div5(__mv));222if (__mvMod5 == 0) {223__vrIsTrailingZeros = __multipleOfPowerOf5(__mv, __q);224} else if (__acceptBounds) {225// Same as min(__e2 + (~__mm & 1), __pow5Factor(__mm)) >= __q226// <=> __e2 + (~__mm & 1) >= __q && __pow5Factor(__mm) >= __q227// <=> true && __pow5Factor(__mm) >= __q, since __e2 >= __q.228__vmIsTrailingZeros = __multipleOfPowerOf5(__mv - 1 - __mmShift, __q);229} else {230// Same as min(__e2 + 1, __pow5Factor(__mp)) >= __q.231__vp -= __multipleOfPowerOf5(__mv + 2, __q);232}233}234} else {235// This expression is slightly faster than max(0, __log10Pow5(-__e2) - 1).236const uint32_t __q = __log10Pow5(-__e2) - (-__e2 > 1);237__e10 = static_cast<int32_t>(__q) + __e2;238const int32_t __i = -__e2 - static_cast<int32_t>(__q);239const int32_t __k = __pow5bits(__i) - __DOUBLE_POW5_BITCOUNT;240const int32_t __j = static_cast<int32_t>(__q) - __k;241__vr = __mulShiftAll(__m2, __DOUBLE_POW5_SPLIT[__i], __j, &__vp, &__vm, __mmShift);242if (__q <= 1) {243// {__vr,__vp,__vm} is trailing zeros if {__mv,__mp,__mm} has at least __q trailing 0 bits.244// __mv = 4 * __m2, so it always has at least two trailing 0 bits.245__vrIsTrailingZeros = true;246if (__acceptBounds) {247// __mm = __mv - 1 - __mmShift, so it has 1 trailing 0 bit iff __mmShift == 1.248__vmIsTrailingZeros = __mmShift == 1;249} else {250// __mp = __mv + 2, so it always has at least one trailing 0 bit.251--__vp;252}253} else if (__q < 63) { // TRANSITION(ulfjack): Use a tighter bound here.254// We need to compute min(ntz(__mv), __pow5Factor(__mv) - __e2) >= __q - 1255// <=> ntz(__mv) >= __q - 1 && __pow5Factor(__mv) - __e2 >= __q - 1256// <=> ntz(__mv) >= __q - 1 (__e2 is negative and -__e2 >= __q)257// <=> (__mv & ((1 << (__q - 1)) - 1)) == 0258// We also need to make sure that the left shift does not overflow.259__vrIsTrailingZeros = __multipleOfPowerOf2(__mv, __q - 1);260}261}262263// Step 4: Find the shortest decimal representation in the interval of valid representations.264int32_t __removed = 0;265uint8_t __lastRemovedDigit = 0;266uint64_t _Output;267// On average, we remove ~2 digits.268if (__vmIsTrailingZeros || __vrIsTrailingZeros) {269// General case, which happens rarely (~0.7%).270for (;;) {271const uint64_t __vpDiv10 = __div10(__vp);272const uint64_t __vmDiv10 = __div10(__vm);273if (__vpDiv10 <= __vmDiv10) {274break;275}276const uint32_t __vmMod10 = static_cast<uint32_t>(__vm) - 10 * static_cast<uint32_t>(__vmDiv10);277const uint64_t __vrDiv10 = __div10(__vr);278const uint32_t __vrMod10 = static_cast<uint32_t>(__vr) - 10 * static_cast<uint32_t>(__vrDiv10);279__vmIsTrailingZeros &= __vmMod10 == 0;280__vrIsTrailingZeros &= __lastRemovedDigit == 0;281__lastRemovedDigit = static_cast<uint8_t>(__vrMod10);282__vr = __vrDiv10;283__vp = __vpDiv10;284__vm = __vmDiv10;285++__removed;286}287if (__vmIsTrailingZeros) {288for (;;) {289const uint64_t __vmDiv10 = __div10(__vm);290const uint32_t __vmMod10 = static_cast<uint32_t>(__vm) - 10 * static_cast<uint32_t>(__vmDiv10);291if (__vmMod10 != 0) {292break;293}294const uint64_t __vpDiv10 = __div10(__vp);295const uint64_t __vrDiv10 = __div10(__vr);296const uint32_t __vrMod10 = static_cast<uint32_t>(__vr) - 10 * static_cast<uint32_t>(__vrDiv10);297__vrIsTrailingZeros &= __lastRemovedDigit == 0;298__lastRemovedDigit = static_cast<uint8_t>(__vrMod10);299__vr = __vrDiv10;300__vp = __vpDiv10;301__vm = __vmDiv10;302++__removed;303}304}305if (__vrIsTrailingZeros && __lastRemovedDigit == 5 && __vr % 2 == 0) {306// Round even if the exact number is .....50..0.307__lastRemovedDigit = 4;308}309// We need to take __vr + 1 if __vr is outside bounds or we need to round up.310_Output = __vr + ((__vr == __vm && (!__acceptBounds || !__vmIsTrailingZeros)) || __lastRemovedDigit >= 5);311} else {312// Specialized for the common case (~99.3%). Percentages below are relative to this.313bool __roundUp = false;314const uint64_t __vpDiv100 = __div100(__vp);315const uint64_t __vmDiv100 = __div100(__vm);316if (__vpDiv100 > __vmDiv100) { // Optimization: remove two digits at a time (~86.2%).317const uint64_t __vrDiv100 = __div100(__vr);318const uint32_t __vrMod100 = static_cast<uint32_t>(__vr) - 100 * static_cast<uint32_t>(__vrDiv100);319__roundUp = __vrMod100 >= 50;320__vr = __vrDiv100;321__vp = __vpDiv100;322__vm = __vmDiv100;323__removed += 2;324}325// Loop iterations below (approximately), without optimization above:326// 0: 0.03%, 1: 13.8%, 2: 70.6%, 3: 14.0%, 4: 1.40%, 5: 0.14%, 6+: 0.02%327// Loop iterations below (approximately), with optimization above:328// 0: 70.6%, 1: 27.8%, 2: 1.40%, 3: 0.14%, 4+: 0.02%329for (;;) {330const uint64_t __vpDiv10 = __div10(__vp);331const uint64_t __vmDiv10 = __div10(__vm);332if (__vpDiv10 <= __vmDiv10) {333break;334}335const uint64_t __vrDiv10 = __div10(__vr);336const uint32_t __vrMod10 = static_cast<uint32_t>(__vr) - 10 * static_cast<uint32_t>(__vrDiv10);337__roundUp = __vrMod10 >= 5;338__vr = __vrDiv10;339__vp = __vpDiv10;340__vm = __vmDiv10;341++__removed;342}343// We need to take __vr + 1 if __vr is outside bounds or we need to round up.344_Output = __vr + (__vr == __vm || __roundUp);345}346const int32_t __exp = __e10 + __removed;347348__floating_decimal_64 __fd;349__fd.__exponent = __exp;350__fd.__mantissa = _Output;351return __fd;352}353354[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline to_chars_result __to_chars(char* const _First, char* const _Last, const __floating_decimal_64 __v,355chars_format _Fmt, const double __f) {356// Step 5: Print the decimal representation.357uint64_t _Output = __v.__mantissa;358int32_t _Ryu_exponent = __v.__exponent;359const uint32_t __olength = __decimalLength17(_Output);360int32_t _Scientific_exponent = _Ryu_exponent + static_cast<int32_t>(__olength) - 1;361362if (_Fmt == chars_format{}) {363int32_t _Lower;364int32_t _Upper;365366if (__olength == 1) {367// Value | Fixed | Scientific368// 1e-3 | "0.001" | "1e-03"369// 1e4 | "10000" | "1e+04"370_Lower = -3;371_Upper = 4;372} else {373// Value | Fixed | Scientific374// 1234e-7 | "0.0001234" | "1.234e-04"375// 1234e5 | "123400000" | "1.234e+08"376_Lower = -static_cast<int32_t>(__olength + 3);377_Upper = 5;378}379380if (_Lower <= _Ryu_exponent && _Ryu_exponent <= _Upper) {381_Fmt = chars_format::fixed;382} else {383_Fmt = chars_format::scientific;384}385} else if (_Fmt == chars_format::general) {386// C11 7.21.6.1 "The fprintf function"/8:387// "Let P equal [...] 6 if the precision is omitted [...].388// Then, if a conversion with style E would have an exponent of X:389// - if P > X >= -4, the conversion is with style f [...].390// - otherwise, the conversion is with style e [...]."391if (-4 <= _Scientific_exponent && _Scientific_exponent < 6) {392_Fmt = chars_format::fixed;393} else {394_Fmt = chars_format::scientific;395}396}397398if (_Fmt == chars_format::fixed) {399// Example: _Output == 1729, __olength == 4400401// _Ryu_exponent | Printed | _Whole_digits | _Total_fixed_length | Notes402// --------------|----------|---------------|----------------------|---------------------------------------403// 2 | 172900 | 6 | _Whole_digits | Ryu can't be used for printing404// 1 | 17290 | 5 | (sometimes adjusted) | when the trimmed digits are nonzero.405// --------------|----------|---------------|----------------------|---------------------------------------406// 0 | 1729 | 4 | _Whole_digits | Unified length cases.407// --------------|----------|---------------|----------------------|---------------------------------------408// -1 | 172.9 | 3 | __olength + 1 | This case can't happen for409// -2 | 17.29 | 2 | | __olength == 1, but no additional410// -3 | 1.729 | 1 | | code is needed to avoid it.411// --------------|----------|---------------|----------------------|---------------------------------------412// -4 | 0.1729 | 0 | 2 - _Ryu_exponent | C11 7.21.6.1 "The fprintf function"/8:413// -5 | 0.01729 | -1 | | "If a decimal-point character appears,414// -6 | 0.001729 | -2 | | at least one digit appears before it."415416const int32_t _Whole_digits = static_cast<int32_t>(__olength) + _Ryu_exponent;417418uint32_t _Total_fixed_length;419if (_Ryu_exponent >= 0) { // cases "172900" and "1729"420_Total_fixed_length = static_cast<uint32_t>(_Whole_digits);421if (_Output == 1) {422// Rounding can affect the number of digits.423// For example, 1e23 is exactly "99999999999999991611392" which is 23 digits instead of 24.424// We can use a lookup table to detect this and adjust the total length.425static constexpr uint8_t _Adjustment[309] = {4260,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0,4271,1,0,0,1,0,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,1,0,1,0,1,1,0,0,0,0,1,1,1,4281,0,0,0,0,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,0,1,1,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,1,0,1,1,0,1,4291,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,0,0,1,0,0,1,1,1,1,0,0,1,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,0,1,4300,1,0,1,0,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,1,1,1,0,1,0,1,1,0,0,0,1,4311,1,0,1,1,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,1,1,0,0,0,1,0,1,0,0,0,0,0,1,1,0,4320,1,0,1,1,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,1,0 };433_Total_fixed_length -= _Adjustment[_Ryu_exponent];434// _Whole_digits doesn't need to be adjusted because these cases won't refer to it later.435}436} else if (_Whole_digits > 0) { // case "17.29"437_Total_fixed_length = __olength + 1;438} else { // case "0.001729"439_Total_fixed_length = static_cast<uint32_t>(2 - _Ryu_exponent);440}441442if (_Last - _First < static_cast<ptrdiff_t>(_Total_fixed_length)) {443return { _Last, errc::value_too_large };444}445446char* _Mid;447if (_Ryu_exponent > 0) { // case "172900"448bool _Can_use_ryu;449450if (_Ryu_exponent > 22) { // 10^22 is the largest power of 10 that's exactly representable as a double.451_Can_use_ryu = false;452} else {453// Ryu generated X: __v.__mantissa * 10^_Ryu_exponent454// __v.__mantissa == 2^_Trailing_zero_bits * (__v.__mantissa >> _Trailing_zero_bits)455// 10^_Ryu_exponent == 2^_Ryu_exponent * 5^_Ryu_exponent456457// _Trailing_zero_bits is [0, 56] (aside: because 2^56 is the largest power of 2458// with 17 decimal digits, which is double's round-trip limit.)459// _Ryu_exponent is [1, 22].460// Normalization adds [2, 52] (aside: at least 2 because the pre-normalized mantissa is at least 5).461// This adds up to [3, 130], which is well below double's maximum binary exponent 1023.462463// Therefore, we just need to consider (__v.__mantissa >> _Trailing_zero_bits) * 5^_Ryu_exponent.464465// If that product would exceed 53 bits, then X can't be exactly represented as a double.466// (That's not a problem for round-tripping, because X is close enough to the original double,467// but X isn't mathematically equal to the original double.) This requires a high-precision fallback.468469// If the product is 53 bits or smaller, then X can be exactly represented as a double (and we don't470// need to re-synthesize it; the original double must have been X, because Ryu wouldn't produce the471// same output for two different doubles X and Y). This allows Ryu's output to be used (zero-filled).472473// (2^53 - 1) / 5^0 (for indexing), (2^53 - 1) / 5^1, ..., (2^53 - 1) / 5^22474static constexpr uint64_t _Max_shifted_mantissa[23] = {4759007199254740991u, 1801439850948198u, 360287970189639u, 72057594037927u, 14411518807585u,4762882303761517u, 576460752303u, 115292150460u, 23058430092u, 4611686018u, 922337203u, 184467440u,47736893488u, 7378697u, 1475739u, 295147u, 59029u, 11805u, 2361u, 472u, 94u, 18u, 3u };478479unsigned long _Trailing_zero_bits;480#ifdef _LIBCPP_HAS_BITSCAN64481(void) _BitScanForward64(&_Trailing_zero_bits, __v.__mantissa); // __v.__mantissa is guaranteed nonzero482#else // ^^^ 64-bit ^^^ / vvv 32-bit vvv483const uint32_t _Low_mantissa = static_cast<uint32_t>(__v.__mantissa);484if (_Low_mantissa != 0) {485(void) _BitScanForward(&_Trailing_zero_bits, _Low_mantissa);486} else {487const uint32_t _High_mantissa = static_cast<uint32_t>(__v.__mantissa >> 32); // nonzero here488(void) _BitScanForward(&_Trailing_zero_bits, _High_mantissa);489_Trailing_zero_bits += 32;490}491#endif // ^^^ 32-bit ^^^492const uint64_t _Shifted_mantissa = __v.__mantissa >> _Trailing_zero_bits;493_Can_use_ryu = _Shifted_mantissa <= _Max_shifted_mantissa[_Ryu_exponent];494}495496if (!_Can_use_ryu) {497// Print the integer exactly.498// Performance note: This will redundantly perform bounds checking.499// Performance note: This will redundantly decompose the IEEE representation.500return __d2fixed_buffered_n(_First, _Last, __f, 0);501}502503// _Can_use_ryu504// Print the decimal digits, left-aligned within [_First, _First + _Total_fixed_length).505_Mid = _First + __olength;506} else { // cases "1729", "17.29", and "0.001729"507// Print the decimal digits, right-aligned within [_First, _First + _Total_fixed_length).508_Mid = _First + _Total_fixed_length;509}510511// We prefer 32-bit operations, even on 64-bit platforms.512// We have at most 17 digits, and uint32_t can store 9 digits.513// If _Output doesn't fit into uint32_t, we cut off 8 digits,514// so the rest will fit into uint32_t.515if ((_Output >> 32) != 0) {516// Expensive 64-bit division.517const uint64_t __q = __div1e8(_Output);518uint32_t __output2 = static_cast<uint32_t>(_Output - 100000000 * __q);519_Output = __q;520521const uint32_t __c = __output2 % 10000;522__output2 /= 10000;523const uint32_t __d = __output2 % 10000;524const uint32_t __c0 = (__c % 100) << 1;525const uint32_t __c1 = (__c / 100) << 1;526const uint32_t __d0 = (__d % 100) << 1;527const uint32_t __d1 = (__d / 100) << 1;528529std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c0, 2);530std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c1, 2);531std::memcpy(_Mid -= 2, __DIGIT_TABLE + __d0, 2);532std::memcpy(_Mid -= 2, __DIGIT_TABLE + __d1, 2);533}534uint32_t __output2 = static_cast<uint32_t>(_Output);535while (__output2 >= 10000) {536#ifdef __clang__ // TRANSITION, LLVM-38217537const uint32_t __c = __output2 - 10000 * (__output2 / 10000);538#else539const uint32_t __c = __output2 % 10000;540#endif541__output2 /= 10000;542const uint32_t __c0 = (__c % 100) << 1;543const uint32_t __c1 = (__c / 100) << 1;544std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c0, 2);545std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c1, 2);546}547if (__output2 >= 100) {548const uint32_t __c = (__output2 % 100) << 1;549__output2 /= 100;550std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c, 2);551}552if (__output2 >= 10) {553const uint32_t __c = __output2 << 1;554std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c, 2);555} else {556*--_Mid = static_cast<char>('0' + __output2);557}558559if (_Ryu_exponent > 0) { // case "172900" with _Can_use_ryu560// Performance note: it might be more efficient to do this immediately after setting _Mid.561std::memset(_First + __olength, '0', static_cast<size_t>(_Ryu_exponent));562} else if (_Ryu_exponent == 0) { // case "1729"563// Done!564} else if (_Whole_digits > 0) { // case "17.29"565// Performance note: moving digits might not be optimal.566std::memmove(_First, _First + 1, static_cast<size_t>(_Whole_digits));567_First[_Whole_digits] = '.';568} else { // case "0.001729"569// Performance note: a larger memset() followed by overwriting '.' might be more efficient.570_First[0] = '0';571_First[1] = '.';572std::memset(_First + 2, '0', static_cast<size_t>(-_Whole_digits));573}574575return { _First + _Total_fixed_length, errc{} };576}577578const uint32_t _Total_scientific_length = __olength + (__olength > 1) // digits + possible decimal point579+ (-100 < _Scientific_exponent && _Scientific_exponent < 100 ? 4 : 5); // + scientific exponent580if (_Last - _First < static_cast<ptrdiff_t>(_Total_scientific_length)) {581return { _Last, errc::value_too_large };582}583char* const __result = _First;584585// Print the decimal digits.586uint32_t __i = 0;587// We prefer 32-bit operations, even on 64-bit platforms.588// We have at most 17 digits, and uint32_t can store 9 digits.589// If _Output doesn't fit into uint32_t, we cut off 8 digits,590// so the rest will fit into uint32_t.591if ((_Output >> 32) != 0) {592// Expensive 64-bit division.593const uint64_t __q = __div1e8(_Output);594uint32_t __output2 = static_cast<uint32_t>(_Output) - 100000000 * static_cast<uint32_t>(__q);595_Output = __q;596597const uint32_t __c = __output2 % 10000;598__output2 /= 10000;599const uint32_t __d = __output2 % 10000;600const uint32_t __c0 = (__c % 100) << 1;601const uint32_t __c1 = (__c / 100) << 1;602const uint32_t __d0 = (__d % 100) << 1;603const uint32_t __d1 = (__d / 100) << 1;604std::memcpy(__result + __olength - __i - 1, __DIGIT_TABLE + __c0, 2);605std::memcpy(__result + __olength - __i - 3, __DIGIT_TABLE + __c1, 2);606std::memcpy(__result + __olength - __i - 5, __DIGIT_TABLE + __d0, 2);607std::memcpy(__result + __olength - __i - 7, __DIGIT_TABLE + __d1, 2);608__i += 8;609}610uint32_t __output2 = static_cast<uint32_t>(_Output);611while (__output2 >= 10000) {612#ifdef __clang__ // TRANSITION, LLVM-38217613const uint32_t __c = __output2 - 10000 * (__output2 / 10000);614#else615const uint32_t __c = __output2 % 10000;616#endif617__output2 /= 10000;618const uint32_t __c0 = (__c % 100) << 1;619const uint32_t __c1 = (__c / 100) << 1;620std::memcpy(__result + __olength - __i - 1, __DIGIT_TABLE + __c0, 2);621std::memcpy(__result + __olength - __i - 3, __DIGIT_TABLE + __c1, 2);622__i += 4;623}624if (__output2 >= 100) {625const uint32_t __c = (__output2 % 100) << 1;626__output2 /= 100;627std::memcpy(__result + __olength - __i - 1, __DIGIT_TABLE + __c, 2);628__i += 2;629}630if (__output2 >= 10) {631const uint32_t __c = __output2 << 1;632// We can't use memcpy here: the decimal dot goes between these two digits.633__result[2] = __DIGIT_TABLE[__c + 1];634__result[0] = __DIGIT_TABLE[__c];635} else {636__result[0] = static_cast<char>('0' + __output2);637}638639// Print decimal point if needed.640uint32_t __index;641if (__olength > 1) {642__result[1] = '.';643__index = __olength + 1;644} else {645__index = 1;646}647648// Print the exponent.649__result[__index++] = 'e';650if (_Scientific_exponent < 0) {651__result[__index++] = '-';652_Scientific_exponent = -_Scientific_exponent;653} else {654__result[__index++] = '+';655}656657if (_Scientific_exponent >= 100) {658const int32_t __c = _Scientific_exponent % 10;659std::memcpy(__result + __index, __DIGIT_TABLE + 2 * (_Scientific_exponent / 10), 2);660__result[__index + 2] = static_cast<char>('0' + __c);661__index += 3;662} else {663std::memcpy(__result + __index, __DIGIT_TABLE + 2 * _Scientific_exponent, 2);664__index += 2;665}666667return { _First + _Total_scientific_length, errc{} };668}669670[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline bool __d2d_small_int(const uint64_t __ieeeMantissa, const uint32_t __ieeeExponent,671__floating_decimal_64* const __v) {672const uint64_t __m2 = (1ull << __DOUBLE_MANTISSA_BITS) | __ieeeMantissa;673const int32_t __e2 = static_cast<int32_t>(__ieeeExponent) - __DOUBLE_BIAS - __DOUBLE_MANTISSA_BITS;674675if (__e2 > 0) {676// f = __m2 * 2^__e2 >= 2^53 is an integer.677// Ignore this case for now.678return false;679}680681if (__e2 < -52) {682// f < 1.683return false;684}685686// Since 2^52 <= __m2 < 2^53 and 0 <= -__e2 <= 52: 1 <= f = __m2 / 2^-__e2 < 2^53.687// Test if the lower -__e2 bits of the significand are 0, i.e. whether the fraction is 0.688const uint64_t __mask = (1ull << -__e2) - 1;689const uint64_t __fraction = __m2 & __mask;690if (__fraction != 0) {691return false;692}693694// f is an integer in the range [1, 2^53).695// Note: __mantissa might contain trailing (decimal) 0's.696// Note: since 2^53 < 10^16, there is no need to adjust __decimalLength17().697__v->__mantissa = __m2 >> -__e2;698__v->__exponent = 0;699return true;700}701702[[nodiscard]] to_chars_result __d2s_buffered_n(char* const _First, char* const _Last, const double __f,703const chars_format _Fmt) {704705// Step 1: Decode the floating-point number, and unify normalized and subnormal cases.706const uint64_t __bits = __double_to_bits(__f);707708// Case distinction; exit early for the easy cases.709if (__bits == 0) {710if (_Fmt == chars_format::scientific) {711if (_Last - _First < 5) {712return { _Last, errc::value_too_large };713}714715std::memcpy(_First, "0e+00", 5);716717return { _First + 5, errc{} };718}719720// Print "0" for chars_format::fixed, chars_format::general, and chars_format{}.721if (_First == _Last) {722return { _Last, errc::value_too_large };723}724725*_First = '0';726727return { _First + 1, errc{} };728}729730// Decode __bits into mantissa and exponent.731const uint64_t __ieeeMantissa = __bits & ((1ull << __DOUBLE_MANTISSA_BITS) - 1);732const uint32_t __ieeeExponent = static_cast<uint32_t>(__bits >> __DOUBLE_MANTISSA_BITS);733734if (_Fmt == chars_format::fixed) {735// const uint64_t _Mantissa2 = __ieeeMantissa | (1ull << __DOUBLE_MANTISSA_BITS); // restore implicit bit736const int32_t _Exponent2 = static_cast<int32_t>(__ieeeExponent)737- __DOUBLE_BIAS - __DOUBLE_MANTISSA_BITS; // bias and normalization738739// Normal values are equal to _Mantissa2 * 2^_Exponent2.740// (Subnormals are different, but they'll be rejected by the _Exponent2 test here, so they can be ignored.)741742// For nonzero integers, _Exponent2 >= -52. (The minimum value occurs when _Mantissa2 * 2^_Exponent2 is 1.743// In that case, _Mantissa2 is the implicit 1 bit followed by 52 zeros, so _Exponent2 is -52 to shift away744// the zeros.) The dense range of exactly representable integers has negative or zero exponents745// (as positive exponents make the range non-dense). For that dense range, Ryu will always be used:746// every digit is necessary to uniquely identify the value, so Ryu must print them all.747748// Positive exponents are the non-dense range of exactly representable integers. This contains all of the values749// for which Ryu can't be used (and a few Ryu-friendly values). We can save time by detecting positive750// exponents here and skipping Ryu. Calling __d2fixed_buffered_n() with precision 0 is valid for all integers751// (so it's okay if we call it with a Ryu-friendly value).752if (_Exponent2 > 0) {753return __d2fixed_buffered_n(_First, _Last, __f, 0);754}755}756757__floating_decimal_64 __v;758const bool __isSmallInt = __d2d_small_int(__ieeeMantissa, __ieeeExponent, &__v);759if (__isSmallInt) {760// For small integers in the range [1, 2^53), __v.__mantissa might contain trailing (decimal) zeros.761// For scientific notation we need to move these zeros into the exponent.762// (This is not needed for fixed-point notation, so it might be beneficial to trim763// trailing zeros in __to_chars only if needed - once fixed-point notation output is implemented.)764for (;;) {765const uint64_t __q = __div10(__v.__mantissa);766const uint32_t __r = static_cast<uint32_t>(__v.__mantissa) - 10 * static_cast<uint32_t>(__q);767if (__r != 0) {768break;769}770__v.__mantissa = __q;771++__v.__exponent;772}773} else {774__v = __d2d(__ieeeMantissa, __ieeeExponent);775}776777return __to_chars(_First, _Last, __v, _Fmt, __f);778}779780_LIBCPP_END_NAMESPACE_STD781782// clang-format on783784785