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 | |
5 | #include "qlocale_tools_p.h" |
6 | #include "qdoublescanprint_p.h" |
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 | |
41 | QT_BEGIN_NAMESPACE |
42 | |
43 | using namespace QtMiscUtils; |
44 | |
45 | QT_CLOCALE_HOLDER |
46 | |
47 | void 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)(a: bufSize, b: qsizetype(INT_MAX))); |
106 | double_conversion::DoubleToStringConverter::DoubleToAscii(v: d, mode, requested_digits: precision, buffer: buf, |
107 | buffer_length: boundedBufferSize, |
108 | sign: &sign, length: &length, point: &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 (isZero(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 | |
255 | QSimpleParsedNumber<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 { .result: negative ? -qt_inf() : qt_inf(), .used: offset + 3 }; |
291 | else if (c == 'n' && c2 == 'a' && c3 == 'n' && !hasSign) |
292 | return { .result: qt_qnan(), .used: 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(buffer: num, length: int(numLen), processed_characters_count: &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 { .result: d, .used: -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 (isZero(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 {.result: d, .used: -processed}; |
364 | } else if (num[i] == 'e' || num[i] == 'E') { |
365 | break; |
366 | } |
367 | } |
368 | } |
369 | return { .result: d, .used: processed }; |
370 | } |
371 | |
372 | /* Detect base if 0 and, if base is hex or bin, skip over 0x/0b prefixes */ |
373 | static 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(c: *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{.next: p, .base: base}; |
392 | case 'x': |
393 | case 'X': |
394 | if (base == 0) |
395 | base = 16; |
396 | if (base == 16) |
397 | p += 2; |
398 | return R{.next: p, .base: 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{.next: p, .base: base}; |
409 | } |
410 | |
411 | static bool isDigitForBase(char d, int base) |
412 | { |
413 | if (d < '0') |
414 | return false; |
415 | if (d - '0' < qMin(a: base, b: 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 | |
424 | QSimpleParsedNumber<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(c: *p)) |
428 | ++p; |
429 | unsigned long long result = 0; |
430 | if (p >= stop || *p == '-') |
431 | return { }; |
432 | const auto prefix = scanPrefix(p: *p == '+' ? p + 1 : p, stop, base); |
433 | if (!prefix.base || prefix.next >= stop) |
434 | return { }; |
435 | |
436 | const auto res = std::from_chars(first: prefix.next, last: stop, value&: result, base: prefix.base); |
437 | if (res.ec != std::errc{}) |
438 | return { }; |
439 | return { .result: result, .used: res.ptr == prefix.next ? 0 : res.ptr - begin }; |
440 | } |
441 | |
442 | QSimpleParsedNumber<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(c: *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(d: *prefix.next, base: prefix.base)) |
458 | return { }; |
459 | |
460 | long long result = 0; |
461 | auto res = std::from_chars(first: prefix.next, last: stop, value&: result, base: 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(first: prefix.next, last: stop, value&: check, base: prefix.base); |
466 | if (res.ec == std::errc{} && check + std::numeric_limits<long long>::min() == 0) |
467 | return { .result: std::numeric_limits<long long>::min(), .used: res.ptr - begin }; |
468 | return { }; |
469 | } |
470 | if (res.ec != std::errc{}) |
471 | return { }; |
472 | return { .result: negate ? -result : result, .used: res.ptr - begin }; |
473 | } |
474 | |
475 | template <typename Char> |
476 | static 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 |
505 | QString 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 | |
523 | QString 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(n: 0).isSurrogate()) { |
535 | const char16_t zeroUcs2 = zero.at(n: 0).unicode(); |
536 | while (number != 0) { |
537 | *(--p) = unicodeForDigit(digit: number % base, zero: zeroUcs2); |
538 | |
539 | number /= base; |
540 | } |
541 | } else if (zero.size() == 2 && zero.at(n: 0).isHighSurrogate()) { |
542 | const char32_t zeroUcs4 = QChar::surrogateToUcs4(high: zero.at(n: 0), low: zero.at(n: 1)); |
543 | while (number != 0) { |
544 | const char32_t digit = unicodeForDigit(digit: number % base, zero: zeroUcs4); |
545 | |
546 | *(--p) = QChar::lowSurrogate(ucs4: digit); |
547 | *(--p) = QChar::highSurrogate(ucs4: 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 | |
558 | char *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(number: 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 | */ |
577 | double qstrntod(const char *s00, qsizetype len, const char **se, bool *ok) |
578 | { |
579 | auto r = qt_asciiToDouble(num: s00, numLen: len, strayCharMode: 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 | |
587 | QString 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, form: QLocaleData::DFSignificantDigits, precision: QLocale::FloatingPointShortest, |
597 | buf: result, bufSize: digits, sign&: nonNullSign, length, decpt&: nonNullDecpt); |
598 | |
599 | if (sign) |
600 | *sign = nonNullSign ? 1 : 0; |
601 | if (decpt) |
602 | *decpt = nonNullDecpt; |
603 | |
604 | return QLatin1StringView(result, length); |
605 | } |
606 | |
607 | static 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 | } |
638 | return useDecimal ? QLocaleData::DFDecimal : QLocaleData::DFExponent; |
639 | } |
640 | |
641 | static 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 |
653 | template <typename T> |
654 | static 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(a: D::max_exponent10, b: 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(d: qAbs(t: d)) + precision; |
671 | else // Add extra digit due to different interpretations of precision. |
672 | bufSize += qMax(a: 2, b: 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, buf: buffer.data(), bufSize: buffer.size(), sign&: 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, length: view.size()); |
687 | |
688 | switch (form) { |
689 | case QLocaleData::DFExponent: |
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(a: 2, b: digits(number: std::abs(x: decpt - 1))); |
693 | // "length - 1" because one of the digits will always be before the decimal point |
694 | if (int = precision - (length - 1); extraPrecision > 0 && !succinct) |
695 | total += extraPrecision; // some requested zero-padding |
696 | break; |
697 | case QLocaleData::DFDecimal: |
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(a: 0, b: precision - length + decpt); |
709 | else // and a dot to separate them: |
710 | total += 1 + precision; |
711 | } |
712 | break; |
713 | case QLocaleData::DFSignificantDigits: |
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 && !isZero(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) { |
732 | case QLocaleData::DFExponent: { |
733 | result.append(view.first(n: 1)); |
734 | view = view.sliced(pos: 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(x: exponent); |
747 | Q_ASSERT(exponent <= D::max_exponent10 + D::max_digits10); |
748 | int exponentDigits = digits(number: 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 | } |
757 | case QLocaleData::DFDecimal: |
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(n: decpt)); |
780 | view = view.sliced(pos: 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; |
794 | case QLocaleData::DFSignificantDigits: |
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 | |
803 | QString qdtoBasicLatin(double d, QLocaleData::DoubleForm form, int precision, bool uppercase) |
804 | { |
805 | return dtoString<QString>(d, form, precision, uppercase); |
806 | } |
807 | |
808 | QByteArray 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) |
814 | static 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 | |
823 | QString 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(l: quint64(number), precision: 64, base, width: Width, flags); |
860 | result.prepend(s: dd->unsLongLongToString(l: quint64(number >> 64), precision: -1, base, width: Width, flags)); |
861 | } else { |
862 | int digitCount = digitCounts[base - 2]; |
863 | quint64 divider = dividers[base - 2]; |
864 | quint64 lower = toUInt64(v: number % divider); |
865 | number /= divider; |
866 | while (number) { |
867 | result.prepend(s: dd->unsLongLongToString(l: lower, precision: digitCount, base, width: Width, flags)); |
868 | lower = toUInt64(v: number % divider); |
869 | number /= divider; |
870 | } |
871 | result.prepend(s: dd->unsLongLongToString(l: lower, precision: -1, base, width: Width, flags)); |
872 | } |
873 | return result; |
874 | } |
875 | |
876 | QString qint128toBasicLatin(qinternalint128 number, int base) |
877 | { |
878 | const bool negative = number < 0; |
879 | if (negative) |
880 | number *= -1; |
881 | QString result = quint128toBasicLatin(number: qinternaluint128(number), base); |
882 | if (negative) |
883 | result.prepend(c: u'-'); |
884 | return result; |
885 | } |
886 | #endif // defined(QT_SUPPORTS_INT128) || defined(QT_USE_MSVC_INT128) |
887 | |
888 | QT_END_NAMESPACE |
889 | |