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