Path: blob/main/system/lib/libcxx/src/ryu/f2s.cpp
6175 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>44#include <cstdint>45#include <cstddef>4647#include "include/ryu/common.h"48#include "include/ryu/d2fixed.h"49#include "include/ryu/d2s_intrinsics.h"50#include "include/ryu/digit_table.h"51#include "include/ryu/f2s.h"52#include "include/ryu/ryu.h"5354_LIBCPP_BEGIN_NAMESPACE_STD5556inline constexpr int __FLOAT_MANTISSA_BITS = 23;57inline constexpr int __FLOAT_EXPONENT_BITS = 8;58inline constexpr int __FLOAT_BIAS = 127;5960inline constexpr int __FLOAT_POW5_INV_BITCOUNT = 59;61inline constexpr uint64_t __FLOAT_POW5_INV_SPLIT[31] = {62576460752303423489u, 461168601842738791u, 368934881474191033u, 295147905179352826u,63472236648286964522u, 377789318629571618u, 302231454903657294u, 483570327845851670u,64386856262276681336u, 309485009821345069u, 495176015714152110u, 396140812571321688u,65316912650057057351u, 507060240091291761u, 405648192073033409u, 324518553658426727u,66519229685853482763u, 415383748682786211u, 332306998946228969u, 531691198313966350u,67425352958651173080u, 340282366920938464u, 544451787073501542u, 435561429658801234u,68348449143727040987u, 557518629963265579u, 446014903970612463u, 356811923176489971u,69570899077082383953u, 456719261665907162u, 365375409332725730u70};71inline constexpr int __FLOAT_POW5_BITCOUNT = 61;72inline constexpr uint64_t __FLOAT_POW5_SPLIT[47] = {731152921504606846976u, 1441151880758558720u, 1801439850948198400u, 2251799813685248000u,741407374883553280000u, 1759218604441600000u, 2199023255552000000u, 1374389534720000000u,751717986918400000000u, 2147483648000000000u, 1342177280000000000u, 1677721600000000000u,762097152000000000000u, 1310720000000000000u, 1638400000000000000u, 2048000000000000000u,771280000000000000000u, 1600000000000000000u, 2000000000000000000u, 1250000000000000000u,781562500000000000000u, 1953125000000000000u, 1220703125000000000u, 1525878906250000000u,791907348632812500000u, 1192092895507812500u, 1490116119384765625u, 1862645149230957031u,801164153218269348144u, 1455191522836685180u, 1818989403545856475u, 2273736754432320594u,811421085471520200371u, 1776356839400250464u, 2220446049250313080u, 1387778780781445675u,821734723475976807094u, 2168404344971008868u, 1355252715606880542u, 1694065894508600678u,832117582368135750847u, 1323488980084844279u, 1654361225106055349u, 2067951531382569187u,841292469707114105741u, 1615587133892632177u, 2019483917365790221u85};8687[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline uint32_t __pow5Factor(uint32_t __value) {88uint32_t __count = 0;89for (;;) {90_LIBCPP_ASSERT_INTERNAL(__value != 0, "");91const uint32_t __q = __value / 5;92const uint32_t __r = __value % 5;93if (__r != 0) {94break;95}96__value = __q;97++__count;98}99return __count;100}101102// Returns true if __value is divisible by 5^__p.103[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline bool __multipleOfPowerOf5(const uint32_t __value, const uint32_t __p) {104return __pow5Factor(__value) >= __p;105}106107// Returns true if __value is divisible by 2^__p.108[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline bool __multipleOfPowerOf2(const uint32_t __value, const uint32_t __p) {109_LIBCPP_ASSERT_INTERNAL(__value != 0, "");110_LIBCPP_ASSERT_INTERNAL(__p < 32, "");111// __builtin_ctz doesn't appear to be faster here.112return (__value & ((1u << __p) - 1)) == 0;113}114115[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline uint32_t __mulShift(const uint32_t __m, const uint64_t __factor, const int32_t __shift) {116_LIBCPP_ASSERT_INTERNAL(__shift > 32, "");117118// The casts here help MSVC to avoid calls to the __allmul library119// function.120const uint32_t __factorLo = static_cast<uint32_t>(__factor);121const uint32_t __factorHi = static_cast<uint32_t>(__factor >> 32);122const uint64_t __bits0 = static_cast<uint64_t>(__m) * __factorLo;123const uint64_t __bits1 = static_cast<uint64_t>(__m) * __factorHi;124125#ifndef _LIBCPP_64_BIT126// On 32-bit platforms we can avoid a 64-bit shift-right since we only127// need the upper 32 bits of the result and the shift value is > 32.128const uint32_t __bits0Hi = static_cast<uint32_t>(__bits0 >> 32);129uint32_t __bits1Lo = static_cast<uint32_t>(__bits1);130uint32_t __bits1Hi = static_cast<uint32_t>(__bits1 >> 32);131__bits1Lo += __bits0Hi;132__bits1Hi += (__bits1Lo < __bits0Hi);133const int32_t __s = __shift - 32;134return (__bits1Hi << (32 - __s)) | (__bits1Lo >> __s);135#else // ^^^ 32-bit ^^^ / vvv 64-bit vvv136const uint64_t __sum = (__bits0 >> 32) + __bits1;137const uint64_t __shiftedSum = __sum >> (__shift - 32);138_LIBCPP_ASSERT_INTERNAL(__shiftedSum <= UINT32_MAX, "");139return static_cast<uint32_t>(__shiftedSum);140#endif // ^^^ 64-bit ^^^141}142143[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline uint32_t __mulPow5InvDivPow2(const uint32_t __m, const uint32_t __q, const int32_t __j) {144return __mulShift(__m, __FLOAT_POW5_INV_SPLIT[__q], __j);145}146147[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline uint32_t __mulPow5divPow2(const uint32_t __m, const uint32_t __i, const int32_t __j) {148return __mulShift(__m, __FLOAT_POW5_SPLIT[__i], __j);149}150151// A floating decimal representing m * 10^e.152struct __floating_decimal_32 {153uint32_t __mantissa;154int32_t __exponent;155};156157[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline __floating_decimal_32 __f2d(const uint32_t __ieeeMantissa, const uint32_t __ieeeExponent) {158int32_t __e2;159uint32_t __m2;160if (__ieeeExponent == 0) {161// We subtract 2 so that the bounds computation has 2 additional bits.162__e2 = 1 - __FLOAT_BIAS - __FLOAT_MANTISSA_BITS - 2;163__m2 = __ieeeMantissa;164} else {165__e2 = static_cast<int32_t>(__ieeeExponent) - __FLOAT_BIAS - __FLOAT_MANTISSA_BITS - 2;166__m2 = (1u << __FLOAT_MANTISSA_BITS) | __ieeeMantissa;167}168const bool __even = (__m2 & 1) == 0;169const bool __acceptBounds = __even;170171// Step 2: Determine the interval of valid decimal representations.172const uint32_t __mv = 4 * __m2;173const uint32_t __mp = 4 * __m2 + 2;174// Implicit bool -> int conversion. True is 1, false is 0.175const uint32_t __mmShift = __ieeeMantissa != 0 || __ieeeExponent <= 1;176const uint32_t __mm = 4 * __m2 - 1 - __mmShift;177178// Step 3: Convert to a decimal power base using 64-bit arithmetic.179uint32_t __vr, __vp, __vm;180int32_t __e10;181bool __vmIsTrailingZeros = false;182bool __vrIsTrailingZeros = false;183uint8_t __lastRemovedDigit = 0;184if (__e2 >= 0) {185const uint32_t __q = __log10Pow2(__e2);186__e10 = static_cast<int32_t>(__q);187const int32_t __k = __FLOAT_POW5_INV_BITCOUNT + __pow5bits(static_cast<int32_t>(__q)) - 1;188const int32_t __i = -__e2 + static_cast<int32_t>(__q) + __k;189__vr = __mulPow5InvDivPow2(__mv, __q, __i);190__vp = __mulPow5InvDivPow2(__mp, __q, __i);191__vm = __mulPow5InvDivPow2(__mm, __q, __i);192if (__q != 0 && (__vp - 1) / 10 <= __vm / 10) {193// We need to know one removed digit even if we are not going to loop below. We could use194// __q = X - 1 above, except that would require 33 bits for the result, and we've found that195// 32-bit arithmetic is faster even on 64-bit machines.196const int32_t __l = __FLOAT_POW5_INV_BITCOUNT + __pow5bits(static_cast<int32_t>(__q - 1)) - 1;197__lastRemovedDigit = static_cast<uint8_t>(__mulPow5InvDivPow2(__mv, __q - 1,198-__e2 + static_cast<int32_t>(__q) - 1 + __l) % 10);199}200if (__q <= 9) {201// The largest power of 5 that fits in 24 bits is 5^10, but __q <= 9 seems to be safe as well.202// Only one of __mp, __mv, and __mm can be a multiple of 5, if any.203if (__mv % 5 == 0) {204__vrIsTrailingZeros = __multipleOfPowerOf5(__mv, __q);205} else if (__acceptBounds) {206__vmIsTrailingZeros = __multipleOfPowerOf5(__mm, __q);207} else {208__vp -= __multipleOfPowerOf5(__mp, __q);209}210}211} else {212const uint32_t __q = __log10Pow5(-__e2);213__e10 = static_cast<int32_t>(__q) + __e2;214const int32_t __i = -__e2 - static_cast<int32_t>(__q);215const int32_t __k = __pow5bits(__i) - __FLOAT_POW5_BITCOUNT;216int32_t __j = static_cast<int32_t>(__q) - __k;217__vr = __mulPow5divPow2(__mv, static_cast<uint32_t>(__i), __j);218__vp = __mulPow5divPow2(__mp, static_cast<uint32_t>(__i), __j);219__vm = __mulPow5divPow2(__mm, static_cast<uint32_t>(__i), __j);220if (__q != 0 && (__vp - 1) / 10 <= __vm / 10) {221__j = static_cast<int32_t>(__q) - 1 - (__pow5bits(__i + 1) - __FLOAT_POW5_BITCOUNT);222__lastRemovedDigit = static_cast<uint8_t>(__mulPow5divPow2(__mv, static_cast<uint32_t>(__i + 1), __j) % 10);223}224if (__q <= 1) {225// {__vr,__vp,__vm} is trailing zeros if {__mv,__mp,__mm} has at least __q trailing 0 bits.226// __mv = 4 * __m2, so it always has at least two trailing 0 bits.227__vrIsTrailingZeros = true;228if (__acceptBounds) {229// __mm = __mv - 1 - __mmShift, so it has 1 trailing 0 bit iff __mmShift == 1.230__vmIsTrailingZeros = __mmShift == 1;231} else {232// __mp = __mv + 2, so it always has at least one trailing 0 bit.233--__vp;234}235} else if (__q < 31) { // TRANSITION(ulfjack): Use a tighter bound here.236__vrIsTrailingZeros = __multipleOfPowerOf2(__mv, __q - 1);237}238}239240// Step 4: Find the shortest decimal representation in the interval of valid representations.241int32_t __removed = 0;242uint32_t _Output;243if (__vmIsTrailingZeros || __vrIsTrailingZeros) {244// General case, which happens rarely (~4.0%).245while (__vp / 10 > __vm / 10) {246#ifdef __clang__ // TRANSITION, LLVM-23106247__vmIsTrailingZeros &= __vm - (__vm / 10) * 10 == 0;248#else249__vmIsTrailingZeros &= __vm % 10 == 0;250#endif251__vrIsTrailingZeros &= __lastRemovedDigit == 0;252__lastRemovedDigit = static_cast<uint8_t>(__vr % 10);253__vr /= 10;254__vp /= 10;255__vm /= 10;256++__removed;257}258if (__vmIsTrailingZeros) {259while (__vm % 10 == 0) {260__vrIsTrailingZeros &= __lastRemovedDigit == 0;261__lastRemovedDigit = static_cast<uint8_t>(__vr % 10);262__vr /= 10;263__vp /= 10;264__vm /= 10;265++__removed;266}267}268if (__vrIsTrailingZeros && __lastRemovedDigit == 5 && __vr % 2 == 0) {269// Round even if the exact number is .....50..0.270__lastRemovedDigit = 4;271}272// We need to take __vr + 1 if __vr is outside bounds or we need to round up.273_Output = __vr + ((__vr == __vm && (!__acceptBounds || !__vmIsTrailingZeros)) || __lastRemovedDigit >= 5);274} else {275// Specialized for the common case (~96.0%). Percentages below are relative to this.276// Loop iterations below (approximately):277// 0: 13.6%, 1: 70.7%, 2: 14.1%, 3: 1.39%, 4: 0.14%, 5+: 0.01%278while (__vp / 10 > __vm / 10) {279__lastRemovedDigit = static_cast<uint8_t>(__vr % 10);280__vr /= 10;281__vp /= 10;282__vm /= 10;283++__removed;284}285// We need to take __vr + 1 if __vr is outside bounds or we need to round up.286_Output = __vr + (__vr == __vm || __lastRemovedDigit >= 5);287}288const int32_t __exp = __e10 + __removed;289290__floating_decimal_32 __fd;291__fd.__exponent = __exp;292__fd.__mantissa = _Output;293return __fd;294}295296[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline to_chars_result _Large_integer_to_chars(char* const _First, char* const _Last,297const uint32_t _Mantissa2, const int32_t _Exponent2) {298299// Print the integer _Mantissa2 * 2^_Exponent2 exactly.300301// For nonzero integers, _Exponent2 >= -23. (The minimum value occurs when _Mantissa2 * 2^_Exponent2 is 1.302// In that case, _Mantissa2 is the implicit 1 bit followed by 23 zeros, so _Exponent2 is -23 to shift away303// the zeros.) The dense range of exactly representable integers has negative or zero exponents304// (as positive exponents make the range non-dense). For that dense range, Ryu will always be used:305// every digit is necessary to uniquely identify the value, so Ryu must print them all.306307// Positive exponents are the non-dense range of exactly representable integers.308// This contains all of the values for which Ryu can't be used (and a few Ryu-friendly values).309310// Performance note: Long division appears to be faster than losslessly widening float to double and calling311// __d2fixed_buffered_n(). If __f2fixed_buffered_n() is implemented, it might be faster than long division.312313_LIBCPP_ASSERT_INTERNAL(_Exponent2 > 0, "");314_LIBCPP_ASSERT_INTERNAL(_Exponent2 <= 104, ""); // because __ieeeExponent <= 254315316// Manually represent _Mantissa2 * 2^_Exponent2 as a large integer. _Mantissa2 is always 24 bits317// (due to the implicit bit), while _Exponent2 indicates a shift of at most 104 bits.318// 24 + 104 equals 128 equals 4 * 32, so we need exactly 4 32-bit elements.319// We use a little-endian representation, visualized like this:320321// << left shift <<322// most significant323// _Data[3] _Data[2] _Data[1] _Data[0]324// least significant325// >> right shift >>326327constexpr uint32_t _Data_size = 4;328uint32_t _Data[_Data_size]{};329330// _Maxidx is the index of the most significant nonzero element.331uint32_t _Maxidx = ((24 + static_cast<uint32_t>(_Exponent2) + 31) / 32) - 1;332_LIBCPP_ASSERT_INTERNAL(_Maxidx < _Data_size, "");333334const uint32_t _Bit_shift = static_cast<uint32_t>(_Exponent2) % 32;335if (_Bit_shift <= 8) { // _Mantissa2's 24 bits don't cross an element boundary336_Data[_Maxidx] = _Mantissa2 << _Bit_shift;337} else { // _Mantissa2's 24 bits cross an element boundary338_Data[_Maxidx - 1] = _Mantissa2 << _Bit_shift;339_Data[_Maxidx] = _Mantissa2 >> (32 - _Bit_shift);340}341342// If Ryu hasn't determined the total output length, we need to buffer the digits generated from right to left343// by long division. The largest possible float is: 340'282346638'528859811'704183484'516925440344uint32_t _Blocks[4];345int32_t _Filled_blocks = 0;346// From left to right, we're going to print:347// _Data[0] will be [1, 10] digits.348// Then if _Filled_blocks > 0:349// _Blocks[_Filled_blocks - 1], ..., _Blocks[0] will be 0-filled 9-digit blocks.350351if (_Maxidx != 0) { // If the integer is actually large, perform long division.352// Otherwise, skip to printing _Data[0].353for (;;) {354// Loop invariant: _Maxidx != 0 (i.e. the integer is actually large)355356const uint32_t _Most_significant_elem = _Data[_Maxidx];357const uint32_t _Initial_remainder = _Most_significant_elem % 1000000000;358const uint32_t _Initial_quotient = _Most_significant_elem / 1000000000;359_Data[_Maxidx] = _Initial_quotient;360uint64_t _Remainder = _Initial_remainder;361362// Process less significant elements.363uint32_t _Idx = _Maxidx;364do {365--_Idx; // Initially, _Remainder is at most 10^9 - 1.366367// Now, _Remainder is at most (10^9 - 1) * 2^32 + 2^32 - 1, simplified to 10^9 * 2^32 - 1.368_Remainder = (_Remainder << 32) | _Data[_Idx];369370// floor((10^9 * 2^32 - 1) / 10^9) == 2^32 - 1, so uint32_t _Quotient is lossless.371const uint32_t _Quotient = static_cast<uint32_t>(__div1e9(_Remainder));372373// _Remainder is at most 10^9 - 1 again.374// For uint32_t truncation, see the __mod1e9() comment in d2s_intrinsics.h.375_Remainder = static_cast<uint32_t>(_Remainder) - 1000000000u * _Quotient;376377_Data[_Idx] = _Quotient;378} while (_Idx != 0);379380// Store a 0-filled 9-digit block.381_Blocks[_Filled_blocks++] = static_cast<uint32_t>(_Remainder);382383if (_Initial_quotient == 0) { // Is the large integer shrinking?384--_Maxidx; // log2(10^9) is 29.9, so we can't shrink by more than one element.385if (_Maxidx == 0) {386break; // We've finished long division. Now we need to print _Data[0].387}388}389}390}391392_LIBCPP_ASSERT_INTERNAL(_Data[0] != 0, "");393for (uint32_t _Idx = 1; _Idx < _Data_size; ++_Idx) {394_LIBCPP_ASSERT_INTERNAL(_Data[_Idx] == 0, "");395}396397const uint32_t _Data_olength = _Data[0] >= 1000000000 ? 10 : __decimalLength9(_Data[0]);398const uint32_t _Total_fixed_length = _Data_olength + 9 * _Filled_blocks;399400if (_Last - _First < static_cast<ptrdiff_t>(_Total_fixed_length)) {401return { _Last, errc::value_too_large };402}403404char* _Result = _First;405406// Print _Data[0]. While it's up to 10 digits,407// which is more than Ryu generates, the code below can handle this.408__append_n_digits(_Data_olength, _Data[0], _Result);409_Result += _Data_olength;410411// Print 0-filled 9-digit blocks.412for (int32_t _Idx = _Filled_blocks - 1; _Idx >= 0; --_Idx) {413__append_nine_digits(_Blocks[_Idx], _Result);414_Result += 9;415}416417return { _Result, errc{} };418}419420[[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline to_chars_result __to_chars(char* const _First, char* const _Last, const __floating_decimal_32 __v,421chars_format _Fmt, const uint32_t __ieeeMantissa, const uint32_t __ieeeExponent) {422// Step 5: Print the decimal representation.423uint32_t _Output = __v.__mantissa;424int32_t _Ryu_exponent = __v.__exponent;425const uint32_t __olength = __decimalLength9(_Output);426int32_t _Scientific_exponent = _Ryu_exponent + static_cast<int32_t>(__olength) - 1;427428if (_Fmt == chars_format{}) {429int32_t _Lower;430int32_t _Upper;431432if (__olength == 1) {433// Value | Fixed | Scientific434// 1e-3 | "0.001" | "1e-03"435// 1e4 | "10000" | "1e+04"436_Lower = -3;437_Upper = 4;438} else {439// Value | Fixed | Scientific440// 1234e-7 | "0.0001234" | "1.234e-04"441// 1234e5 | "123400000" | "1.234e+08"442_Lower = -static_cast<int32_t>(__olength + 3);443_Upper = 5;444}445446if (_Lower <= _Ryu_exponent && _Ryu_exponent <= _Upper) {447_Fmt = chars_format::fixed;448} else {449_Fmt = chars_format::scientific;450}451} else if (_Fmt == chars_format::general) {452// C11 7.21.6.1 "The fprintf function"/8:453// "Let P equal [...] 6 if the precision is omitted [...].454// Then, if a conversion with style E would have an exponent of X:455// - if P > X >= -4, the conversion is with style f [...].456// - otherwise, the conversion is with style e [...]."457if (-4 <= _Scientific_exponent && _Scientific_exponent < 6) {458_Fmt = chars_format::fixed;459} else {460_Fmt = chars_format::scientific;461}462}463464if (_Fmt == chars_format::fixed) {465// Example: _Output == 1729, __olength == 4466467// _Ryu_exponent | Printed | _Whole_digits | _Total_fixed_length | Notes468// --------------|----------|---------------|----------------------|---------------------------------------469// 2 | 172900 | 6 | _Whole_digits | Ryu can't be used for printing470// 1 | 17290 | 5 | (sometimes adjusted) | when the trimmed digits are nonzero.471// --------------|----------|---------------|----------------------|---------------------------------------472// 0 | 1729 | 4 | _Whole_digits | Unified length cases.473// --------------|----------|---------------|----------------------|---------------------------------------474// -1 | 172.9 | 3 | __olength + 1 | This case can't happen for475// -2 | 17.29 | 2 | | __olength == 1, but no additional476// -3 | 1.729 | 1 | | code is needed to avoid it.477// --------------|----------|---------------|----------------------|---------------------------------------478// -4 | 0.1729 | 0 | 2 - _Ryu_exponent | C11 7.21.6.1 "The fprintf function"/8:479// -5 | 0.01729 | -1 | | "If a decimal-point character appears,480// -6 | 0.001729 | -2 | | at least one digit appears before it."481482const int32_t _Whole_digits = static_cast<int32_t>(__olength) + _Ryu_exponent;483484uint32_t _Total_fixed_length;485if (_Ryu_exponent >= 0) { // cases "172900" and "1729"486_Total_fixed_length = static_cast<uint32_t>(_Whole_digits);487if (_Output == 1) {488// Rounding can affect the number of digits.489// For example, 1e11f is exactly "99999997952" which is 11 digits instead of 12.490// We can use a lookup table to detect this and adjust the total length.491static constexpr uint8_t _Adjustment[39] = {4920,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,1,1,1,0,0,1,1,0,1,0,1,1,0,0,1,0,1,1,0,1,1,1 };493_Total_fixed_length -= _Adjustment[_Ryu_exponent];494// _Whole_digits doesn't need to be adjusted because these cases won't refer to it later.495}496} else if (_Whole_digits > 0) { // case "17.29"497_Total_fixed_length = __olength + 1;498} else { // case "0.001729"499_Total_fixed_length = static_cast<uint32_t>(2 - _Ryu_exponent);500}501502if (_Last - _First < static_cast<ptrdiff_t>(_Total_fixed_length)) {503return { _Last, errc::value_too_large };504}505506char* _Mid;507if (_Ryu_exponent > 0) { // case "172900"508bool _Can_use_ryu;509510if (_Ryu_exponent > 10) { // 10^10 is the largest power of 10 that's exactly representable as a float.511_Can_use_ryu = false;512} else {513// Ryu generated X: __v.__mantissa * 10^_Ryu_exponent514// __v.__mantissa == 2^_Trailing_zero_bits * (__v.__mantissa >> _Trailing_zero_bits)515// 10^_Ryu_exponent == 2^_Ryu_exponent * 5^_Ryu_exponent516517// _Trailing_zero_bits is [0, 29] (aside: because 2^29 is the largest power of 2518// with 9 decimal digits, which is float's round-trip limit.)519// _Ryu_exponent is [1, 10].520// Normalization adds [2, 23] (aside: at least 2 because the pre-normalized mantissa is at least 5).521// This adds up to [3, 62], which is well below float's maximum binary exponent 127.522523// Therefore, we just need to consider (__v.__mantissa >> _Trailing_zero_bits) * 5^_Ryu_exponent.524525// If that product would exceed 24 bits, then X can't be exactly represented as a float.526// (That's not a problem for round-tripping, because X is close enough to the original float,527// but X isn't mathematically equal to the original float.) This requires a high-precision fallback.528529// If the product is 24 bits or smaller, then X can be exactly represented as a float (and we don't530// need to re-synthesize it; the original float must have been X, because Ryu wouldn't produce the531// same output for two different floats X and Y). This allows Ryu's output to be used (zero-filled).532533// (2^24 - 1) / 5^0 (for indexing), (2^24 - 1) / 5^1, ..., (2^24 - 1) / 5^10534static constexpr uint32_t _Max_shifted_mantissa[11] = {53516777215, 3355443, 671088, 134217, 26843, 5368, 1073, 214, 42, 8, 1 };536537unsigned long _Trailing_zero_bits;538(void) _BitScanForward(&_Trailing_zero_bits, __v.__mantissa); // __v.__mantissa is guaranteed nonzero539const uint32_t _Shifted_mantissa = __v.__mantissa >> _Trailing_zero_bits;540_Can_use_ryu = _Shifted_mantissa <= _Max_shifted_mantissa[_Ryu_exponent];541}542543if (!_Can_use_ryu) {544const uint32_t _Mantissa2 = __ieeeMantissa | (1u << __FLOAT_MANTISSA_BITS); // restore implicit bit545const int32_t _Exponent2 = static_cast<int32_t>(__ieeeExponent)546- __FLOAT_BIAS - __FLOAT_MANTISSA_BITS; // bias and normalization547548// Performance note: We've already called Ryu, so this will redundantly perform buffering and bounds checking.549return _Large_integer_to_chars(_First, _Last, _Mantissa2, _Exponent2);550}551552// _Can_use_ryu553// Print the decimal digits, left-aligned within [_First, _First + _Total_fixed_length).554_Mid = _First + __olength;555} else { // cases "1729", "17.29", and "0.001729"556// Print the decimal digits, right-aligned within [_First, _First + _Total_fixed_length).557_Mid = _First + _Total_fixed_length;558}559560while (_Output >= 10000) {561#ifdef __clang__ // TRANSITION, LLVM-38217562const uint32_t __c = _Output - 10000 * (_Output / 10000);563#else564const uint32_t __c = _Output % 10000;565#endif566_Output /= 10000;567const uint32_t __c0 = (__c % 100) << 1;568const uint32_t __c1 = (__c / 100) << 1;569std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c0, 2);570std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c1, 2);571}572if (_Output >= 100) {573const uint32_t __c = (_Output % 100) << 1;574_Output /= 100;575std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c, 2);576}577if (_Output >= 10) {578const uint32_t __c = _Output << 1;579std::memcpy(_Mid -= 2, __DIGIT_TABLE + __c, 2);580} else {581*--_Mid = static_cast<char>('0' + _Output);582}583584if (_Ryu_exponent > 0) { // case "172900" with _Can_use_ryu585// Performance note: it might be more efficient to do this immediately after setting _Mid.586std::memset(_First + __olength, '0', static_cast<size_t>(_Ryu_exponent));587} else if (_Ryu_exponent == 0) { // case "1729"588// Done!589} else if (_Whole_digits > 0) { // case "17.29"590// Performance note: moving digits might not be optimal.591std::memmove(_First, _First + 1, static_cast<size_t>(_Whole_digits));592_First[_Whole_digits] = '.';593} else { // case "0.001729"594// Performance note: a larger memset() followed by overwriting '.' might be more efficient.595_First[0] = '0';596_First[1] = '.';597std::memset(_First + 2, '0', static_cast<size_t>(-_Whole_digits));598}599600return { _First + _Total_fixed_length, errc{} };601}602603const uint32_t _Total_scientific_length =604__olength + (__olength > 1) + 4; // digits + possible decimal point + scientific exponent605if (_Last - _First < static_cast<ptrdiff_t>(_Total_scientific_length)) {606return { _Last, errc::value_too_large };607}608char* const __result = _First;609610// Print the decimal digits.611uint32_t __i = 0;612while (_Output >= 10000) {613#ifdef __clang__ // TRANSITION, LLVM-38217614const uint32_t __c = _Output - 10000 * (_Output / 10000);615#else616const uint32_t __c = _Output % 10000;617#endif618_Output /= 10000;619const uint32_t __c0 = (__c % 100) << 1;620const uint32_t __c1 = (__c / 100) << 1;621std::memcpy(__result + __olength - __i - 1, __DIGIT_TABLE + __c0, 2);622std::memcpy(__result + __olength - __i - 3, __DIGIT_TABLE + __c1, 2);623__i += 4;624}625if (_Output >= 100) {626const uint32_t __c = (_Output % 100) << 1;627_Output /= 100;628std::memcpy(__result + __olength - __i - 1, __DIGIT_TABLE + __c, 2);629__i += 2;630}631if (_Output >= 10) {632const uint32_t __c = _Output << 1;633// We can't use memcpy here: the decimal dot goes between these two digits.634__result[2] = __DIGIT_TABLE[__c + 1];635__result[0] = __DIGIT_TABLE[__c];636} else {637__result[0] = static_cast<char>('0' + _Output);638}639640// Print decimal point if needed.641uint32_t __index;642if (__olength > 1) {643__result[1] = '.';644__index = __olength + 1;645} else {646__index = 1;647}648649// Print the exponent.650__result[__index++] = 'e';651if (_Scientific_exponent < 0) {652__result[__index++] = '-';653_Scientific_exponent = -_Scientific_exponent;654} else {655__result[__index++] = '+';656}657658std::memcpy(__result + __index, __DIGIT_TABLE + 2 * _Scientific_exponent, 2);659__index += 2;660661return { _First + _Total_scientific_length, errc{} };662}663664[[nodiscard]] to_chars_result __f2s_buffered_n(char* const _First, char* const _Last, const float __f,665const chars_format _Fmt) {666667// Step 1: Decode the floating-point number, and unify normalized and subnormal cases.668const uint32_t __bits = __float_to_bits(__f);669670// Case distinction; exit early for the easy cases.671if (__bits == 0) {672if (_Fmt == chars_format::scientific) {673if (_Last - _First < 5) {674return { _Last, errc::value_too_large };675}676677std::memcpy(_First, "0e+00", 5);678679return { _First + 5, errc{} };680}681682// Print "0" for chars_format::fixed, chars_format::general, and chars_format{}.683if (_First == _Last) {684return { _Last, errc::value_too_large };685}686687*_First = '0';688689return { _First + 1, errc{} };690}691692// Decode __bits into mantissa and exponent.693const uint32_t __ieeeMantissa = __bits & ((1u << __FLOAT_MANTISSA_BITS) - 1);694const uint32_t __ieeeExponent = __bits >> __FLOAT_MANTISSA_BITS;695696// When _Fmt == chars_format::fixed and the floating-point number is a large integer,697// it's faster to skip Ryu and immediately print the integer exactly.698if (_Fmt == chars_format::fixed) {699const uint32_t _Mantissa2 = __ieeeMantissa | (1u << __FLOAT_MANTISSA_BITS); // restore implicit bit700const int32_t _Exponent2 = static_cast<int32_t>(__ieeeExponent)701- __FLOAT_BIAS - __FLOAT_MANTISSA_BITS; // bias and normalization702703// Normal values are equal to _Mantissa2 * 2^_Exponent2.704// (Subnormals are different, but they'll be rejected by the _Exponent2 test here, so they can be ignored.)705706if (_Exponent2 > 0) {707return _Large_integer_to_chars(_First, _Last, _Mantissa2, _Exponent2);708}709}710711const __floating_decimal_32 __v = __f2d(__ieeeMantissa, __ieeeExponent);712return __to_chars(_First, _Last, __v, _Fmt, __ieeeMantissa, __ieeeExponent);713}714715_LIBCPP_END_NAMESPACE_STD716717// clang-format on718719720