Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qlocale_tools.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2016 Intel Corporation.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4
7#include "qlocale_p.h"
8#include "qstring.h"
9
10#include <private/qtools_p.h>
11#include <private/qnumeric_p.h>
12
13#include <cstdio>
14
15#include <ctype.h>
16#include <errno.h>
17#include <float.h>
18#include <limits.h>
19#include <math.h>
20#include <stdlib.h>
21#include <time.h>
22
23#include <limits>
24#include <charconv>
25
26#if defined(Q_OS_LINUX) && !defined(__UCLIBC__)
27# include <fenv.h>
28#endif
29
30// Sizes as defined by the ISO C99 standard - fallback
31#ifndef LLONG_MAX
32# define LLONG_MAX Q_INT64_C(0x7fffffffffffffff)
33#endif
34#ifndef LLONG_MIN
35# define LLONG_MIN (-LLONG_MAX - Q_INT64_C(1))
36#endif
37#ifndef ULLONG_MAX
38# define ULLONG_MAX Q_UINT64_C(0xffffffffffffffff)
39#endif
40
41QT_BEGIN_NAMESPACE
42
43using namespace QtMiscUtils;
44
46
47void qt_doubleToAscii(double d, QLocaleData::DoubleForm form, int precision,
48 char *buf, qsizetype bufSize,
49 bool &sign, int &length, int &decpt)
50{
51 if (bufSize == 0) {
52 decpt = 0;
53 sign = d < 0;
54 length = 0;
55 return;
56 }
57
58 // Detect special numbers (nan, +/-inf)
59 // We cannot use the high-level API of libdouble-conversion as we need to
60 // apply locale-specific formatting, such as decimal points, grouping
61 // separators, etc. Because of this, we have to check for infinity and NaN
62 // before calling DoubleToAscii.
63 if (qt_is_inf(d)) {
64 sign = d < 0;
65 if (bufSize >= 3) {
66 buf[0] = 'i';
67 buf[1] = 'n';
68 buf[2] = 'f';
69 length = 3;
70 } else {
71 length = 0;
72 }
73 return;
74 } else if (qt_is_nan(d)) {
75 if (bufSize >= 3) {
76 buf[0] = 'n';
77 buf[1] = 'a';
78 buf[2] = 'n';
79 length = 3;
80 } else {
81 length = 0;
82 }
83 return;
84 }
85
86 if (form == QLocaleData::DFSignificantDigits && precision == 0)
87 precision = 1; // 0 significant digits is silently converted to 1
88
89#if !defined(QT_NO_DOUBLECONVERSION) && !defined(QT_BOOTSTRAPPED)
90 // one digit before the decimal dot, counts as significant digit for DoubleToStringConverter
91 if (form == QLocaleData::DFExponent && precision >= 0)
92 ++precision;
93
94 double_conversion::DoubleToStringConverter::DtoaMode mode;
95 if (precision == QLocale::FloatingPointShortest) {
96 mode = double_conversion::DoubleToStringConverter::SHORTEST;
97 } else if (form == QLocaleData::DFSignificantDigits || form == QLocaleData::DFExponent) {
98 mode = double_conversion::DoubleToStringConverter::PRECISION;
99 } else {
100 mode = double_conversion::DoubleToStringConverter::FIXED;
101 }
102 // libDoubleConversion is limited to 32-bit lengths. It's ok to cap the buffer size,
103 // though, because the library will never write 2GiB of chars as output
104 // (the length out-parameter is just an int, too).
105 const auto boundedBufferSize = static_cast<int>((std::min)(bufSize, qsizetype(INT_MAX)));
106 double_conversion::DoubleToStringConverter::DoubleToAscii(d, mode, precision, buf,
107 boundedBufferSize,
108 &sign, &length, &decpt);
109#else // QT_NO_DOUBLECONVERSION || QT_BOOTSTRAPPED
110
111 // Cut the precision at 999, to fit it into the format string. We can't get more than 17
112 // significant digits, so anything after that is mostly noise. You do get closer to the "middle"
113 // of the range covered by the given double with more digits, so to a degree it does make sense
114 // to honor higher precisions. We define that at more than 999 digits that is not the case.
115 if (precision > 999)
116 precision = 999;
117 else if (precision == QLocale::FloatingPointShortest)
118 precision = std::numeric_limits<double>::max_digits10; // snprintf lacks "shortest" mode
119
120 if (qIsNull(d)) {
121 // Negative zero is expected as simple "0", not "-0". We cannot do d < 0, though.
122 sign = false;
123 buf[0] = '0';
124 length = 1;
125 decpt = 1;
126 return;
127 } else if (d < 0) {
128 sign = true;
129 d = -d;
130 } else {
131 sign = false;
132 }
133
134 const int formatLength = 7; // '%', '.', 3 digits precision, 'f', '\0'
135 char format[formatLength];
136 format[formatLength - 1] = '\0';
137 format[0] = '%';
138 format[1] = '.';
139 format[2] = char((precision / 100) % 10) + '0';
140 format[3] = char((precision / 10) % 10) + '0';
141 format[4] = char(precision % 10) + '0';
142 int extraChars;
143 switch (form) {
144 case QLocaleData::DFDecimal:
145 format[formatLength - 2] = 'f';
146 // <anything> '.' <precision> '\0'
147 extraChars = wholePartSpace(d) + 2;
148 break;
149 case QLocaleData::DFExponent:
150 format[formatLength - 2] = 'e';
151 // '.', 'e', '-', <exponent> '\0'
152 extraChars = 7;
153 break;
154 case QLocaleData::DFSignificantDigits:
155 format[formatLength - 2] = 'g';
156
157 // either the same as in the 'e' case, or '.' and '\0'
158 // precision covers part before '.'
159 extraChars = 7;
160 break;
161 default:
162 Q_UNREACHABLE();
163 }
164
165 QVarLengthArray<char> target(precision + extraChars);
166
167 length = qDoubleSnprintf(target.data(), target.size(), QT_CLOCALE, format, d);
168 int firstSignificant = 0;
169 int decptInTarget = length;
170
171 // Find the first significant digit (not 0), and note any '.' we encounter.
172 // There is no '-' at the front of target because we made sure d > 0 above.
173 while (firstSignificant < length) {
174 if (target[firstSignificant] == '.')
175 decptInTarget = firstSignificant;
176 else if (target[firstSignificant] != '0')
177 break;
178 ++firstSignificant;
179 }
180
181 // If no '.' found so far, search the rest of the target buffer for it.
182 if (decptInTarget == length)
183 decptInTarget = std::find(target.data() + firstSignificant, target.data() + length, '.') -
184 target.data();
185
186 int eSign = length;
187 if (form != QLocaleData::DFDecimal) {
188 // In 'e' or 'g' form, look for the 'e'.
189 eSign = std::find(target.data() + firstSignificant, target.data() + length, 'e') -
190 target.data();
191
192 if (eSign < length) {
193 // If 'e' is found, the final decimal point is determined by the number after 'e'.
194 // Mind that the final decimal point, decpt, is the offset of the decimal point from the
195 // start of the resulting string in buf. It may be negative or larger than bufSize, in
196 // which case the missing digits are zeroes. In the 'e' case decptInTarget is always 1,
197 // as variants of snprintf always generate numbers with one digit before the '.' then.
198 // This is why the final decimal point is offset by 1, relative to the number after 'e'.
199 auto r = qstrntoll(target.data() + eSign + 1, length - eSign - 1, 10);
200 decpt = r.result + 1;
201 Q_ASSERT(r.ok());
202 Q_ASSERT(r.used + eSign + 1 <= length);
203 } else {
204 // No 'e' found, so it's the 'f' form. Variants of snprintf generate numbers with
205 // potentially multiple digits before the '.', but without decimal exponent then. So we
206 // get the final decimal point from the position of the '.'. The '.' itself takes up one
207 // character. We adjust by 1 below if that gets in the way.
208 decpt = decptInTarget - firstSignificant;
209 }
210 } else {
211 // In 'f' form, there can not be an 'e', so it's enough to look for the '.'
212 // (and possibly adjust by 1 below)
213 decpt = decptInTarget - firstSignificant;
214 }
215
216 // Move the actual digits from the snprintf target to the actual buffer.
217 if (decptInTarget > firstSignificant) {
218 // First move the digits before the '.', if any
219 int lengthBeforeDecpt = decptInTarget - firstSignificant;
220 memcpy(buf, target.data() + firstSignificant, qMin(lengthBeforeDecpt, bufSize));
221 if (eSign > decptInTarget && lengthBeforeDecpt < bufSize) {
222 // Then move any remaining digits, until 'e'
223 memcpy(buf + lengthBeforeDecpt, target.data() + decptInTarget + 1,
224 qMin(eSign - decptInTarget - 1, bufSize - lengthBeforeDecpt));
225 // The final length of the output is the distance between the first significant digit
226 // and 'e' minus 1, for the '.', except if the buffer is smaller.
227 length = qMin(eSign - firstSignificant - 1, bufSize);
228 } else {
229 // 'e' was before the decpt or things didn't fit. Don't subtract the '.' from the length.
230 length = qMin(eSign - firstSignificant, bufSize);
231 }
232 } else {
233 if (eSign > firstSignificant) {
234 // If there are any significant digits at all, they are all after the '.' now.
235 // Just copy them straight away.
236 memcpy(buf, target.data() + firstSignificant, qMin(eSign - firstSignificant, bufSize));
237
238 // The decimal point was before the first significant digit, so we were one off above.
239 // Consider 0.1 - buf will be just '1', and decpt should be 0. But
240 // "decptInTarget - firstSignificant" will yield -1.
241 ++decpt;
242 length = qMin(eSign - firstSignificant, bufSize);
243 } else {
244 // No significant digits means the number is just 0.
245 buf[0] = '0';
246 length = 1;
247 decpt = 1;
248 }
249 }
250#endif // QT_NO_DOUBLECONVERSION || QT_BOOTSTRAPPED
251 while (length > 1 && buf[length - 1] == '0') // drop trailing zeroes
252 --length;
253}
254
255QSimpleParsedNumber<double> qt_asciiToDouble(const char *num, qsizetype numLen,
256 StrayCharacterMode strayCharMode)
257{
258 if (numLen <= 0)
259 return {};
260
261 // We have to catch NaN before because we need NaN as marker for "garbage" in the
262 // libdouble-conversion case and, in contrast to libdouble-conversion or sscanf, we don't allow
263 // "-nan" or "+nan"
264 if (char c = *num; numLen >= 3
265 && (c == '-' || c == '+' || c == 'I' || c == 'i' || c == 'N' || c == 'n')) {
266 bool negative = (c == '-');
267 bool hasSign = negative || (c == '+');
268 qptrdiff offset = 0;
269 if (hasSign) {
270 offset = 1;
271 c = num[offset];
272 }
273
274 if (c > '9') {
275 auto lowered = [](char c) {
276 // this will mangle non-letters, but none can become a letter
277 return c | 0x20;
278 };
279
280 // Found a non-digit, so this MUST be either "inf", "+inf", "-inf"
281 // or "nan". Anything else is an invalid parse and we don't need to
282 // feed it to the converter below.
283 if (numLen != offset + 3)
284 return {};
285
286 c = lowered(c);
287 char c2 = lowered(num[offset + 1]);
288 char c3 = lowered(num[offset + 2]);
289 if (c == 'i' && c2 == 'n' && c3 == 'f')
290 return { negative ? -qt_inf() : qt_inf(), offset + 3 };
291 else if (c == 'n' && c2 == 'a' && c3 == 'n' && !hasSign)
292 return { qt_qnan(), 3 };
293 return {};
294 }
295 }
296
297 double d = 0.0;
298 int processed;
299#if !defined(QT_NO_DOUBLECONVERSION) && !defined(QT_BOOTSTRAPPED)
300 int conv_flags = double_conversion::StringToDoubleConverter::NO_FLAGS;
301 if (strayCharMode == TrailingJunkAllowed) {
302 conv_flags = double_conversion::StringToDoubleConverter::ALLOW_TRAILING_JUNK;
303 } else if (strayCharMode == WhitespacesAllowed) {
304 conv_flags = double_conversion::StringToDoubleConverter::ALLOW_LEADING_SPACES
305 | double_conversion::StringToDoubleConverter::ALLOW_TRAILING_SPACES;
306 }
307 double_conversion::StringToDoubleConverter conv(conv_flags, 0.0, qt_qnan(), nullptr, nullptr);
308 if (int(numLen) != numLen) {
309 // a number over 2 GB in length is silly, just assume it isn't valid
310 return {};
311 } else {
312 d = conv.StringToDouble(num, int(numLen), &processed);
313 }
314
315 if (!qt_is_finite(d)) {
316 if (qt_is_nan(d)) {
317 // Garbage found. We don't accept it and return 0.
318 return {};
319 } else {
320 // Overflow. That's not OK, but we still return infinity.
321 return { d, -processed };
322 }
323 }
324#else
325 // ::digits10 is 19, but ::max() is 18'446'744'073'709'551'615ULL - go, figure...
326 constexpr auto maxDigitsForULongLong = 1 + std::numeric_limits<unsigned long long>::digits10;
327 // need to ensure that we don't read more than numLen of input:
328 char fmt[1 + maxDigitsForULongLong + 4 + 1];
329 std::snprintf(fmt, sizeof fmt, "%s%llu%s",
330 "%", static_cast<unsigned long long>(numLen), "lf%n");
331
332 if (qDoubleSscanf(num, QT_CLOCALE, fmt, &d, &processed) < 1)
333 processed = 0;
334
335 if ((strayCharMode == TrailingJunkProhibited && processed != numLen) || qt_is_nan(d)) {
336 // Implementation defined nan symbol or garbage found. We don't accept it.
337 return {};
338 }
339
340 if (!qt_is_finite(d)) {
341 // Overflow. Check for implementation-defined infinity symbols and reject them.
342 // We assume that any infinity symbol has to contain a character that cannot be part of a
343 // "normal" number (that is 0-9, ., -, +, e).
344 for (int i = 0; i < processed; ++i) {
345 char c = num[i];
346 if ((c < '0' || c > '9') && c != '.' && c != '-' && c != '+' && c != 'e' && c != 'E') {
347 // Garbage found
348 return {};
349 }
350 }
351 return { d, -processed };
352 }
353#endif // !defined(QT_NO_DOUBLECONVERSION) && !defined(QT_BOOTSTRAPPED)
354
355 // Otherwise we would have gotten NaN or sorted it out above.
356 Q_ASSERT(strayCharMode == TrailingJunkAllowed || processed == numLen);
357
358 // Check if underflow has occurred.
359 if (qIsNull(d)) {
360 for (int i = 0; i < processed; ++i) {
361 if (num[i] >= '1' && num[i] <= '9') {
362 // if a digit before any 'e' is not 0, then a non-zero number was intended.
363 return {d, -processed};
364 } else if (num[i] == 'e' || num[i] == 'E') {
365 break;
366 }
367 }
368 }
369 return { d, processed };
370}
371
372/* Detect base if 0 and, if base is hex or bin, skip over 0x/0b prefixes */
373static auto scanPrefix(const char *p, const char *stop, int base)
374{
375 struct R
376 {
377 const char *next;
378 int base;
379 };
380 if (p < stop && isAsciiDigit(*p)) {
381 if (*p == '0') {
382 const char *x_or_b = p + 1;
383 if (x_or_b < stop) {
384 switch (*x_or_b) {
385 case 'b':
386 case 'B':
387 if (base == 0)
388 base = 2;
389 if (base == 2)
390 p += 2;
391 return R{p, base};
392 case 'x':
393 case 'X':
394 if (base == 0)
395 base = 16;
396 if (base == 16)
397 p += 2;
398 return R{p, base};
399 }
400 }
401 if (base == 0)
402 base = 8;
403 } else if (base == 0) {
404 base = 10;
405 }
406 Q_ASSERT(base);
407 }
408 return R{p, base};
409}
410
411static bool isDigitForBase(char d, int base)
412{
413 if (d < '0')
414 return false;
415 if (d - '0' < qMin(base, 10))
416 return true;
417 if (base > 10) {
418 d |= 0x20; // tolower
419 return d >= 'a' && d < 'a' + base - 10;
420 }
421 return false;
422}
423
424QSimpleParsedNumber<qulonglong> qstrntoull(const char *begin, qsizetype size, int base)
425{
426 const char *p = begin, *const stop = begin + size;
427 while (p < stop && ascii_isspace(*p))
428 ++p;
429 unsigned long long result = 0;
430 if (p >= stop || *p == '-')
431 return { };
432 const auto prefix = scanPrefix(*p == '+' ? p + 1 : p, stop, base);
433 if (!prefix.base || prefix.next >= stop)
434 return { };
435
436 const auto res = std::from_chars(prefix.next, stop, result, prefix.base);
437 if (res.ec != std::errc{})
438 return { };
439 return { result, res.ptr == prefix.next ? 0 : res.ptr - begin };
440}
441
442QSimpleParsedNumber<qlonglong> qstrntoll(const char *begin, qsizetype size, int base)
443{
444 const char *p = begin, *const stop = begin + size;
445 while (p < stop && ascii_isspace(*p))
446 ++p;
447 // Frustratingly, std::from_chars() doesn't cope with a 0x prefix that might
448 // be between the sign and digits, so we have to handle that for it, which
449 // means we can't use its ability to read LLONG_MIN directly; see below.
450 const bool negate = p < stop && *p == '-';
451 if (negate || (p < stop && *p == '+'))
452 ++p;
453
454 const auto prefix = scanPrefix(p, stop, base);
455 // Must check for digit, as from_chars() will accept a sign, which would be
456 // a second sign, that we should reject.
457 if (!prefix.base || prefix.next >= stop || !isDigitForBase(*prefix.next, prefix.base))
458 return { };
459
460 long long result = 0;
461 auto res = std::from_chars(prefix.next, stop, result, prefix.base);
462 if (negate && res.ec == std::errc::result_out_of_range) {
463 // Maybe LLONG_MIN:
464 unsigned long long check = 0;
465 res = std::from_chars(prefix.next, stop, check, prefix.base);
466 if (res.ec == std::errc{} && check + std::numeric_limits<long long>::min() == 0)
467 return { std::numeric_limits<long long>::min(), res.ptr - begin };
468 return { };
469 }
470 if (res.ec != std::errc{})
471 return { };
472 return { negate ? -result : result, res.ptr - begin };
473}
474
475template <typename Char>
476static Q_ALWAYS_INLINE void qulltoString_helper(qulonglong number, int base, Char *&p)
477{
478 // Performance-optimized code. Compiler can generate faster code when base is known.
479 switch (base) {
480#define BIG_BASE_LOOP(b)
481 do {
482 const int r = number % b;
483 *--p = Char((r < 10 ? '0' : 'a' - 10) + r);
484 number /= b;
485 } while (number)
486#ifndef __OPTIMIZE_SIZE__
487# define SMALL_BASE_LOOP(b)
488 do {
489 *--p = Char('0' + number % b);
490 number /= b;
491 } while (number)
492
493 case 2: SMALL_BASE_LOOP(2); break;
494 case 8: SMALL_BASE_LOOP(8); break;
495 case 10: SMALL_BASE_LOOP(10); break;
496 case 16: BIG_BASE_LOOP(16); break;
497#undef SMALL_BASE_LOOP
498#endif
499 default: BIG_BASE_LOOP(base); break;
500#undef BIG_BASE_LOOP
501 }
502}
503
504// This is technically "qulonglong to ascii", but that name's taken
505QString qulltoBasicLatin(qulonglong number, int base, bool negative)
506{
507 if (number == 0)
508 return QStringLiteral("0");
509 // Length of MIN_LLONG with the sign in front is 65; we never need surrogate pairs.
510 // We do not need a terminator.
511 const unsigned maxlen = 65;
512 static_assert(CHAR_BIT * sizeof(number) + 1 <= maxlen);
513 char16_t buff[maxlen];
514 char16_t *const end = buff + maxlen, *p = end;
515
516 qulltoString_helper<char16_t>(number, base, p);
517 if (negative)
518 *--p = u'-';
519
520 return QString(reinterpret_cast<QChar *>(p), end - p);
521}
522
523QString qulltoa(qulonglong number, int base, const QStringView zero)
524{
525 // Length of MAX_ULLONG in base 2 is 64; and we may need a surrogate pair
526 // per digit. We do not need a terminator.
527 const unsigned maxlen = 128;
528 static_assert(CHAR_BIT * sizeof(number) <= maxlen);
529 char16_t buff[maxlen];
530 char16_t *const end = buff + maxlen, *p = end;
531
532 if (base != 10 || zero == u"0") {
533 qulltoString_helper<char16_t>(number, base, p);
534 } else if (zero.size() && !zero.at(0).isSurrogate()) {
535 const char16_t zeroUcs2 = zero.at(0).unicode();
536 while (number != 0) {
537 *(--p) = unicodeForDigit(number % base, zeroUcs2);
538
539 number /= base;
540 }
541 } else if (zero.size() == 2 && zero.at(0).isHighSurrogate()) {
542 const char32_t zeroUcs4 = QChar::surrogateToUcs4(zero.at(0), zero.at(1));
543 while (number != 0) {
544 const char32_t digit = unicodeForDigit(number % base, zeroUcs4);
545
546 *(--p) = QChar::lowSurrogate(digit);
547 *(--p) = QChar::highSurrogate(digit);
548
549 number /= base;
550 }
551 } else { // zero should always be either a non-surrogate or a surrogate pair:
552 Q_UNREACHABLE_RETURN(QString());
553 }
554
555 return QString(reinterpret_cast<QChar *>(p), end - p);
556}
557
558char *qulltoa2(char *p, qulonglong n, int base)
559{
560#if defined(QT_CHECK_RANGE)
561 if (base < 2 || base > 36) {
562 qWarning("QByteArray::setNum: Invalid base %d", base);
563 base = 10;
564 }
565#endif
566 qulltoString_helper(n, base, p);
567 return p;
568}
569
570/*!
571 \internal
572
573 Converts the initial portion of the string pointed to by \a s00 to a double,
574 using the 'C' locale. The function sets the pointer pointed to by \a se to
575 point to the character past the last character converted.
576 */
577double qstrntod(const char *s00, qsizetype len, const char **se, bool *ok)
578{
579 auto r = qt_asciiToDouble(s00, len, TrailingJunkAllowed);
580 if (se)
581 *se = s00 + (r.used < 0 ? -r.used : r.used);
582 if (ok)
583 *ok = r.ok();
584 return r.result;
585}
586
587QString qdtoa(qreal d, int *decpt, int *sign)
588{
589 bool nonNullSign = false;
590 int nonNullDecpt = 0;
591 int length = 0;
592
593 // Some versions of libdouble-conversion like an extra digit, probably for '\0'
594 constexpr qsizetype digits = std::numeric_limits<double>::max_digits10 + 1;
595 char result[digits];
596 qt_doubleToAscii(d, QLocaleData::DFSignificantDigits, QLocale::FloatingPointShortest,
597 result, digits, nonNullSign, length, nonNullDecpt);
598
599 if (sign)
600 *sign = nonNullSign ? 1 : 0;
601 if (decpt)
602 *decpt = nonNullDecpt;
603
604 return QLatin1StringView(result, length);
605}
606
607static QLocaleData::DoubleForm resolveFormat(int precision, int decpt, qsizetype length)
608{
609 bool useDecimal;
610 if (precision == QLocale::FloatingPointShortest) {
611 // Find out which representation is shorter.
612 // Set bias to everything added to exponent form but not
613 // decimal, minus the converse.
614
615 // Exponent adds separator, sign and two exponents:
616 int bias = 2 + 2;
617 if (length <= decpt && length > 1)
618 ++bias;
619 else if (length == 1 && decpt <= 0)
620 --bias;
621
622 // When 0 < decpt <= length, the forms have equal digit
623 // counts, plus things bias has taken into account;
624 // otherwise decimal form's digit count is right-padded with
625 // zeros to decpt, when decpt is positive, otherwise it's
626 // left-padded with 1 - decpt zeros.
627 if (decpt <= 0)
628 useDecimal = 1 - decpt <= bias;
629 else if (decpt <= length)
630 useDecimal = true;
631 else
632 useDecimal = decpt <= length + bias;
633 } else {
634 // X == decpt - 1, POSIX's P; -4 <= X < P iff -4 < decpt <= P
635 Q_ASSERT(precision >= 0);
636 useDecimal = decpt > -4 && decpt <= (precision ? precision : 1);
637 }
639}
640
641static constexpr int digits(int number)
642{
643 Q_ASSERT(number >= 0);
644 if (Q_LIKELY(number < 1000))
645 return number < 10 ? 1 : number < 100 ? 2 : 3;
646 int i = 3;
647 for (number /= 1000; number; number /= 10)
648 ++i;
649 return i;
650}
651
652// Used generically for both QString and QByteArray
653template <typename T>
654static T dtoString(double d, QLocaleData::DoubleForm form, int precision, bool uppercase)
655{
656 // Undocumented: aside from F.P.Shortest, precision < 0 is treated as
657 // default, 6 - same as printf().
658 if (precision != QLocale::FloatingPointShortest && precision < 0)
659 precision = 6;
660
661 using D = std::numeric_limits<double>;
662 // 1 is for the null-terminator
663 constexpr int MaxDigits = 1 + qMax(D::max_exponent10, D::digits10 - D::min_exponent10);
664
665 // "maxDigits" above is a reasonable estimate, though we may need more due to extra precision
666 int bufSize = 1;
667 if (precision == QLocale::FloatingPointShortest)
668 bufSize += D::max_digits10;
669 else if (form == QLocaleData::DFDecimal && qt_is_finite(d))
670 bufSize += wholePartSpace(qAbs(d)) + precision;
671 else // Add extra digit due to different interpretations of precision.
672 bufSize += qMax(2, precision) + 1; // Must also be big enough for "nan" or "inf"
673
674 // Reserve `MaxDigits` on the stack, which is a reasonable estimate;
675 // but we may need more due to extra precision, which we cannot know at compile-time.
676 QVarLengthArray<char, MaxDigits> buffer(bufSize);
677 bool negative = false;
678 int length = 0;
679 int decpt = 0;
680 qt_doubleToAscii(d, form, precision, buffer.data(), buffer.size(), negative, length, decpt);
681 QLatin1StringView view(buffer.data(), length);
682 const bool succinct = form == QLocaleData::DFSignificantDigits;
683 qsizetype total = (negative ? 1 : 0) + length;
684 if (qt_is_finite(d)) {
685 if (succinct)
686 form = resolveFormat(precision, decpt, view.size());
687
688 switch (form) {
690 total += 3; // (.e+) The '.' may not be needed, but we would only overestimate by 1 char
691 // Exponents: we guarantee at least 2
692 total += std::max(2, digits(std::abs(decpt - 1)));
693 // "length - 1" because one of the digits will always be before the decimal point
694 if (int extraPrecision = precision - (length - 1); extraPrecision > 0 && !succinct)
695 total += extraPrecision; // some requested zero-padding
696 break;
698 if (decpt <= 0) // leading "0." and zeros
699 total += 2 - decpt;
700 else if (decpt < length) // just the dot
701 total += 1;
702 else // trailing zeros (and no dot, unless we require extra precision):
703 total += decpt - length;
704
705 if (precision > 0 && !succinct) {
706 // May need trailing zeros to satisfy precision:
707 if (decpt < length)
708 total += std::max(0, precision - length + decpt);
709 else // and a dot to separate them:
710 total += 1 + precision;
711 }
712 break;
714 Q_UNREACHABLE(); // Handled earlier
715 }
716 }
717
718 constexpr bool IsQString = std::is_same_v<T, QString>;
719 using Char = std::conditional_t<IsQString, char16_t, char>;
720
721 T result;
722 result.reserve(total);
723
724 if (negative && !qIsNull(d)) // We don't return "-0"
725 result.append(Char('-'));
726 if (!qt_is_finite(d)) {
727 result.append(view);
728 if (uppercase)
729 result = std::move(result).toUpper();
730 } else {
731 switch (form) {
733 result.append(view.first(1));
734 view = view.sliced(1);
735 if (!view.isEmpty() || (!succinct && precision > 0)) {
736 result.append(Char('.'));
737 result.append(view);
738 if (qsizetype pad = precision - view.size(); !succinct && pad > 0) {
739 for (int i = 0; i < pad; ++i)
740 result.append(Char('0'));
741 }
742 }
743 int exponent = decpt - 1;
744 result.append(Char(uppercase ? 'E' : 'e'));
745 result.append(Char(exponent < 0 ? '-' : '+'));
746 exponent = std::abs(exponent);
747 Q_ASSERT(exponent <= D::max_exponent10 + D::max_digits10);
748 int exponentDigits = digits(exponent);
749 // C's printf guarantees a two-digit exponent, and so do we:
750 if (exponentDigits == 1)
751 result.append(Char('0'));
752 result.resize(result.size() + exponentDigits);
753 auto location = reinterpret_cast<Char *>(result.end());
754 qulltoString_helper<Char>(exponent, 10, location);
755 break;
756 }
758 if (decpt < 0) {
759 if constexpr (IsQString)
760 result.append(u"0.0");
761 else
762 result.append("0.0");
763 while (++decpt < 0)
764 result.append(Char('0'));
765 result.append(view);
766 if (!succinct) {
767 auto numDecimals = result.size() - 2 - (negative ? 1 : 0);
768 for (qsizetype i = numDecimals; i < precision; ++i)
769 result.append(Char('0'));
770 }
771 } else {
772 if (decpt > view.size()) {
773 result.append(view);
774 const int sign = negative ? 1 : 0;
775 while (result.size() - sign < decpt)
776 result.append(Char('0'));
777 view = {};
778 } else if (decpt) {
779 result.append(view.first(decpt));
780 view = view.sliced(decpt);
781 } else {
782 result.append(Char('0'));
783 }
784 if (!view.isEmpty() || (!succinct && view.size() < precision)) {
785 result.append(Char('.'));
786 result.append(view);
787 if (!succinct) {
788 for (qsizetype i = view.size(); i < precision; ++i)
789 result.append(Char('0'));
790 }
791 }
792 }
793 break;
795 Q_UNREACHABLE(); // taken care of earlier
796 break;
797 }
798 }
799 Q_ASSERT(total >= result.size()); // No reallocations are needed
800 return result;
801}
802
803QString qdtoBasicLatin(double d, QLocaleData::DoubleForm form, int precision, bool uppercase)
804{
805 return dtoString<QString>(d, form, precision, uppercase);
806}
807
808QByteArray qdtoAscii(double d, QLocaleData::DoubleForm form, int precision, bool uppercase)
809{
810 return dtoString<QByteArray>(d, form, precision, uppercase);
811}
812
813#if defined(QT_SUPPORTS_INT128) || defined(QT_USE_MSVC_INT128)
814static inline quint64 toUInt64(qinternaluint128 v)
815{
816#if defined(QT_USE_MSVC_INT128)
817 return quint64(v._Word[0]);
818#else
819 return quint64(v);
820#endif
821}
822
823QString quint128toBasicLatin(qinternaluint128 number, int base)
824{
825 // We divide our 128-bit number into parts that we can do text
826 // concatenation with. This list is the maximum power of the
827 // base that is less than 2^64.
828 static constexpr auto dividers = []() constexpr {
829 std::array<quint64, 35> bases {};
830 for (int base = 2; base <= 36; ++base) {
831 quint64 v = base;
832 while (v * base > v)
833 v *= base;
834 bases[base - 2] = v;
835 }
836 return bases;
837 }();
838 static constexpr auto digitCounts = []() constexpr {
839 std::array<quint8, 35> digits{};
840 for (int base = 2; base <= 36; ++base) {
841 quint64 v = base;
842 int i = 0;
843 for (i = 0; v * base > v; ++i)
844 v *= base;
845 digits[base - 2] = i;
846 }
847 return digits;
848 }();
849
850 QString result;
851
852 constexpr unsigned flags = QLocaleData::NoFlags;
853 const QLocaleData *dd = QLocaleData::c();
854
855 // special base cases:
856 constexpr int Width = -1;
857 if (base == 2 || base == 4 || base == 16) {
858 // 2^64 is a power of 2, 4 and 16
859 result = dd->unsLongLongToString(quint64(number), 64, base, Width, flags);
860 result.prepend(dd->unsLongLongToString(quint64(number >> 64), -1, base, Width, flags));
861 } else {
862 int digitCount = digitCounts[base - 2];
863 quint64 divider = dividers[base - 2];
864 quint64 lower = toUInt64(number % divider);
865 number /= divider;
866 while (number) {
867 result.prepend(dd->unsLongLongToString(lower, digitCount, base, Width, flags));
868 lower = toUInt64(number % divider);
869 number /= divider;
870 }
871 result.prepend(dd->unsLongLongToString(lower, -1, base, Width, flags));
872 }
873 return result;
874}
875
876QString qint128toBasicLatin(qinternalint128 number, int base)
877{
878 const bool negative = number < 0;
879 if (negative)
880 number *= -1;
881 QString result = quint128toBasicLatin(qinternaluint128(number), base);
882 if (negative)
883 result.prepend(u'-');
884 return result;
885}
886#endif // defined(QT_SUPPORTS_INT128) || defined(QT_USE_MSVC_INT128)
887
888QT_END_NAMESPACE
#define QT_CLOCALE_HOLDER
static T dtoString(double d, QLocaleData::DoubleForm form, int precision, bool uppercase)
#define LLONG_MAX
static Q_ALWAYS_INLINE void qulltoString_helper(qulonglong number, int base, Char *&p)
static auto scanPrefix(const char *p, const char *stop, int base)
static constexpr int digits(int number)
#define SMALL_BASE_LOOP(b)
#define ULLONG_MAX
static bool isDigitForBase(char d, int base)
QSimpleParsedNumber< qlonglong > qstrntoll(const char *begin, qsizetype size, int base)
#define BIG_BASE_LOOP(b)
static QLocaleData::DoubleForm resolveFormat(int precision, int decpt, qsizetype length)
#define LLONG_MIN
QString qdtoa(qreal d, int *decpt, int *sign)
StrayCharacterMode
@ TrailingJunkAllowed
@ WhitespacesAllowed
Q_CORE_EXPORT double qstrntod(const char *s00, qsizetype len, char const **se, bool *ok)
QSimpleParsedNumber< double > qt_asciiToDouble(const char *num, qsizetype numLen, StrayCharacterMode strayCharMode=TrailingJunkProhibited)
QByteArray qdtoAscii(double d, QLocaleData::DoubleForm form, int precision, bool uppercase)
char * qulltoa2(char *p, qulonglong n, int base)
QString qdtoBasicLatin(double d, QLocaleData::DoubleForm form, int precision, bool uppercase)
QString qulltoa(qulonglong l, int base, const QStringView zero)
QSimpleParsedNumber< qulonglong > qstrntoull(const char *nptr, qsizetype size, int base)
void qt_doubleToAscii(double d, QLocaleData::DoubleForm form, int precision, char *buf, qsizetype bufSize, bool &sign, int &length, int &decpt)
QString qulltoBasicLatin(qulonglong l, int base, bool negative)
@ DFSignificantDigits
Definition qlocale_p.h:255