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.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// Copyright (C) 2021 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
6#include "qglobal.h"
7
8#if defined(Q_CC_GNU_ONLY) && Q_CC_GNU >= 1000
9/* gcc has complained about storing a pointer to a static QLocalePrivate in a
10 QSharedDataPointer, whose destructor would free the non-heap object if the
11 refcount ever got down to zero. The static instances this happens to are
12 instantiated with a refcount of 1 that never gets decremented so as long as
13 QSharedDataPointer keeps its incref()s and decref()s balanced it'll never get
14 down to zero - but the clever compiler isn't quite smart enough to figure
15 that out.
16*/
17QT_WARNING_DISABLE_GCC("-Wfree-nonheap-object") // false positive tracking
18#endif
19
20#if defined(Q_OS_MACOS)
21# include "private/qcore_mac_p.h"
22# include <CoreFoundation/CoreFoundation.h>
23#endif
24
25#include "qplatformdefs.h"
26
27#include "qcalendar.h"
28#include "qdatastream.h"
29#include "qdebug.h"
30#include "private/qduplicatetracker_p.h"
31#include "qhashfunctions.h"
32#include "qstring.h"
34#include "qlocale.h"
35#include "qlocale_p.h"
37#include <private/qtools_p.h>
38#if QT_CONFIG(datetimeparser)
39#include "private/qdatetimeparser_p.h"
40#endif
41#include "qnamespace.h"
42#include "qdatetime.h"
43#include "qstringlist.h"
44#include "qvariant.h"
46#include "qstringbuilder.h"
47#if QT_CONFIG(timezone)
48# include "qtimezone.h"
49#endif
50#include "private/qnumeric_p.h"
51#include "private/qtools_p.h"
52#include <cmath>
53#ifndef QT_NO_SYSTEMLOCALE
54# include "qmutex.h"
55#endif
56#ifdef Q_OS_WIN
57# include <qt_windows.h>
58# include <time.h>
59#endif
60
61#include "private/qcalendarbackend_p.h"
62#include "private/qgregoriancalendar_p.h"
63#if QT_CONFIG(timezone) && QT_CONFIG(timezone_locale) && !QT_CONFIG(icu)
64# include "private/qtimezonelocale_p.h"
65#endif
66#if QT_CONFIG(datestring)
67# include "private/qttemporalpattern_p.h"
68#endif
69
70#include <q20iterator.h>
71
73
74constexpr int QLocale::DefaultTwoDigitBaseYear;
75
76QT_IMPL_METATYPE_EXTERN_TAGGED(QList<Qt::DayOfWeek>, QList_Qt__DayOfWeek)
77#ifndef QT_NO_SYSTEMLOCALE
78QT_IMPL_METATYPE_EXTERN_TAGGED(QSystemLocale::CurrencyToStringArgument,
79 QSystemLocale__CurrencyToStringArgument)
80#endif
81
82using namespace Qt::StringLiterals;
83using namespace QtMiscUtils;
84
85#ifndef QT_NO_SYSTEMLOCALE
86Q_CONSTINIT static QSystemLocale *_systemLocale = nullptr;
87Q_CONSTINIT static QLocaleData systemLocaleData = {};
88#endif
89
90static_assert(ascii_isspace(' '));
91static_assert(ascii_isspace('\t'));
92static_assert(ascii_isspace('\n'));
93static_assert(ascii_isspace('\v'));
94static_assert(ascii_isspace('\f'));
95static_assert(ascii_isspace('\r'));
96static_assert(!ascii_isspace('\0'));
97static_assert(!ascii_isspace('\a'));
98static_assert(!ascii_isspace('a'));
99static_assert(!ascii_isspace('\177'));
100static_assert(!ascii_isspace(uchar('\200')));
101static_assert(!ascii_isspace(uchar('\xA0'))); // NBSP (is a space but Latin 1, not ASCII)
102static_assert(!ascii_isspace(uchar('\377')));
103
104/******************************************************************************
105** Helpers for accessing Qt locale database
106*/
107
108QT_BEGIN_INCLUDE_NAMESPACE
109#include "qlocale_data_p.h"
110QT_END_INCLUDE_NAMESPACE
111
112QLocale::Language QLocalePrivate::codeToLanguage(QStringView code,
113 QLocale::LanguageCodeTypes codeTypes) noexcept
114{
115 const auto len = code.size();
116 if (len != 2 && len != 3)
117 return QLocale::AnyLanguage;
118
119 const char16_t uc1 = code[0].toLower().unicode();
120 const char16_t uc2 = code[1].toLower().unicode();
121 const char16_t uc3 = len > 2 ? code[2].toLower().unicode() : 0;
122
123 // All language codes are ASCII.
124 if (uc1 > 0x7F || uc2 > 0x7F || uc3 > 0x7F)
125 return QLocale::AnyLanguage;
126
127 const AlphaCode codeBuf = { char(uc1), char(uc2), char(uc3) };
128
129 auto searchCode = [codeBuf](auto f) {
130 return std::find_if(languageCodeList.begin(), languageCodeList.end(),
131 [=](LanguageCodeEntry i) { return f(i) == codeBuf; });
132 };
133
134 if (codeTypes.testFlag(QLocale::ISO639Part1) && uc3 == 0) {
135 auto i = searchCode([](LanguageCodeEntry i) { return i.part1; });
136 if (i != languageCodeList.end())
137 return QLocale::Language(std::distance(languageCodeList.begin(), i));
138 }
139
140 if (uc3 != 0) {
141 if (codeTypes.testFlag(QLocale::ISO639Part2B)) {
142 auto i = searchCode([](LanguageCodeEntry i) { return i.part2B; });
143 if (i != languageCodeList.end())
144 return QLocale::Language(std::distance(languageCodeList.begin(), i));
145 }
146
147 // Optimization: Part 2T code if present is always the same as Part 3 code.
148 // This is asserted in iso639_3.LanguageCodeData.
149 if (codeTypes.testFlag(QLocale::ISO639Part2T)
150 && !codeTypes.testFlag(QLocale::ISO639Part3)) {
151 auto i = searchCode([](LanguageCodeEntry i) { return i.part2T; });
152 if (i != languageCodeList.end())
153 return QLocale::Language(std::distance(languageCodeList.begin(), i));
154 }
155
156 if (codeTypes.testFlag(QLocale::ISO639Part3)) {
157 auto i = searchCode([](LanguageCodeEntry i) { return i.part3; });
158 if (i != languageCodeList.end())
159 return QLocale::Language(std::distance(languageCodeList.begin(), i));
160 }
161 } else if (codeTypes.testFlag(QLocale::LegacyLanguageCode)) {
162 constexpr struct LegacyCodes {
163 AlphaCode code;
164 QLocale::Language language;
165 } legacyCodes[] = {
166 { {'n', 'o'}, QLocale::NorwegianBokmal }, // no -> nb
167 { {'t', 'l'}, QLocale::Filipino }, // tl -> fil
168 { {'s', 'h'}, QLocale::Serbian }, // sh -> sr[_Latn]
169 { {'m', 'o'}, QLocale::Romanian }, // mo -> ro
170 // Android uses the following deprecated codes:
171 { {'i', 'w'}, QLocale::Hebrew }, // iw -> he
172 { {'i', 'n'}, QLocale::Indonesian }, // in -> id
173 { {'j', 'i'}, QLocale::Yiddish }, // ji -> yi
174 };
175 // We don't need binary search for seven entries (and they're not
176 // sorted), so search linearly:
177 for (const auto &e : legacyCodes) {
178 if (codeBuf == e.code)
179 return e.language;
180 }
181 }
182 return QLocale::AnyLanguage;
183}
184
185static qsizetype scriptIndex(QStringView code, Qt::CaseSensitivity cs) noexcept
186{
187 if (code.size() != 4)
188 return -1;
189
190 // Scripts are titlecased in script_code_list.
191 const bool fixCase = cs == Qt::CaseInsensitive;
192 const unsigned char c0 = (fixCase ? code[0].toUpper() : code[0]).toLatin1();
193 const unsigned char c1 = (fixCase ? code[1].toLower() : code[1]).toLatin1();
194 const unsigned char c2 = (fixCase ? code[2].toLower() : code[2]).toLatin1();
195 const unsigned char c3 = (fixCase ? code[3].toLower() : code[3]).toLatin1();
196 // Any outside the Latin1 repertoire aren't ASCII => will not match.
197 if (!c0 || !c1 || !c2 || !c3)
198 return -1;
199
200 constexpr qsizetype NumScripts = QLocale::LastScript + 1;
201 static_assert(sizeof(script_code_list) == 4 * NumScripts + 1); // +1 for an extra NUL
202 const unsigned char *c = script_code_list;
203 for (qsizetype i = 0; i < NumScripts; ++i, c += 4) {
204 if (c0 == c[0] && c1 == c[1] && c2 == c[2] && c3 == c[3])
205 return i;
206 }
207 return -1;
208}
209
210QLocale::Script QLocalePrivate::codeToScript(QStringView code) noexcept
211{
212 qsizetype index = scriptIndex(code, Qt::CaseInsensitive);
213 return index < 0 ? QLocale::AnyScript : QLocale::Script(index);
214}
215
216QLocale::Territory QLocalePrivate::codeToTerritory(QStringView code) noexcept
217{
218 const auto len = code.size();
219 if (len != 2 && len != 3)
220 return QLocale::AnyTerritory;
221
222 char16_t uc1 = code[0].toUpper().unicode();
223 char16_t uc2 = code[1].toUpper().unicode();
224 char16_t uc3 = len > 2 ? code[2].toUpper().unicode() : 0;
225
226 const unsigned char *c = territory_code_list;
227 for (; *c != 0; c += 3) {
228 if (uc1 == c[0] && uc2 == c[1] && uc3 == c[2])
229 return QLocale::Territory((c - territory_code_list)/3);
230 }
231
232 return QLocale::AnyTerritory;
233}
234
235std::array<char, 4> QLocalePrivate::languageToCode(QLocale::Language language,
236 QLocale::LanguageCodeTypes codeTypes)
237{
238 if (language == QLocale::AnyLanguage || language > QLocale::LastLanguage)
239 return {};
240 if (language == QLocale::C)
241 return {'C'};
242
243 const LanguageCodeEntry &i = languageCodeList[language];
244
245 if (codeTypes.testFlag(QLocale::ISO639Part1) && i.part1.isValid())
246 return i.part1.decode();
247
248 if (codeTypes.testFlag(QLocale::ISO639Part2B) && i.part2B.isValid())
249 return i.part2B.decode();
250
251 if (codeTypes.testFlag(QLocale::ISO639Part2T) && i.part2T.isValid())
252 return i.part2T.decode();
253
254 if (codeTypes.testFlag(QLocale::ISO639Part3))
255 return i.part3.decode();
256
257 return {};
258}
259
260QLatin1StringView QLocalePrivate::scriptToCode(QLocale::Script script)
261{
262 if (script == QLocale::AnyScript || script > QLocale::LastScript)
263 return {};
264 const unsigned char *c = script_code_list + 4 * script;
265 return {reinterpret_cast<const char *>(c), 4};
266}
267
268QLatin1StringView QLocalePrivate::territoryToCode(QLocale::Territory territory)
269{
270 if (territory == QLocale::AnyTerritory || territory > QLocale::LastTerritory)
271 return {};
272
273 const unsigned char *c = territory_code_list + 3 * territory;
274 return {reinterpret_cast<const char*>(c), c[2] == 0 ? 2 : 3};
275}
276
277namespace {
278struct LikelyPair
279{
280 QLocaleId key; // Search key.
281 QLocaleId value = QLocaleId { 0, 0, 0 };
282};
283
284bool operator<(LikelyPair lhs, LikelyPair rhs)
285{
286 // Must match the comparison LocaleDataWriter.likelySubtags() uses when
287 // sorting, see qtbase/util/locale_database.qlocalexml2cpp.py
288 const auto compare = [](int lhs, int rhs) {
289 // 0 sorts after all other values; lhs and rhs are passed ushort values.
290 const int huge = 0x10000;
291 return (lhs ? lhs : huge) - (rhs ? rhs : huge);
292 };
293 const auto &left = lhs.key;
294 const auto &right = rhs.key;
295 // Comparison order: language, region, script:
296 if (int cmp = compare(left.language_id, right.language_id))
297 return cmp < 0;
298 if (int cmp = compare(left.territory_id, right.territory_id))
299 return cmp < 0;
300 return compare(left.script_id, right.script_id) < 0;
301}
302} // anonymous namespace
303
304/*!
305 \internal
306 Fill in blank fields of a locale ID.
307
308 An ID in which some fields are zero stands for any locale that agrees with
309 it in its non-zero fields. CLDR's likely-subtag data is meant to help us
310 chose which candidate to prefer. (Note, however, that CLDR does have some
311 cases where it maps an ID to a "best match" for which CLDR does not provide
312 data, even though there are locales for which CLDR does provide data that do
313 match the given ID. It's telling us, unhelpfully but truthfully, what
314 locale would (most likely) be meant by (someone using) the combination
315 requested, even when that locale isn't yet supported.) It may also map an
316 obsolete or generic tag to a modern or more specific replacement, possibly
317 filling in some of the other fields in the process (presently only for
318 countries). Note that some fields of the result may remain blank, but there
319 is no more specific recommendation available.
320
321 For the formal specification, see
322 https://www.unicode.org/reports/tr35/#Likely_Subtags
323
324 \note We also search und_script_region and und_region; they're not mentioned
325 in the spec, but the examples clearly presume them and CLDR does provide
326 such likely matches.
327*/
329{
330 /* Each pattern that appears in a comments below, language_script_region and
331 similar, indicates which of this's fields (even if blank) are being
332 attended to in a given search; for fields left out of the pattern, the
333 search uses 0 regardless of whether this has specified the field.
334
335 If a key matches what we're searching for (possibly with a wildcard in
336 the key matching a non-wildcard in our search), the tags from this that
337 are specified in the key are replaced by the match (even if different);
338 but the other tags of this replace what's in the match (even when the
339 match does specify a value).
340
341 Keep QLocaleXmlReader.__fillLikely() in sync with this, to ensure
342 locale-appropriate time-zone naming works correctly.
343 */
344 static_assert(std::size(likely_subtags) % 2 == 0);
345 auto *pairs = reinterpret_cast<const LikelyPair *>(likely_subtags);
346 auto *const afterPairs = pairs + std::size(likely_subtags) / 2;
347 LikelyPair sought { *this };
348 // Our array is sorted in the order that puts all candidate matches in the
349 // order we would want them; ones we should prefer appear before the others.
350 if (language_id) {
351 // language_script_region, language_region, language_script, language:
352 pairs = std::lower_bound(pairs, afterPairs, sought);
353 // Single language's block isn't long enough to warrant more binary
354 // chopping within it - just traverse it all:
355 for (; pairs < afterPairs && pairs->key.language_id == language_id; ++pairs) {
356 const QLocaleId &key = pairs->key;
358 continue;
359 if (key.script_id && key.script_id != script_id)
360 continue;
361 QLocaleId value = pairs->value;
362 if (territory_id && !key.territory_id)
364 if (script_id && !key.script_id)
365 value.script_id = script_id;
366 return value;
367 }
368 }
369 // und_script_region or und_region (in that order):
370 if (territory_id) {
371 sought.key = QLocaleId { 0, script_id, territory_id };
372 pairs = std::lower_bound(pairs, afterPairs, sought);
373 // Again, individual und_?_region block isn't long enough to make binary
374 // chop a win:
375 for (; pairs < afterPairs && pairs->key.territory_id == territory_id; ++pairs) {
376 const QLocaleId &key = pairs->key;
377 Q_ASSERT(!key.language_id);
378 if (key.script_id && key.script_id != script_id)
379 continue;
380 QLocaleId value = pairs->value;
381 if (language_id)
383 if (script_id && !key.script_id)
384 value.script_id = script_id;
385 return value;
386 }
387 }
388 // und_script:
389 if (script_id) {
390 sought.key = QLocaleId { 0, script_id, 0 };
391 pairs = std::lower_bound(pairs, afterPairs, sought);
392 if (pairs < afterPairs && pairs->key.script_id == script_id) {
393 Q_ASSERT(!pairs->key.language_id && !pairs->key.territory_id);
394 QLocaleId value = pairs->value;
395 if (language_id)
397 if (territory_id)
399 return value;
400 }
401 }
402 // Finally, fall back to the match-all rule (if there is one):
403 pairs = afterPairs - 1; // All other keys are < match-all.
404 if (pairs->key.matchesAll()) {
405 QLocaleId value = pairs->value;
406 if (language_id)
408 if (territory_id)
410 if (script_id)
411 value.script_id = script_id;
412 return value;
413 }
414 return *this;
415}
416
418{
420 // language
421 {
422 QLocaleId id { language_id, 0, 0 };
424 return id;
425 }
426 // language_region
427 if (territory_id) {
430 return id;
431 }
432 // language_script
433 if (script_id) {
436 return id;
437 }
438 return max;
439}
440
441QByteArray QLocaleId::name(char separator) const
442{
443 if (language_id == QLocale::AnyLanguage)
444 return QByteArray();
445 if (language_id == QLocale::C)
446 return QByteArrayLiteral("C");
447 Q_ASSERT(language_id <= QLocale::LastLanguage);
448 Q_ASSERT(script_id <= QLocale::LastScript);
449 Q_ASSERT(territory_id <= QLocale::LastTerritory);
450
451 const LanguageCodeEntry &language = languageCodeList[language_id];
452 AlphaCode lang;
453 qsizetype langLen;
454
455 if (language.part1.isValid()) {
456 lang = language.part1;
457 langLen = 2;
458 } else {
459 lang = language.part2B.isValid() ? language.part2B : language.part3;
460 langLen = 3;
461 }
462
463 const unsigned char *script =
464 (script_id != QLocale::AnyScript ? script_code_list + 4 * script_id : nullptr);
465 const unsigned char *country =
466 (territory_id != QLocale::AnyTerritory
467 ? territory_code_list + 3 * territory_id : nullptr);
468 qsizetype len = langLen + (script ? 4 + 1 : 0) + (country ? (country[2] != 0 ? 3 : 2) + 1 : 0);
469 QByteArray name(len, Qt::Uninitialized);
470 char *uc = name.data();
471
472 auto langArray = lang.decode();
473
474 *uc++ = langArray[0];
475 *uc++ = langArray[1];
476 if (langLen > 2)
477 *uc++ = langArray[2];
478
479 if (script) {
480 *uc++ = separator;
481 *uc++ = script[0];
482 *uc++ = script[1];
483 *uc++ = script[2];
484 *uc++ = script[3];
485 }
486 if (country) {
487 *uc++ = separator;
488 *uc++ = country[0];
489 *uc++ = country[1];
490 if (country[2] != 0)
491 *uc++ = country[2];
492 }
493 return name;
494}
495
496QByteArray QLocalePrivate::bcp47Name(char separator) const
497{
498 if (m_data->m_language_id == QLocale::AnyLanguage)
499 return QByteArray();
500 if (m_data->m_language_id == QLocale::C)
501 return QByteArrayView("en") % separator % QByteArrayView("POSIX");
502
503 return m_data->id().withLikelySubtagsRemoved().name(separator);
504}
505
506static qsizetype findLocaleIndexById(QLocaleId localeId) noexcept
507{
508 qsizetype idx = locale_index[localeId.language_id];
509 // If there are no locales for specified language (so we we've got the
510 // default language, which has no associated script or country), give up:
511 if (localeId.language_id && idx == 0)
512 return idx;
513
514 Q_ASSERT(localeId.acceptLanguage(locale_data[idx].m_language_id));
515
516 do {
517 if (localeId.acceptScriptTerritory(locale_data[idx].id()))
518 return idx;
519 ++idx;
520 } while (localeId.acceptLanguage(locale_data[idx].m_language_id));
521
522 return -1;
523}
524
525static constexpr qsizetype locale_data_size = q20::ssize(locale_data) - 1; // trailing guard
526bool QLocaleData::allLocaleDataRows(bool (*check)(qsizetype, const QLocaleData &))
527{
528 for (qsizetype index = 0; index < locale_data_size; ++index) {
529 if (!(*check)(index, locale_data[index]))
530 return false;
531 }
532 return true;
533}
534
535// Internal: to enable tst_qlocaledata to access locales
536const QLocaleData *QLocaleData::dataForLocaleIndex(qsizetype index)
537{
538 Q_PRE(index >= 0);
539 Q_PRE(index < locale_data_size);
540 return locale_data + index;
541}
542
543#if QT_CONFIG(timezone) && QT_CONFIG(timezone_locale) && !QT_CONFIG(icu)
544namespace QtTimeZoneLocale {
545
546// Indices of locales obtained from the given by likely subtag fall-backs.
547QList<qsizetype> fallbackLocalesFor(qsizetype index)
548{
549 // Should match QLocaleXmlReader.pruneZoneNaming()'s fallbacks() helper,
550 // aside from the special-case kludge for C -> en_US.
551 Q_ASSERT(index < locale_data_size);
552 QList<qsizetype> result = {index};
553 QLocaleId id = locale_data[index].id();
554 if (id.language_id == QLocale::C) {
555 id = { QLocale::English, QLocale::LatinScript, QLocale::UnitedStates };
556 qsizetype it = findLocaleIndexById(id);
557 Q_ASSERT_X(it != -1, Q_FUNC_INFO, "Missing en_Latn_US from locale data");
558 Q_ASSERT_X(it != index, // equivalent to !result.contains(it)
559 Q_FUNC_INFO, "en_Latn_US != C");
560 result << it;
561 }
562
563 const QLocaleId base = id;
564 QLocaleId likely = id.withLikelySubtagsAdded();
565 if (likely != base) {
566 qsizetype it = findLocaleIndexById(likely);
567 if (it != -1 && !result.contains(it))
568 result << it;
569 }
570 if (id.territory_id) {
571 id.territory_id = 0;
572 likely = id.withLikelySubtagsAdded();
573 if (likely != base) {
574 qsizetype it = findLocaleIndexById(likely);
575 if (it != -1 && !result.contains(it))
576 result << it;
577 }
578 }
579 if (id.script_id) {
580 id.script_id = 0;
581 likely = id.withLikelySubtagsAdded();
582 if (likely != base) {
583 qsizetype it = findLocaleIndexById(likely);
584 if (it != -1 && !result.contains(it))
585 result << it;
586 }
587 }
588 return result;
589}
590
591} // QtTimeZoneLocale
592#endif // timezone_locale && !icu
593
594qsizetype QLocaleData::findLocaleIndex(QLocaleId lid) noexcept
595{
596 QLocaleId localeId = lid;
597 QLocaleId likelyId = localeId.withLikelySubtagsAdded();
598 const ushort fallback = likelyId.language_id;
599
600 // Try a straight match with the likely data:
601 qsizetype index = findLocaleIndexById(likelyId);
602 if (index >= 0)
603 return index;
604 QVarLengthArray<QLocaleId, 6> tried;
605 tried.push_back(likelyId);
606
607#define CheckCandidate(id) do {
608 if (!tried.contains(id)) {
609 index = findLocaleIndexById(id);
610 if (index >= 0)
611 return index;
612 tried.push_back(id);
613 }
614 } while (false) // end CheckCandidate
615
616 // No match; try again with raw data:
617 CheckCandidate(localeId);
618
619 // No match; try again with likely country for language_script
620 if (lid.territory_id && (lid.language_id || lid.script_id)) {
621 localeId.territory_id = 0;
622 likelyId = localeId.withLikelySubtagsAdded();
623 CheckCandidate(likelyId);
624
625 // No match; try again with any country
626 CheckCandidate(localeId);
627 }
628
629 // No match; try again with likely script for language_region
630 if (lid.script_id && (lid.language_id || lid.territory_id)) {
631 localeId = QLocaleId { lid.language_id, 0, lid.territory_id };
632 likelyId = localeId.withLikelySubtagsAdded();
633 CheckCandidate(likelyId);
634
635 // No match; try again with any script
636 CheckCandidate(localeId);
637 }
638#undef CheckCandidate
639
640 // No match; return base index for initial likely language:
641 return locale_index[fallback];
642}
643
644static QStringView findTag(QStringView name) noexcept
645{
646 const std::u16string_view v(name.utf16(), size_t(name.size()));
647 const auto i = v.find_first_of(u"_-.@");
648 if (i == std::string_view::npos)
649 return name;
650 return name.first(qsizetype(i));
651}
652
653static bool validTag(QStringView tag)
654{
655 // Is tag is a non-empty sequence of ASCII letters and/or digits ?
656 for (QChar uc : tag) {
657 const char16_t ch = uc.unicode();
658 if (!isAsciiLetterOrNumber(ch))
659 return false;
660 }
661 return tag.size() > 0;
662}
663
664bool qt_splitLocaleName(QStringView name,
665 QStringView *lang, QStringView *script, QStringView *land) noexcept
666{
667 // Assume each of lang, script and land is nullptr or points to an empty QStringView.
668 enum ParserState { NoState, LangState, ScriptState, CountryState };
669 ParserState state = LangState;
670 while (name.size() && state != NoState) {
671 const QStringView tag = findTag(name);
672 if (!validTag(tag))
673 break;
674 name = name.sliced(tag.size());
675 const bool sep = name.size() > 0;
676 if (sep) // tag wasn't all that remained; there was a separator
677 name = name.sliced(1);
678
679 switch (state) {
680 case LangState:
681 if (tag.size() != 2 && tag.size() != 3)
682 return false;
683 if (lang)
684 *lang = tag;
685 state = sep ? ScriptState : NoState;
686 break;
687 case ScriptState:
688 if (scriptIndex(tag, Qt::CaseSensitive) >= 0) {
689 if (script)
690 *script = tag;
691 state = sep ? CountryState : NoState;
692 break;
693 }
694 // It wasn't a script, assume it's a country.
695 Q_FALLTHROUGH();
696 case CountryState:
697 if (land)
698 *land = tag;
699 state = NoState;
700 break;
701 case NoState: // Precluded by loop condition !
702 Q_UNREACHABLE();
703 break;
704 }
705 }
706 return state != LangState;
707}
708
709QLocaleId QLocaleId::fromName(QStringView name) noexcept
710{
711 QStringView lang;
712 QStringView script;
713 QStringView land;
714 if (!qt_splitLocaleName(name, &lang, &script, &land))
715 return { QLocale::C, 0, 0 };
716
717 // POSIX is a variant, but looks like a territory.
718 if (land.compare("POSIX", Qt::CaseInsensitive) == 0)
719 return { QLocale::C, 0, 0 };
720
721 QLocale::Language langId = QLocalePrivate::codeToLanguage(lang);
722 if (langId == QLocale::AnyLanguage)
723 return { QLocale::C, 0, 0 };
724 return { langId, QLocalePrivate::codeToScript(script), QLocalePrivate::codeToTerritory(land) };
725}
726
727QString qt_readEscapedFormatString(QStringView format, qsizetype *idx)
728{
729 qsizetype &i = *idx;
730
731 Q_ASSERT(format.at(i) == u'\'');
732 ++i;
733 if (i == format.size())
734 return QString();
735 if (format.at(i).unicode() == '\'') { // "''" outside of a quoted string
736 ++i;
737 return "'"_L1;
738 }
739
740 QString result;
741
742 while (i < format.size()) {
743 if (format.at(i).unicode() == '\'') {
744 if (format.mid(i + 1).startsWith(u'\'')) {
745 // "''" inside a quoted string
746 result.append(u'\'');
747 i += 2;
748 } else {
749 break;
750 }
751 } else {
752 result.append(format.at(i++));
753 }
754 }
755 if (i < format.size())
756 ++i;
757
758 return result;
759}
760
761Q_CONSTINIT static const QLocaleData *default_data = nullptr;
762Q_CONSTINIT QBasicAtomicInt QLocalePrivate::s_generation = Q_BASIC_ATOMIC_INITIALIZER(0);
763
764static QLocalePrivate *c_private() noexcept
765{
766 Q_CONSTINIT static QLocalePrivate c_locale(locale_data, 0, QLocale::OmitGroupSeparator, 1);
767 return &c_locale;
768}
769
770static constexpr QLocale::NumberOptions defaultNumberOptions(QLocale::Language forLanguage)
771{
772 return forLanguage == QLocale::C ? QLocale::OmitGroupSeparator : QLocale::DefaultNumberOptions;
773}
774
775static constexpr QLocale::NumberOptions defaultNumberOptions(quint16 forLanguage)
776{
777 return defaultNumberOptions(QLocale::Language(forLanguage));
778}
779
780#ifndef QT_NO_SYSTEMLOCALE
781/******************************************************************************
782** Default system locale behavior
783*/
784
785/*!
786 \internal
787 Constructs a QSystemLocale object.
788
789 The constructor will automatically install this object as the system locale.
790 It and the destructor maintain a stack of system locales, with the
791 most-recently-created instance (that hasn't yet been deleted) used as the
792 system locale. This is only intended as a way to let a platform plugin
793 install its own system locale, overriding what might otherwise be provided
794 for its class of platform (as Android does, differing from Linux), and to
795 let tests transiently override the system or plugin-supplied one. As such,
796 there should not be diverse threads creating and destroying QSystemLocale
797 instances concurrently, so no attempt is made at thread-safety in managing
798 the stack.
799
800 This constructor also resets the flag that'll prompt QLocale::system() to
801 re-initialize its data, so that instantiating a QSystemLocale (even
802 transiently) triggers a refresh of the system locale's data. This is
803 exploited by some test code.
804*/
805QSystemLocale::QSystemLocale() : next(_systemLocale)
806{
807 _systemLocale = this;
808
809 systemLocaleData.m_language_id = 0;
810}
811
812/*!
813 \internal
814 Deletes the object.
815*/
816QSystemLocale::~QSystemLocale()
817{
818 if (_systemLocale == this) {
819 _systemLocale = next;
820
821 // Change to system locale => force refresh.
822 systemLocaleData.m_language_id = 0;
823 } else {
824 for (QSystemLocale *p = _systemLocale; p; p = p->next) {
825 if (p->next == this)
826 p->next = next;
827 }
828 }
829}
830
832{
833 if (_systemLocale)
834 return _systemLocale;
835
836 // As this is only ever instantiated with _systemLocale null, it is
837 // necessarily the ->next-most in any chain that may subsequently develop;
838 // and it won't be destructed until exit()-time.
839 static QSystemLocale globalInstance;
840 return &globalInstance;
841}
842
844{
845 // This function is NOT thread-safe!
846 // It *should not* be called by anything but systemData()
847 // It *is* called before {system,default}LocalePrivate exist.
848 const QSystemLocale *sys_locale = systemLocale();
849
850 // tell the object that the system locale has changed.
851 sys_locale->query(QSystemLocale::LocaleChanged);
852
853 // Populate system locale with fallback as basis
854 systemLocaleData = locale_data[sys_locale->fallbackLocaleIndex()];
855
856 QVariant res = sys_locale->query(QSystemLocale::LanguageId);
857 if (!res.isNull()) {
858 systemLocaleData.m_language_id = res.toInt();
859 systemLocaleData.m_script_id = QLocale::AnyScript; // default for compatibility
860 }
861 res = sys_locale->query(QSystemLocale::TerritoryId);
862 if (!res.isNull()) {
863 systemLocaleData.m_territory_id = res.toInt();
864 systemLocaleData.m_script_id = QLocale::AnyScript; // default for compatibility
865 }
866 res = sys_locale->query(QSystemLocale::ScriptId);
867 if (!res.isNull())
868 systemLocaleData.m_script_id = res.toInt();
869
870 // Should we replace Any values based on likely sub-tags ?
871
872 // If system locale is default locale, update the default collator's generation:
873 if (default_data == &systemLocaleData)
874 QLocalePrivate::s_generation.fetchAndAddRelaxed(1);
875}
876#endif // !QT_NO_SYSTEMLOCALE
877
878static const QLocaleData *systemData(qsizetype *sysIndex = nullptr)
879{
880#ifndef QT_NO_SYSTEMLOCALE
881 /*
882 Copy over the information from the fallback locale and modify.
883
884 If sysIndex is passed, it should be the m_index of the system locale's
885 QLocalePrivate, which we'll update if it needs it.
886
887 This modifies (cross-thread) global state, so is mutex-protected.
888 */
889 {
890 Q_CONSTINIT static QLocaleId sysId;
891 bool updated = false;
892
893 Q_CONSTINIT static QBasicMutex systemDataMutex;
894 systemDataMutex.lock();
895 if (systemLocaleData.m_language_id == 0) {
896 updateSystemPrivate();
897 updated = true;
898 }
899 // Initialization of system private has *sysIndex == -1 to hit this.
900 if (sysIndex && (updated || *sysIndex < 0)) {
901 const QLocaleId nowId = systemLocaleData.id();
902 if (sysId != nowId || *sysIndex < 0) {
903 // This look-up may be expensive:
904 *sysIndex = QLocaleData::findLocaleIndex(nowId);
905 sysId = nowId;
906 }
907 }
908 systemDataMutex.unlock();
909 }
910
911 return &systemLocaleData;
912#else
913 Q_UNUSED(sysIndex);
914 return locale_data;
915#endif
916}
917
919{
920 if (!default_data)
921 default_data = systemData();
922 return default_data;
923}
924
926{
927 const QLocaleData *const data = defaultData();
928#ifndef QT_NO_SYSTEMLOCALE
929 if (data == &systemLocaleData) {
930 // Work out a suitable index matching the system data, for use when
931 // accessing calendar data, when not fetched from system.
932 return QLocaleData::findLocaleIndex(data->id());
933 }
934#endif
935
936 using QtPrivate::q_points_into_range;
937 Q_ASSERT(q_points_into_range(data, locale_data));
938 return data - locale_data;
939}
940
941const QLocaleData *QLocaleData::c() noexcept
942{
943 Q_ASSERT(locale_index[QLocale::C] == 0);
944 return locale_data;
945}
946
947#ifndef QT_NO_DATASTREAM
948QDataStream &operator<<(QDataStream &ds, const QLocale &l)
949{
950 ds << l.name();
951 return ds;
952}
953
954QDataStream &operator>>(QDataStream &ds, QLocale &l)
955{
956 QString s;
957 ds >> s;
958 l = QLocale(s);
959 return ds;
960}
961#endif // QT_NO_DATASTREAM
962
963Q_GLOBAL_STATIC(QSharedDataPointer<QLocalePrivate>, defaultLocalePrivate,
964 new QLocalePrivate(defaultData(), defaultIndex(),
965 defaultNumberOptions(defaultData()->m_language_id)))
966
967static QLocalePrivate *localePrivateByName(QStringView name)
968{
969 if (name == u"C")
970 return c_private();
971 const qsizetype index = QLocaleData::findLocaleIndex(QLocaleId::fromName(name));
972 return new QLocalePrivate(QLocaleData::dataForLocaleIndex(index), index,
973 defaultNumberOptions(locale_data[index].m_language_id));
974}
975
976static QLocalePrivate *findLocalePrivate(QLocale::Language language, QLocale::Script script,
977 QLocale::Territory territory)
978{
979 if (language == QLocale::C)
980 return c_private();
981
982 qsizetype index = QLocaleData::findLocaleIndex(QLocaleId { language, script, territory });
983 const QLocaleData *data = QLocaleData::dataForLocaleIndex(index);
984
985 QLocale::NumberOptions numberOptions = QLocale::DefaultNumberOptions;
986
987 // If not found, should use default locale:
988 if (data->m_language_id == QLocale::C) {
989 if (defaultLocalePrivate.exists())
990 numberOptions = defaultLocalePrivate->data()->m_numberOptions;
991 data = defaultData();
992 index = defaultIndex();
993 }
994 return new QLocalePrivate(data, index, numberOptions);
995}
996
997bool comparesEqual(const QLocale &loc, QLocale::Language lang)
998{
999 // Keep in sync with findLocalePrivate()!
1000 auto compareWithPrivate = [&loc](const QLocaleData *data, QLocale::NumberOptions opts)
1001 {
1002 return loc.d->m_data == data && loc.d->m_numberOptions == opts;
1003 };
1004
1005 if (lang == QLocale::C)
1006 return compareWithPrivate(c_private()->m_data, c_private()->m_numberOptions);
1007
1008 qsizetype index = QLocaleData::findLocaleIndex(QLocaleId { lang });
1009 const QLocaleData *data = QLocaleData::dataForLocaleIndex(index);
1010
1011 QLocale::NumberOptions numberOptions = QLocale::DefaultNumberOptions;
1012
1013 // If not found, should use default locale:
1014 if (data->m_language_id == QLocale::C) {
1015 if (defaultLocalePrivate.exists())
1016 numberOptions = defaultLocalePrivate->data()->m_numberOptions;
1017 data = defaultData();
1018 }
1019 return compareWithPrivate(data, numberOptions);
1020}
1021
1022static std::optional<QString>
1023systemLocaleString(const QLocaleData *that, QSystemLocale::QueryType type)
1024{
1025#ifndef QT_NO_SYSTEMLOCALE
1026 if (that != &systemLocaleData)
1027 return std::nullopt;
1028
1029 QVariant v = systemLocale()->query(type);
1030 if (v.metaType() != QMetaType::fromType<QString>())
1031 return std::nullopt;
1032
1033 return v.toString();
1034#else
1035 Q_UNUSED(that)
1036 Q_UNUSED(type)
1037 return std::nullopt;
1038#endif
1039}
1040
1041static QString localeString(const QLocaleData *that, QSystemLocale::QueryType type,
1042 QLocaleData::DataRange range)
1043{
1044 if (auto opt = systemLocaleString(that, type))
1045 return *opt;
1046 return range.getData(single_character_data);
1047}
1048
1050{
1051 return localeString(this, QSystemLocale::DecimalPoint, decimalSeparator());
1052}
1053
1055{
1056 return localeString(this, QSystemLocale::GroupSeparator, groupDelim());
1057}
1058
1059QString QLocaleData::percentSign() const
1060{
1061 return percent().getData(single_character_data);
1062}
1063
1065{
1066 return listDelimit().getData(single_character_data);
1067}
1068
1069QString QLocaleData::zeroDigit() const
1070{
1071 return localeString(this, QSystemLocale::ZeroDigit, zero());
1072}
1073
1074char32_t QLocaleData::zeroUcs() const
1075{
1076#ifndef QT_NO_SYSTEMLOCALE
1077 if (this == &systemLocaleData) {
1078 const auto text = systemLocale()->query(QSystemLocale::ZeroDigit).toString();
1079 if (!text.isEmpty()) {
1080 if (text.size() == 1 && !text.at(0).isSurrogate())
1081 return text.at(0).unicode();
1082 if (text.size() == 2 && text.at(0).isHighSurrogate())
1083 return QChar::surrogateToUcs4(text.at(0), text.at(1));
1084 }
1085 }
1086#endif
1088}
1089
1091{
1092 return localeString(this, QSystemLocale::NegativeSign, minus());
1093}
1094
1096{
1097 return localeString(this, QSystemLocale::PositiveSign, plus());
1098}
1099
1101{
1102 return exponential().getData(single_character_data);
1103}
1104
1106{
1107#ifndef QT_NO_SYSTEMLOCALE
1108 if (this == &systemLocaleData) {
1109 QVariant queryResult = systemLocale()->query(QSystemLocale::Grouping);
1110 if (!queryResult.isNull()) {
1111 QLocaleData::GroupSizes sysGroupSizes =
1112 queryResult.value<QLocaleData::GroupSizes>();
1113 if (sysGroupSizes.first <= 0)
1114 sysGroupSizes.first = m_grouping_first;
1115 if (sysGroupSizes.higher <= 0)
1116 sysGroupSizes.higher = m_grouping_higher;
1117 if (sysGroupSizes.least <= 0)
1118 sysGroupSizes.least = m_grouping_least;
1119 return sysGroupSizes;
1120 }
1121 }
1122#endif
1123 return { m_grouping_first,
1124 m_grouping_higher,
1125 m_grouping_least };
1126}
1127
1128/*!
1129 \internal
1130*/
1131QLocale::QLocale(QLocalePrivate &dd)
1132 // If this ever becomes explicitly noexcept(false),
1133 // adjust QLocale::c() to not use this ctor anymore.
1134 : d(&dd)
1135{}
1136
1137/*!
1138 \variable QLocale::DefaultTwoDigitBaseYear
1139 \since 6.7
1140
1141 \brief The default start year of the century within which a format taking
1142 a two-digit year will select. The value of the constant is \c {1900}.
1143
1144 Some locales use, particularly for ShortFormat, only the last two digits of
1145 the year. Proir to 6.7 the year 1900 was always used as a base year for
1146 such cases. Now various QLocale and QDate functions have the overloads that
1147 allow callers to specify the base year, and this constant is used as its
1148 default value.
1149
1150 \sa toDate(), toDateTime(), QDate::fromString(), QDateTime::fromString()
1151*/
1152
1153/*!
1154 \since 6.3
1155
1156 Constructs a QLocale object with the specified \a name.
1157
1158 The name has the format "language[_script][_territory][.codeset][@modifier]"
1159 or "C", where:
1160
1161 \list
1162 \li language is a lowercase, two-letter, ISO 639 language code (some
1163 three-letter codes are also recognized),
1164 \li script is a capitalized, four-letter, ISO 15924 script code,
1165 \li territory is an uppercase, two-letter, ISO 3166 territory code
1166 (some numeric codes are also recognized), and
1167 \li codeset and modifier are ignored.
1168 \endlist
1169
1170 The separator can be either underscore \c{'_'} (U+005F, "low line") or a
1171 dash \c{'-'} (U+002D, "hyphen-minus"). If QLocale has no data for the
1172 specified combination of language, script, and territory, then it uses the
1173 most suitable match it can find instead. If the string violates the locale
1174 format, or no suitable data can be found for the specified keys, the "C"
1175 locale is used instead.
1176
1177 This constructor is much slower than QLocale(Language, Script, Territory) or
1178 QLocale(Language, Territory).
1179
1180 \sa bcp47Name(), {Matching combinations of language, script and territory}
1181*/
1182QLocale::QLocale(QStringView name)
1183 : d(localePrivateByName(name))
1184{
1185}
1186
1187/*!
1188 \fn QLocale::QLocale(const QString &name)
1189 \overload
1190*/
1191
1192/*!
1193 Constructs a QLocale object initialized with the default locale.
1194
1195 If no default locale was set using setDefault(), this locale will be the
1196 same as the one returned by system().
1197
1198 \sa setDefault(), system()
1199*/
1200
1201QLocale::QLocale()
1202 : d(c_private())
1203{
1204 if (!defaultLocalePrivate.isDestroyed()) {
1205 // Make sure system data is up to date:
1206 systemData();
1207 d = *defaultLocalePrivate;
1208 }
1209}
1210
1211/*!
1212 Constructs a QLocale object for the specified \a language and \a territory.
1213
1214 If there is more than one script in use for this combination, a likely
1215 script will be selected. If QLocale has no data for the specified \a
1216 language, the default locale is used. If QLocale has no data for the
1217 specified combination of \a language and \a territory, an alternative
1218 territory may be used instead.
1219
1220 \sa setDefault(), {Matching combinations of language, script and territory}
1221*/
1222
1223QLocale::QLocale(Language language, Territory territory)
1224 : d(findLocalePrivate(language, AnyScript, territory))
1225{
1226}
1227
1228/*!
1229 \since 4.8
1230
1231 Constructs a QLocale object for the specified \a language, \a script and \a
1232 territory.
1233
1234 If QLocale does not have data for the given combination, it will find data
1235 for as good a match as it can. It falls back on the default locale if
1236
1237 \list
1238 \li \a language is \c AnyLanguage and no language can be inferred from \a
1239 script and \a territory
1240 \li QLocale has no data for the language, either given as \a language or
1241 inferred as above.
1242 \endlist
1243
1244 \sa setDefault(), {Matching combinations of language, script and territory}
1245*/
1246
1247QLocale::QLocale(Language language, Script script, Territory territory)
1248 : d(findLocalePrivate(language, script, territory))
1249{
1250}
1251
1252/*!
1253 Constructs a QLocale object as a copy of \a other.
1254*/
1255
1256QLocale::QLocale(const QLocale &other) noexcept = default;
1257
1258/*!
1259 Destructor
1260*/
1261
1262QLocale::~QLocale()
1263{
1264}
1265
1266/*!
1267 Assigns \a other to this QLocale object and returns a reference
1268 to this QLocale object.
1269*/
1270
1271QLocale &QLocale::operator=(const QLocale &other) noexcept = default;
1272
1273/*!
1274 \internal
1275 Equality comparison.
1276*/
1277
1278bool QLocale::equals(const QLocale &other) const noexcept
1279{
1280 return d->m_data == other.d->m_data && d->m_numberOptions == other.d->m_numberOptions;
1281}
1282
1283/*!
1284 \fn void QLocale::swap(QLocale &other)
1285 \since 5.6
1286 \memberswap{locale}
1287*/
1288
1289/*!
1290 \since 5.6
1291 \qhashold{QLocale}
1292*/
1293size_t qHash(const QLocale &key, size_t seed) noexcept
1294{
1295 return qHashMulti(seed, key.d->m_data, key.d->m_numberOptions);
1296}
1297
1298/*!
1299 \since 4.2
1300
1301 Sets the \a options related to number conversions for this QLocale instance.
1302
1303 \sa numberOptions(), FloatingPointPrecisionOption
1304*/
1305void QLocale::setNumberOptions(NumberOptions options)
1306{
1307 d->m_numberOptions = options;
1308}
1309
1310/*!
1311 \since 4.2
1312
1313 Returns the options related to number conversions for this QLocale instance.
1314
1315 By default, no options are set for the standard locales, except for the "C"
1316 locale, which has OmitGroupSeparator set by default.
1317
1318 \sa setNumberOptions(), toString(), groupSeparator(), FloatingPointPrecisionOption
1319*/
1320QLocale::NumberOptions QLocale::numberOptions() const
1321{
1322 return d->m_numberOptions;
1323}
1324
1325/*!
1326 \fn QString QLocale::quoteString(const QString &str, QuotationStyle style) const
1327
1328 \since 4.8
1329
1330 Returns \a str quoted according to the current locale using the given
1331 quotation \a style.
1332*/
1333
1334/*!
1335 \since 6.0
1336
1337 \overload
1338*/
1339QString QLocale::quoteString(QStringView str, QuotationStyle style) const
1340{
1341#ifndef QT_NO_SYSTEMLOCALE
1342 if (d->m_data == &systemLocaleData) {
1343 QVariant res;
1344 if (style == AlternateQuotation)
1345 res = systemLocale()->query(QSystemLocale::StringToAlternateQuotation,
1346 QVariant::fromValue(str));
1347 if (res.isNull() || style == StandardQuotation)
1348 res = systemLocale()->query(QSystemLocale::StringToStandardQuotation,
1349 QVariant::fromValue(str));
1350 if (!res.isNull())
1351 return res.toString();
1352 }
1353#endif
1354
1355 QLocaleData::DataRange start, end;
1356 if (style == StandardQuotation) {
1357 start = d->m_data->quoteStart();
1358 end = d->m_data->quoteEnd();
1359 } else {
1360 start = d->m_data->quoteStartAlternate();
1361 end = d->m_data->quoteEndAlternate();
1362 }
1363
1364 return start.viewData(single_character_data) % str % end.viewData(single_character_data);
1365}
1366
1367/*!
1368 \since 4.8
1369
1370 Returns a string that represents a join of a given \a list of strings with
1371 a separator defined by the locale.
1372*/
1373QString QLocale::createSeparatedList(const QStringList &list) const
1374{
1375 // May be empty if list is empty or sole entry is empty.
1376#ifndef QT_NO_SYSTEMLOCALE
1377 if (d->m_data == &systemLocaleData) {
1378 QVariant res =
1379 systemLocale()->query(QSystemLocale::ListToSeparatedString, QVariant::fromValue(list));
1380
1381 if (!res.isNull())
1382 return res.toString();
1383 }
1384#endif
1385
1386 const qsizetype size = list.size();
1387 if (size < 1)
1388 return QString();
1389
1390 if (size == 1)
1391 return list.at(0);
1392
1393 if (size == 2)
1394 return d->m_data->pairListPattern().getData(
1395 list_pattern_part_data).arg(list.at(0), list.at(1));
1396
1397 QStringView formatStart = d->m_data->startListPattern().viewData(list_pattern_part_data);
1398 QStringView formatMid = d->m_data->midListPattern().viewData(list_pattern_part_data);
1399 QStringView formatEnd = d->m_data->endListPattern().viewData(list_pattern_part_data);
1400 QString result = formatStart.arg(list.at(0), list.at(1));
1401 for (qsizetype i = 2; i < size - 1; ++i)
1402 result = formatMid.arg(result, list.at(i));
1403 result = formatEnd.arg(result, list.at(size - 1));
1404 return result;
1405}
1406
1407/*!
1408 \nonreentrant
1409
1410 Sets the global default locale to \a locale.
1411
1412 This locale is used when a QLocale object is constructed with no
1413 arguments. If this function is not called, the system's locale is used.
1414
1415 \warning In a multithreaded application, the default locale should be set at
1416 application startup, before any non-GUI threads are created.
1417
1418 \sa system(), c()
1419*/
1420
1421void QLocale::setDefault(const QLocale &locale)
1422{
1423 default_data = locale.d->m_data;
1424
1425 if (defaultLocalePrivate.isDestroyed())
1426 return; // avoid crash on exit
1427 if (!defaultLocalePrivate.exists()) {
1428 // Force it to exist; see QTBUG-83016
1429 [[maybe_unused]] QLocale ignoreme;
1430 Q_ASSERT(defaultLocalePrivate.exists());
1431 }
1432
1433 // update the cached private
1434 *defaultLocalePrivate = locale.d;
1435 QLocalePrivate::s_generation.fetchAndAddRelaxed(1);
1436}
1437
1438/*!
1439 Returns the language of this locale.
1440
1441 \sa script(), territory(), languageToString(), bcp47Name()
1442*/
1443QLocale::Language QLocale::language() const
1444{
1445 return Language(d->languageId());
1446}
1447
1448/*!
1449 \since 4.8
1450
1451 Returns the script of this locale.
1452
1453 \sa language(), territory(), languageToString(), scriptToString(), bcp47Name()
1454*/
1455QLocale::Script QLocale::script() const
1456{
1457 return Script(d->m_data->m_script_id);
1458}
1459
1460/*!
1461 \since 6.2
1462
1463 Returns the territory of this locale.
1464
1465 \sa language(), script(), territoryToString(), bcp47Name()
1466*/
1467QLocale::Territory QLocale::territory() const
1468{
1469 return Territory(d->territoryId());
1470}
1471
1472#if QT_DEPRECATED_SINCE(6, 6)
1473/*!
1474 \deprecated [6.6] Use \l territory() instead.
1475
1476 Returns the territory of this locale.
1477
1478 \sa language(), script(), territoryToString(), bcp47Name()
1479*/
1480QLocale::Country QLocale::country() const
1481{
1482 return territory();
1483}
1484#endif
1485
1486/*!
1487 \since 6.7
1488 \enum QLocale::TagSeparator
1489
1490 Indicate how to combine the parts that make up a locale identifier.
1491
1492 A locale identifier may be made up of several tags, indicating language,
1493 script and territory (plus, potentially, other details), joined together to
1494 form the identifier. Various standards and conventional forms use either a
1495 dash (the Unicode HYPHEN-MINUS, U+002D) or an underscore (LOW LINE, U+005F).
1496 Different clients of QLocale may thus need one or the other.
1497
1498 \value Dash Use \c{'-'}, the dash or hyphen character.
1499 \value Underscore Use \c{'_'}, the underscore character.
1500
1501 \note Although dash and underscore are the only separators used in public
1502 standards (as at 2023), it is possible to cast any \l
1503 {https://en.cppreference.com/w/cpp/language/ascii} {ASCII} character to this
1504 type if a non-standard ASCII separator is needed. Casting a non-ASCII
1505 character (with decimal value above 127) is not supported: such values are
1506 reserved for future use as enum members if some public standard ever uses a
1507 non-ASCII separator. It is, of course, possible to use QString::replace() to
1508 replace the separator used by a function taking a parameter of this type
1509 with an arbitrary Unicode character or string.
1510*/
1511
1512Q_DECL_COLD_FUNCTION static void badSeparatorWarning(const char *method, char sep)
1513{
1514 qWarning("QLocale::%s(): Using non-ASCII separator '%c' (%02x) is unsupported",
1515 method, sep, uint(uchar(sep)));
1516}
1517
1518/*!
1519 \brief The short name of this locale.
1520
1521 Returns the language and territory of this locale as a string of the form
1522 "language_territory", where language is a lowercase, two-letter ISO 639
1523 language code, and territory is an uppercase, two- or three-letter ISO 3166
1524 territory code. If the locale has no specified territory, only the language
1525 name is returned. Since Qt 6.7 an optional \a separator parameter can be
1526 supplied to override the default underscore character separating the two
1527 tags.
1528
1529 Even if the QLocale object was constructed with an explicit script, name()
1530 will not contain it for compatibility reasons. Use \l bcp47Name() instead if
1531 you need a full locale name, or construct the string you want to identify a
1532 locale by from those returned by passing its \l language() to \l
1533 languageToCode() and similar for the script and territory.
1534
1535 \sa QLocale(), language(), script(), territory(), bcp47Name(), uiLanguages()
1536*/
1537
1538QString QLocale::name(TagSeparator separator) const
1539{
1540 const char sep = char(separator);
1541 if (uchar(sep) > 0x7f) {
1542 badSeparatorWarning("name", sep);
1543 return {};
1544 }
1545 const auto code = d->languageCode();
1546 QLatin1StringView view{code.data()};
1547
1548 Language l = language();
1549 if (l == C)
1550 return view;
1551
1552 Territory c = territory();
1553 if (c == AnyTerritory)
1554 return view;
1555
1556 return view + QLatin1Char(sep) + d->territoryCode();
1557}
1558
1559template <typename T> static inline
1560T toIntegral_helper(const QLocalePrivate *d, QStringView str, bool *ok)
1561{
1562 constexpr bool isUnsigned = std::is_unsigned_v<T>;
1563 using Int64 = typename std::conditional_t<isUnsigned, quint64, qint64>;
1564
1565 QSimpleParsedNumber<Int64> r{};
1566 if constexpr (isUnsigned)
1567 r = d->m_data->stringToUnsLongLong(str, 10, d->m_numberOptions);
1568 else
1569 r = d->m_data->stringToLongLong(str, 10, d->m_numberOptions);
1570
1571 if (ok)
1572 *ok = r.ok();
1573
1574 Int64 val = r.result;
1575 if (T(val) != val) {
1576 if (ok != nullptr)
1577 *ok = false;
1578 val = 0;
1579 }
1580 return T(val);
1581}
1582
1583
1584/*!
1585 \since 4.8
1586
1587 \brief Returns the BCP47 field names joined with dashes.
1588
1589 This combines as many of language, script and territory (and possibly other
1590 BCP47 fields) for this locale as are needed to uniquely specify it. Note
1591 that fields may be omitted if the Unicode consortium's \l {Matching
1592 combinations of language, script and territory}{Likely Subtag Rules} imply
1593 the omitted fields when given those retained. See \l name() for how to
1594 construct a string from individual fields, if some other format is needed.
1595
1596 Unlike uiLanguages(), the value returned by bcp47Name() represents the
1597 locale name of the QLocale data; this need not be the language the
1598 user-interface should be in.
1599
1600 This function tries to conform the locale name to the IETF Best Common
1601 Practice 47, defined by RFC 5646. Since Qt 6.7, it supports an optional \a
1602 separator parameter which can be used to override the BCP47-specified use of
1603 a hyphen to separate the tags. For use in IETF-defined protocols, however,
1604 the default, QLocale::TagSeparator::Dash, should be retained.
1605
1606 \sa name(), language(), territory(), script(), uiLanguages()
1607*/
1608QString QLocale::bcp47Name(TagSeparator separator) const
1609{
1610 const char sep = char(separator);
1611 if (uchar(sep) > 0x7f) {
1612 badSeparatorWarning("bcp47Name", sep);
1613 return {};
1614 }
1615 return QString::fromLatin1(d->bcp47Name(sep));
1616}
1617
1618/*!
1619 Returns the two- or three-letter language code for \a language, as defined
1620 in the ISO 639 standards.
1621
1622 If specified, \a codeTypes selects which set of codes to consider. The first
1623 code from the set that is defined for \a language is returned. Otherwise,
1624 all ISO-639 codes are considered. The codes are considered in the following
1625 order: \c ISO639Part1, \c ISO639Part2B, \c ISO639Part2T, \c ISO639Part3.
1626 \c LegacyLanguageCode is ignored by this function.
1627
1628 \note For \c{QLocale::C} the function returns \c{"C"}.
1629 For \c QLocale::AnyLanguage an empty string is returned.
1630 If the language has no code in any selected code set, an empty string
1631 is returned.
1632
1633 \since 6.3
1634 \sa codeToLanguage(), language(), name(), bcp47Name(), territoryToCode(), scriptToCode()
1635*/
1636QString QLocale::languageToCode(Language language, LanguageCodeTypes codeTypes)
1637{
1638 const auto code = QLocalePrivate::languageToCode(language, codeTypes);
1639 return QLatin1StringView{code.data()};
1640}
1641
1642/*!
1643 Returns the QLocale::Language enum corresponding to the two- or three-letter
1644 \a languageCode, as defined in the ISO 639 standards.
1645
1646 If specified, \a codeTypes selects which set of codes to consider for
1647 conversion. By default all codes known to Qt are considered. The codes are
1648 matched in the following order: \c ISO639Part1, \c ISO639Part2B,
1649 \c ISO639Part2T, \c ISO639Part3, \c LegacyLanguageCode.
1650
1651 If the code is invalid or not known \c QLocale::AnyLanguage is returned.
1652
1653 \since 6.3
1654 \sa languageToCode(), codeToTerritory(), codeToScript()
1655*/
1656QLocale::Language QLocale::codeToLanguage(QStringView languageCode,
1657 LanguageCodeTypes codeTypes) noexcept
1658{
1659 return QLocalePrivate::codeToLanguage(languageCode, codeTypes);
1660}
1661
1662/*!
1663 \since 6.2
1664
1665 Returns the two-letter territory code for \a territory, as defined
1666 in the ISO 3166 standard.
1667
1668 \note For \c{QLocale::AnyTerritory} an empty string is returned.
1669
1670 \sa codeToTerritory(), territory(), name(), bcp47Name(), languageToCode(), scriptToCode()
1671*/
1672QString QLocale::territoryToCode(QLocale::Territory territory)
1673{
1674 return QLocalePrivate::territoryToCode(territory);
1675}
1676
1677/*!
1678 \since 6.2
1679
1680 Returns the QLocale::Territory enum corresponding to the two-letter or
1681 three-digit \a territoryCode, as defined in the ISO 3166 standard.
1682
1683 If the code is invalid or not known QLocale::AnyTerritory is returned.
1684
1685 \sa territoryToCode(), codeToLanguage(), codeToScript()
1686*/
1687QLocale::Territory QLocale::codeToTerritory(QStringView territoryCode) noexcept
1688{
1689 return QLocalePrivate::codeToTerritory(territoryCode);
1690}
1691
1692#if QT_DEPRECATED_SINCE(6, 6)
1693/*!
1694 \deprecated [6.6] Use \l territoryToCode() instead.
1695
1696 Returns the two-letter territory code for \a country, as defined
1697 in the ISO 3166 standard.
1698
1699 \note For \c{QLocale::AnyTerritory} or \c{QLocale::AnyCountry} an empty string is returned.
1700
1701 \sa codeToTerritory(), territory(), name(), bcp47Name(), languageToCode(), scriptToCode()
1702*/
1703QString QLocale::countryToCode(Country country)
1704{
1705 return territoryToCode(country);
1706}
1707
1708/*!
1709 Returns the QLocale::Territory enum corresponding to the two-letter or
1710 three-digit \a countryCode, as defined in the ISO 3166 standard.
1711
1712 If the code is invalid or not known QLocale::AnyTerritory is returned.
1713
1714 \deprecated [6.6] Use codeToTerritory(QStringView) instead.
1715 \since 6.1
1716 \sa territoryToCode(), codeToLanguage(), codeToScript()
1717*/
1718QLocale::Country QLocale::codeToCountry(QStringView countryCode) noexcept
1719{
1720 return QLocalePrivate::codeToTerritory(countryCode);
1721}
1722#endif
1723
1724/*!
1725 Returns the four-letter script code for \a script, as defined in the
1726 ISO 15924 standard.
1727
1728 \note For \c{QLocale::AnyScript} an empty string is returned.
1729
1730 \since 6.1
1731 \sa script(), name(), bcp47Name(), languageToCode(), territoryToCode()
1732*/
1733QString QLocale::scriptToCode(Script script)
1734{
1735 return QLocalePrivate::scriptToCode(script);
1736}
1737
1738/*!
1739 Returns the QLocale::Script enum corresponding to the four-letter script
1740 \a scriptCode, as defined in the ISO 15924 standard.
1741
1742 If the code is invalid or not known QLocale::AnyScript is returned.
1743
1744 \since 6.1
1745 \sa scriptToCode(), codeToLanguage(), codeToTerritory()
1746*/
1747QLocale::Script QLocale::codeToScript(QStringView scriptCode) noexcept
1748{
1749 return QLocalePrivate::codeToScript(scriptCode);
1750}
1751
1752/*!
1753 Returns a QString containing the name of \a language.
1754
1755 \sa territoryToString(), scriptToString(), bcp47Name()
1756*/
1757
1758QString QLocale::languageToString(Language language)
1759{
1760 if (language > LastLanguage)
1761 return "Unknown"_L1;
1762 return QString::fromUtf8(language_name_list + language_name_index[language]);
1763}
1764
1765/*!
1766 \since 6.2
1767
1768 Returns a QString containing the name of \a territory.
1769
1770 \sa languageToString(), scriptToString(), territory(), bcp47Name()
1771*/
1772QString QLocale::territoryToString(Territory territory)
1773{
1774 if (territory > LastTerritory)
1775 return "Unknown"_L1;
1776 return QString::fromUtf8(territory_name_list + territory_name_index[territory]);
1777}
1778
1779#if QT_DEPRECATED_SINCE(6, 6)
1780/*!
1781 \deprecated [6.6] Use \l territoryToString() instead.
1782
1783 Returns a QString containing the name of \a country.
1784
1785 \sa languageToString(), scriptToString(), territory(), bcp47Name()
1786*/
1787QString QLocale::countryToString(Country country)
1788{
1789 return territoryToString(country);
1790}
1791#endif
1792
1793/*!
1794 \since 4.8
1795
1796 Returns a QString containing the name of \a script.
1797
1798 \sa languageToString(), territoryToString(), script(), bcp47Name()
1799*/
1800QString QLocale::scriptToString(Script script)
1801{
1802 if (script > LastScript)
1803 return "Unknown"_L1;
1804 return QString::fromUtf8(script_name_list + script_name_index[script]);
1805}
1806
1807/*!
1808 \fn short QLocale::toShort(const QString &s, bool *ok) const
1809
1810 Returns the short int represented by the localized string \a s.
1811
1812 If the conversion fails the function returns 0.
1813
1814 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1815 to \c false, and success by setting *\a{ok} to \c true.
1816
1817 This function ignores leading and trailing whitespace.
1818
1819 \sa toUShort(), toString()
1820*/
1821
1822/*!
1823 \fn ushort QLocale::toUShort(const QString &s, bool *ok) const
1824
1825 Returns the unsigned short int represented by the localized string \a s.
1826
1827 If the conversion fails the function returns 0.
1828
1829 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1830 to \c false, and success by setting *\a{ok} to \c true.
1831
1832 This function ignores leading and trailing whitespace.
1833
1834 \sa toShort(), toString()
1835*/
1836
1837/*!
1838 \fn int QLocale::toInt(const QString &s, bool *ok) const
1839 Returns the int represented by the localized string \a s.
1840
1841 If the conversion fails the function returns 0.
1842
1843 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1844 to \c false, and success by setting *\a{ok} to \c true.
1845
1846 This function ignores leading and trailing whitespace.
1847
1848 \sa toUInt(), toString()
1849*/
1850
1851/*!
1852 \fn uint QLocale::toUInt(const QString &s, bool *ok) const
1853 Returns the unsigned int represented by the localized string \a s.
1854
1855 If the conversion fails the function returns 0.
1856
1857 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1858 to \c false, and success by setting *\a{ok} to \c true.
1859
1860 This function ignores leading and trailing whitespace.
1861
1862 \sa toInt(), toString()
1863*/
1864
1865/*!
1866 \since 5.13
1867 \fn long QLocale::toLong(const QString &s, bool *ok) const
1868
1869 Returns the long int represented by the localized string \a s.
1870
1871 If the conversion fails the function returns 0.
1872
1873 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1874 to \c false, and success by setting *\a{ok} to \c true.
1875
1876 This function ignores leading and trailing whitespace.
1877
1878 \sa toInt(), toULong(), toDouble(), toString()
1879*/
1880
1881/*!
1882 \since 5.13
1883 \fn ulong QLocale::toULong(const QString &s, bool *ok) const
1884
1885 Returns the unsigned long int represented by the localized
1886 string \a s.
1887
1888 If the conversion fails the function returns 0.
1889
1890 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1891 to \c false, and success by setting *\a{ok} to \c true.
1892
1893 This function ignores leading and trailing whitespace.
1894
1895 \sa toLong(), toInt(), toDouble(), toString()
1896*/
1897
1898/*!
1899 \fn qlonglong QLocale::toLongLong(const QString &s, bool *ok) const
1900 Returns the long long int represented by the localized string \a s.
1901
1902 If the conversion fails the function returns 0.
1903
1904 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1905 to \c false, and success by setting *\a{ok} to \c true.
1906
1907 This function ignores leading and trailing whitespace.
1908
1909 \sa toInt(), toULongLong(), toDouble(), toString()
1910*/
1911
1912/*!
1913 \fn qulonglong QLocale::toULongLong(const QString &s, bool *ok) const
1914
1915 Returns the unsigned long long int represented by the localized
1916 string \a s.
1917
1918 If the conversion fails the function returns 0.
1919
1920 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1921 to \c false, and success by setting *\a{ok} to \c true.
1922
1923 This function ignores leading and trailing whitespace.
1924
1925 \sa toLongLong(), toInt(), toDouble(), toString()
1926*/
1927
1928/*!
1929 \fn float QLocale::toFloat(const QString &s, bool *ok) const
1930
1931 Returns the float represented by the localized string \a s.
1932
1933 Returns an infinity if the conversion overflows or 0.0 if the
1934 conversion fails for any other reason (e.g. underflow).
1935
1936 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1937 to \c false, and success by setting *\a{ok} to \c true.
1938
1939 This function ignores leading and trailing whitespace.
1940
1941 \sa toDouble(), toInt(), toString()
1942*/
1943
1944/*!
1945 \fn double QLocale::toDouble(const QString &s, bool *ok) const
1946 Returns the double represented by the localized string \a s.
1947
1948 Returns an infinity if the conversion overflows or 0.0 if the
1949 conversion fails for any other reason (e.g. underflow).
1950
1951 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1952 to \c false, and success by setting *\a{ok} to \c true.
1953
1954 \snippet code/src_corelib_text_qlocale.cpp 3
1955
1956 Notice that the last conversion returns 1234.0, because '.' is the
1957 thousands group separator in the German locale.
1958
1959 This function ignores leading and trailing whitespace.
1960
1961 \sa toFloat(), toInt(), toString()
1962*/
1963
1964/*!
1965 Returns the short int represented by the localized string \a s.
1966
1967 If the conversion fails, the function returns 0.
1968
1969 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1970 to \c false, and success by setting *\a{ok} to \c true.
1971
1972 This function ignores leading and trailing whitespace.
1973
1974 \sa toUShort(), toString()
1975
1976 \since 5.10
1977*/
1978
1979short QLocale::toShort(QStringView s, bool *ok) const
1980{
1981 return toIntegral_helper<short>(d, s, ok);
1982}
1983
1984/*!
1985 Returns the unsigned short int represented by the localized string \a s.
1986
1987 If the conversion fails, the function returns 0.
1988
1989 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
1990 to \c false, and success by setting *\a{ok} to \c true.
1991
1992 This function ignores leading and trailing whitespace.
1993
1994 \sa toShort(), toString()
1995
1996 \since 5.10
1997*/
1998
1999ushort QLocale::toUShort(QStringView s, bool *ok) const
2000{
2001 return toIntegral_helper<ushort>(d, s, ok);
2002}
2003
2004/*!
2005 Returns the int represented by the localized string \a s.
2006
2007 If the conversion fails, the function returns 0.
2008
2009 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
2010 to \c false, and success by setting *\a{ok} to \c true.
2011
2012 This function ignores leading and trailing whitespace.
2013
2014 \sa toUInt(), toString()
2015
2016 \since 5.10
2017*/
2018
2019int QLocale::toInt(QStringView s, bool *ok) const
2020{
2021 return toIntegral_helper<int>(d, s, ok);
2022}
2023
2024/*!
2025 Returns the unsigned int represented by the localized string \a s.
2026
2027 If the conversion fails, the function returns 0.
2028
2029 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
2030 to \c false, and success by setting *\a{ok} to \c true.
2031
2032 This function ignores leading and trailing whitespace.
2033
2034 \sa toInt(), toString()
2035
2036 \since 5.10
2037*/
2038
2039uint QLocale::toUInt(QStringView s, bool *ok) const
2040{
2041 return toIntegral_helper<uint>(d, s, ok);
2042}
2043
2044/*!
2045 \since 5.13
2046 Returns the long int represented by the localized string \a s.
2047
2048 If the conversion fails the function returns 0.
2049
2050 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
2051 to \c false, and success by setting *\a{ok} to \c true.
2052
2053 This function ignores leading and trailing whitespace.
2054
2055 \sa toInt(), toULong(), toDouble(), toString()
2056*/
2057
2058long QLocale::toLong(QStringView s, bool *ok) const
2059{
2060 return toIntegral_helper<long>(d, s, ok);
2061}
2062
2063/*!
2064 \since 5.13
2065 Returns the unsigned long int represented by the localized
2066 string \a s.
2067
2068 If the conversion fails the function returns 0.
2069
2070 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
2071 to \c false, and success by setting *\a{ok} to \c true.
2072
2073 This function ignores leading and trailing whitespace.
2074
2075 \sa toLong(), toInt(), toDouble(), toString()
2076*/
2077
2078ulong QLocale::toULong(QStringView s, bool *ok) const
2079{
2080 return toIntegral_helper<ulong>(d, s, ok);
2081}
2082
2083/*!
2084 Returns the long long int represented by the localized string \a s.
2085
2086 If the conversion fails, the function returns 0.
2087
2088 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
2089 to \c false, and success by setting *\a{ok} to \c true.
2090
2091 This function ignores leading and trailing whitespace.
2092
2093 \sa toInt(), toULongLong(), toDouble(), toString()
2094
2095 \since 5.10
2096*/
2097
2098
2099qlonglong QLocale::toLongLong(QStringView s, bool *ok) const
2100{
2101 return toIntegral_helper<qlonglong>(d, s, ok);
2102}
2103
2104/*!
2105 Returns the unsigned long long int represented by the localized
2106 string \a s.
2107
2108 If the conversion fails, the function returns 0.
2109
2110 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
2111 to \c false, and success by setting *\a{ok} to \c true.
2112
2113 This function ignores leading and trailing whitespace.
2114
2115 \sa toLongLong(), toInt(), toDouble(), toString()
2116
2117 \since 5.10
2118*/
2119
2120qulonglong QLocale::toULongLong(QStringView s, bool *ok) const
2121{
2122 return toIntegral_helper<qulonglong>(d, s, ok);
2123}
2124
2125/*!
2126 Returns the float represented by the localized string \a s.
2127
2128 Returns an infinity if the conversion overflows or 0.0 if the
2129 conversion fails for any other reason (e.g. underflow).
2130
2131 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
2132 to \c false, and success by setting *\a{ok} to \c true.
2133
2134 This function ignores leading and trailing whitespace.
2135
2136 \sa toDouble(), toInt(), toString()
2137
2138 \since 5.10
2139*/
2140
2141float QLocale::toFloat(QStringView s, bool *ok) const
2142{
2143 return QLocaleData::convertDoubleToFloat(toDouble(s, ok), ok);
2144}
2145
2146/*!
2147 Returns the double represented by the localized string \a s.
2148
2149 Returns an infinity if the conversion overflows or 0.0 if the
2150 conversion fails for any other reason (e.g. underflow).
2151
2152 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
2153 to \c false, and success by setting *\a{ok} to \c true.
2154
2155 \snippet code/src_corelib_text_qlocale.cpp 3-qstringview
2156
2157 Notice that the last conversion returns 1234.0, because '.' is the
2158 thousands group separator in the German locale.
2159
2160 This function ignores leading and trailing whitespace.
2161
2162 \sa toFloat(), toInt(), toString()
2163
2164 \since 5.10
2165*/
2166
2167double QLocale::toDouble(QStringView s, bool *ok) const
2168{
2169 return d->m_data->stringToDouble(s, ok, d->m_numberOptions);
2170}
2171
2172/*!
2173 Returns a localized string representation of \a i.
2174
2175 \sa toLongLong(), numberOptions(), zeroDigit(), positiveSign()
2176*/
2177
2178QString QLocale::toString(qlonglong i) const
2179{
2180 int flags = (d->m_numberOptions & OmitGroupSeparator
2181 ? 0 : QLocaleData::GroupDigits);
2182
2183 return d->m_data->longLongToString(i, -1, 10, -1, flags);
2184}
2185
2186/*!
2187 \overload
2188
2189 \sa toULongLong(), numberOptions(), zeroDigit(), positiveSign()
2190*/
2191
2192QString QLocale::toString(qulonglong i) const
2193{
2194 int flags = (d->m_numberOptions & OmitGroupSeparator
2195 ? 0 : QLocaleData::GroupDigits);
2196
2197 return d->m_data->unsLongLongToString(i, -1, 10, -1, flags);
2198}
2199// ### Incorrect way of calculating the width, will be fixed soon.
2200static qsizetype stringWidth(QStringView text)
2201{
2202 QStringIterator counter(text);
2203 qsizetype count = 0;
2204 while (counter.hasNext()) {
2205 ++count;
2206 [[maybe_unused]] auto ch = counter.next();
2207 }
2208 return count;
2209}
2210
2211static unsigned calculateFlags(int fieldWidth, char32_t fillChar,
2212 const QLocale &locale)
2213{
2214 unsigned flags = QLocaleData::NoFlags;
2215 if (!(locale.numberOptions() & QLocale::OmitGroupSeparator))
2216 flags |= QLocaleData::GroupDigits;
2217 if (fieldWidth < 0)
2219 else if (fillChar == U'0')
2220 flags |= QLocaleData::ZeroPadded;
2221
2222 return flags;
2223}
2224
2225static QString calculateFiller(qsizetype padding,
2226 char32_t fillChar,
2227 [[maybe_unused]] qsizetype fieldWidth,
2228 const QLocaleData *localeData)
2229{
2230 QString filler;
2231 if (fillChar == U'0') {
2232 Q_ASSERT(fieldWidth < 0);
2233 filler = localeData->zeroDigit();
2234 } else {
2235 filler = QString(QChar::fromUcs4(fillChar));
2236 }
2237 // ### size is not width
2238 if (padding > 1)
2239 filler = filler.repeated(padding);
2240 return filler;
2241}
2242
2243/*!
2244 \fn QString QLocale::toString(short number, int fieldWidth, char32_t fillChar) const
2245 \fn QString QLocale::toString(int number, int fieldWidth, char32_t fillChar) const
2246 \fn QString QLocale::toString(long number, int fieldWidth, char32_t fillChar) const
2247 \include qlocale.cpp tostring-with-padding
2248 \include qlocale.cpp tostring-signed-padding
2249*/
2250/*!
2251//! [tostring-with-padding]
2252 Returns a string representation of the given \a number.
2253
2254 The string's length shall be at least the absolute value of \a fieldWidth,
2255 using \a fillChar as padding if the \a number has fewer digits. If
2256 \a fillChar is \c{'0'} the zero digit of this locale is used as padding.
2257 If \a fieldWidth is negative the string starts with its representation
2258 of \a number and, if shorter, is padded to length \c{-fieldWidth} with
2259 the given \a fillChar. For positive fieldWidth, the padding appears before
2260 the representation of \a number.
2261//! [tostring-with-padding]
2262//! [tostring-signed-padding]
2263 When the \a number is negative and \a fieldWidth is positive, if
2264 \a fillChar is a \c{'0'} the padding is inserted between this locale's
2265 minus sign and the start of the number's digits.
2266 \overload toString()
2267//! [tostring-signed-padding]
2268 */
2269QString QLocale::toString(qlonglong number, int fieldWidth, char32_t fillChar) const
2270{
2271 int absFieldWidth = qAbs(fieldWidth);
2272 int width = (fillChar == U'0') ? absFieldWidth : -1;
2273 unsigned flags = calculateFlags(fieldWidth, fillChar, *this);
2274
2275 QString result = d->m_data->longLongToString(number, -1, 10, width, flags);
2276 qsizetype padding = absFieldWidth - stringWidth(result);
2277
2278 if (padding > 0) {
2279 QString filler = calculateFiller(padding, fillChar, fieldWidth, d->m_data);
2280 if (fieldWidth < 0)
2281 result.append(filler);
2282 else
2283 result.prepend(filler);
2284 }
2285 return result;
2286}
2287
2288/*!
2289 \fn QString QLocale::toString(ushort number, int fieldWidth, char32_t fillChar) const
2290 \fn QString QLocale::toString(uint number, int fieldWidth, char32_t fillChar) const
2291 \fn QString QLocale::toString(ulong number, int fieldWidth, char32_t fillChar) const
2292 \include qlocale.cpp tostring-with-padding
2293 \overload toString()
2294 */
2295/*!
2296 \include qlocale.cpp tostring-with-padding
2297 \overload toString()
2298 */
2299QString QLocale::toString(qulonglong number, int fieldWidth, char32_t fillChar) const
2300{
2301 int absFieldWidth = qAbs(fieldWidth);
2302 int width = (fillChar == U'0') ? absFieldWidth : -1;
2303 unsigned flags = calculateFlags(fieldWidth, fillChar, *this);
2304
2305 QString result = d->m_data->unsLongLongToString(number, -1, 10, width, flags);
2306 qsizetype padding = absFieldWidth - stringWidth(result);
2307
2308 if (padding > 0) {
2309 QString filler = calculateFiller(padding, fillChar, fieldWidth, d->m_data);
2310 if (fieldWidth < 0)
2311 result.append(filler);
2312 else
2313 result.prepend(filler);
2314 }
2315 return result;
2316}
2317
2318/*!
2319 \overload
2320*/
2321
2322QString QLocale::toString(QDate date, const QString &format) const
2323{
2324 return toString(date, qToStringViewIgnoringNull(format));
2325}
2326
2327/*!
2328 \overload
2329 Returns a localized string representation of the given \a time according
2330 to the specified \a format (see QTime::toString()).
2331
2332 If \a format is an empty string, an empty string is returned.
2333
2334 \sa dateFormat(), QTime::toString()
2335*/
2336
2337QString QLocale::toString(QTime time, const QString &format) const
2338{
2339 return toString(time, qToStringViewIgnoringNull(format));
2340}
2341
2342/*!
2343 \since 4.4
2344 \fn QString QLocale::toString(const QDateTime &dateTime, const QString &format) const
2345 \overload
2346*/
2347
2348/*!
2349 \since 5.14
2350 \overload
2351
2352 Returns a localized string representation of the given \a date in the
2353 specified \a format (see QDate::toString()), optionally for a specified
2354 calendar \a cal.
2355
2356 If \a format is an empty string, an empty string is returned.
2357
2358 \sa dateFormat(), QDate::toString()
2359*/
2360QString QLocale::toString(QDate date, QStringView format, QCalendar cal) const
2361{
2362 return cal.dateTimeToString(format, QDateTime(), date, QTime(), *this);
2363}
2364
2365/*!
2366 \since 5.10
2367 \overload
2368*/
2369QString QLocale::toString(QDate date, QStringView format) const
2370{
2371 return QCalendar().dateTimeToString(format, QDateTime(), date, QTime(), *this);
2372}
2373
2374/*!
2375 \since 5.14
2376
2377 Returns a localized string representation of the given \a date according to
2378 the specified \a format (see dateFormat()), optionally for a specified
2379 calendar \a cal.
2380
2381 \note Some locales may use formats that limit the range of years they can
2382 represent. Some locales' use of two-digit years may lead to ambiguity.
2383*/
2384QString QLocale::toString(QDate date, FormatType format, QCalendar cal) const
2385{
2386 if (!date.isValid())
2387 return QString();
2388
2389#ifndef QT_NO_SYSTEMLOCALE
2390 if (cal.isGregorian() && d->m_data == &systemLocaleData) {
2391 QVariant res = systemLocale()->query(format == LongFormat
2392 ? QSystemLocale::DateToStringLong
2393 : QSystemLocale::DateToStringShort,
2394 date);
2395 if (!res.isNull())
2396 return res.toString();
2397 }
2398#endif
2399
2400 QString format_str = dateFormat(format);
2401 return toString(date, format_str, cal);
2402}
2403
2404/*!
2405 \since 4.5
2406 \overload
2407*/
2408QString QLocale::toString(QDate date, FormatType format) const
2409{
2410 if (!date.isValid())
2411 return QString();
2412
2413#ifndef QT_NO_SYSTEMLOCALE
2414 if (d->m_data == &systemLocaleData) {
2415 QVariant res = systemLocale()->query(format == LongFormat
2416 ? QSystemLocale::DateToStringLong
2417 : QSystemLocale::DateToStringShort,
2418 date);
2419 if (!res.isNull())
2420 return res.toString();
2421 }
2422#endif
2423
2424 QString format_str = dateFormat(format);
2425 return toString(date, format_str);
2426}
2427
2428static bool timeFormatContainsAP(QStringView format)
2429{
2430 qsizetype i = 0;
2431 while (i < format.size()) {
2432 if (format.at(i).unicode() == '\'') {
2433 qt_readEscapedFormatString(format, &i);
2434 continue;
2435 }
2436
2437 if (format.at(i).toLower().unicode() == 'a')
2438 return true;
2439
2440 ++i;
2441 }
2442 return false;
2443}
2444
2445/*!
2446 \since 4.5
2447 \overload
2448*/
2449QString QLocale::toString(QTime time, QStringView format) const
2450{
2451 return QCalendar().dateTimeToString(format, QDateTime(), QDate(), time, *this);
2452}
2453
2454/*!
2455 \since 5.14
2456
2457 Returns a localized string representation of the given \a dateTime according
2458 to the specified \a format (see QDateTime::toString()), optionally for a
2459 specified calendar \a cal.
2460
2461 If \a format is an empty string, an empty string is returned.
2462
2463 \sa QDateTime::toString(), QDate::toString(), QTime::toString()
2464*/
2465QString QLocale::toString(const QDateTime &dateTime, QStringView format, QCalendar cal) const
2466{
2467 return cal.dateTimeToString(format, dateTime, QDate(), QTime(), *this);
2468}
2469
2470/*!
2471 \since 5.10
2472 \overload
2473*/
2474QString QLocale::toString(const QDateTime &dateTime, QStringView format) const
2475{
2476 return QCalendar().dateTimeToString(format, dateTime, QDate(), QTime(), *this);
2477}
2478
2479/*!
2480 \since 5.14
2481
2482 Returns a localized string representation of the given \a dateTime according
2483 to the specified \a format (see dateTimeFormat()), optionally for a
2484 specified calendar \a cal.
2485
2486 \note Some locales may use formats that limit the range of years they can
2487 represent. Some locales' use of two-digit years may lead to ambiguity.
2488*/
2489QString QLocale::toString(const QDateTime &dateTime, FormatType format, QCalendar cal) const
2490{
2491 if (!dateTime.isValid())
2492 return QString();
2493
2494#ifndef QT_NO_SYSTEMLOCALE
2495 if (cal.isGregorian() && d->m_data == &systemLocaleData) {
2496 QVariant res = systemLocale()->query(format == LongFormat
2497 ? QSystemLocale::DateTimeToStringLong
2498 : QSystemLocale::DateTimeToStringShort,
2499 dateTime);
2500 if (!res.isNull())
2501 return res.toString();
2502 }
2503#endif
2504
2505 const QString format_str = dateTimeFormat(format);
2506 return toString(dateTime, format_str, cal);
2507}
2508
2509/*!
2510 \since 4.4
2511 \overload
2512*/
2513QString QLocale::toString(const QDateTime &dateTime, FormatType format) const
2514{
2515 if (!dateTime.isValid())
2516 return QString();
2517
2518#ifndef QT_NO_SYSTEMLOCALE
2519 if (d->m_data == &systemLocaleData) {
2520 QVariant res = systemLocale()->query(format == LongFormat
2521 ? QSystemLocale::DateTimeToStringLong
2522 : QSystemLocale::DateTimeToStringShort,
2523 dateTime);
2524 if (!res.isNull())
2525 return res.toString();
2526 }
2527#endif
2528
2529 const QString format_str = dateTimeFormat(format);
2530 return toString(dateTime, format_str);
2531}
2532
2533
2534/*!
2535 Returns a localized string representation of the given \a time in the
2536 specified \a format (see timeFormat()).
2537*/
2538
2539QString QLocale::toString(QTime time, FormatType format) const
2540{
2541 if (!time.isValid())
2542 return QString();
2543
2544#ifndef QT_NO_SYSTEMLOCALE
2545 if (d->m_data == &systemLocaleData) {
2546 QVariant res = systemLocale()->query(format == LongFormat
2547 ? QSystemLocale::TimeToStringLong
2548 : QSystemLocale::TimeToStringShort,
2549 time);
2550 if (!res.isNull())
2551 return res.toString();
2552 }
2553#endif
2554
2555 QString format_str = timeFormat(format);
2556 return toString(time, format_str);
2557}
2558
2559/*!
2560 \since 4.1
2561
2562 Returns the date format used for the current locale.
2563
2564 If \a format is LongFormat, the format will be elaborate, otherwise it will be short.
2565 For example, LongFormat for the \c{en_US} locale is \c{dddd, MMMM d, yyyy},
2566 ShortFormat is \c{M/d/yy}.
2567
2568 \sa QDate::toString(), QDate::fromString()
2569*/
2570
2571QString QLocale::dateFormat(FormatType format) const
2572{
2573#ifndef QT_NO_SYSTEMLOCALE
2574 if (d->m_data == &systemLocaleData) {
2575 QVariant res = systemLocale()->query(format == LongFormat
2576 ? QSystemLocale::DateFormatLong
2577 : QSystemLocale::DateFormatShort,
2578 QVariant());
2579 if (!res.isNull())
2580 return res.toString();
2581 }
2582#endif
2583
2584 return (format == LongFormat
2585 ? d->m_data->longDateFormat()
2586 : d->m_data->shortDateFormat()
2587 ).getData(date_format_data);
2588}
2589
2590/*!
2591 \since 4.1
2592
2593 Returns the time format used for the current locale.
2594
2595 If \a format is LongFormat, the format will be elaborate, otherwise it will be short.
2596 For example, LongFormat for the \c{en_US} locale is \c{h:mm:ss AP t},
2597 ShortFormat is \c{h:mm AP}.
2598
2599 \sa QTime::toString(), QTime::fromString()
2600*/
2601
2602QString QLocale::timeFormat(FormatType format) const
2603{
2604#ifndef QT_NO_SYSTEMLOCALE
2605 if (d->m_data == &systemLocaleData) {
2606 QVariant res = systemLocale()->query(format == LongFormat
2607 ? QSystemLocale::TimeFormatLong
2608 : QSystemLocale::TimeFormatShort,
2609 QVariant());
2610 if (!res.isNull())
2611 return res.toString();
2612 }
2613#endif
2614
2615 return (format == LongFormat
2616 ? d->m_data->longTimeFormat()
2617 : d->m_data->shortTimeFormat()
2618 ).getData(time_format_data);
2619}
2620
2621/*!
2622 \since 4.4
2623
2624 Returns the date time format used for the current locale.
2625
2626 If \a format is LongFormat, the format will be elaborate, otherwise it will be short.
2627 For example, LongFormat for the \c{en_US} locale is \c{dddd, MMMM d, yyyy h:mm:ss AP t},
2628 ShortFormat is \c{M/d/yy h:mm AP}.
2629
2630 \sa QDateTime::toString(), QDateTime::fromString()
2631*/
2632
2633QString QLocale::dateTimeFormat(FormatType format) const
2634{
2635#ifndef QT_NO_SYSTEMLOCALE
2636 if (d->m_data == &systemLocaleData) {
2637 QVariant res = systemLocale()->query(format == LongFormat
2638 ? QSystemLocale::DateTimeFormatLong
2639 : QSystemLocale::DateTimeFormatShort,
2640 QVariant());
2641 if (!res.isNull()) {
2642 return res.toString();
2643 }
2644 }
2645#endif
2646 return dateFormat(format) + u' ' + timeFormat(format);
2647}
2648
2649#if QT_CONFIG(datestring)
2650/*!
2651 \since 4.4
2652
2653 Reads \a string as a time in a locale-specific \a format.
2654
2655 Parses \a string and returns the time it represents. The format of the time
2656 string is chosen according to the \a format parameter (see timeFormat()).
2657
2658 \note Any am/pm indicators used must match \l amText() or \l pmText(),
2659 ignoring case.
2660
2661 If the time could not be parsed, returns an invalid time.
2662
2663 \sa timeFormat(), toDate(), toDateTime(), QTime::fromString()
2664*/
2665QTime QLocale::toTime(const QString &string, FormatType format) const
2666{
2667 return toTime(string, timeFormat(format));
2668}
2669
2670/*!
2671 \since 4.4
2672
2673 Reads \a string as a date in a locale-specific \a format.
2674
2675 Parses \a string and returns the date it represents. The format of the date
2676 string is chosen according to the \a format parameter (see dateFormat()).
2677
2678//! [base-year-for-short]
2679 Some locales use, particularly for ShortFormat, only the last two digits of
2680 the year. In such a case, the 100 years starting at \a baseYear are the
2681 candidates first considered. Prior to 6.7 there was no \a baseYear parameter
2682 and 1900 was always used. This is the default for \a baseYear, selecting a
2683 year from then to 1999. In some cases, other fields may lead to the next or
2684 previous century being selected, to get a result consistent with all fields
2685 given. See \l QDate::fromString() for details.
2686//! [base-year-for-short]
2687
2688 \note Month and day names, where used, must be given in the locale's
2689 language.
2690
2691 If the date could not be parsed, returns an invalid date.
2692
2693 \sa dateFormat(), toTime(), toDateTime(), QDate::fromString()
2694*/
2695QDate QLocale::toDate(const QString &string, FormatType format, int baseYear) const
2696{
2697 return toDate(string, dateFormat(format), baseYear);
2698}
2699
2700/*!
2701 \since 5.14
2702 \overload
2703*/
2704QDate QLocale::toDate(const QString &string, FormatType format, QCalendar cal, int baseYear) const
2705{
2706 return toDate(string, dateFormat(format), cal, baseYear);
2707}
2708
2709/*!
2710 \since 4.4
2711
2712 Reads \a string as a date-time in a locale-specific \a format.
2713
2714 Parses \a string and returns the date-time it represents. The format of the
2715 date string is chosen according to the \a format parameter (see
2716 dateFormat()).
2717
2718 \include qlocale.cpp base-year-for-short
2719
2720 \note Month and day names, where used, must be given in the locale's
2721 language. Any am/pm indicators used must match \l amText() or \l pmText(),
2722 ignoring case.
2723
2724 If the string could not be parsed, returns an invalid QDateTime.
2725
2726 \sa dateTimeFormat(), toTime(), toDate(), QDateTime::fromString()
2727*/
2728QDateTime QLocale::toDateTime(const QString &string, FormatType format, int baseYear) const
2729{
2730 return toDateTime(string, dateTimeFormat(format), baseYear);
2731}
2732
2733/*!
2734 \since 5.14
2735 \overload
2736*/
2737QDateTime QLocale::toDateTime(const QString &string, FormatType format, QCalendar cal,
2738 int baseYear) const
2739{
2740 return toDateTime(string, dateTimeFormat(format), cal, baseYear);
2741}
2742
2743/*!
2744 \since 4.4
2745
2746 Reads \a string as a time in the given \a format.
2747
2748 Parses \a string and returns the time it represents. See QTime::fromString()
2749 for the interpretation of \a format.
2750
2751 \note Any am/pm indicators used must match \l amText() or \l pmText(),
2752 ignoring case.
2753
2754 If \a format is malformed or \a string does not match it, returns an invalid
2755 time.
2756
2757 \sa timeFormat(), toDate(), toDateTime(), QTime::fromString()
2758*/
2759QTime QLocale::toTime(const QString &string, const QString &format) const
2760{
2761#if QT_CONFIG(datetimeparser)
2762 QTimePattern pattern = QTimePattern::fromQtFormat(format);
2763 if (pattern.isNull() && !format.isEmpty())
2764 return {};
2765 pattern.setLocale(*this);
2766 if (auto match = pattern.parse(string, QTime(0, 0)); match.size == string.size())
2767 return std::move(match.payload);
2768#else
2769 Q_UNUSED(string);
2770 Q_UNUSED(format);
2771#endif
2772 return {};
2773}
2774
2775/*!
2776 \since 4.4
2777
2778 Reads \a string as a date in the given \a format.
2779
2780 Parses \a string and returns the date it represents. See QDate::fromString()
2781 for the interpretation of \a format.
2782
2783//! [base-year-for-two-digit]
2784 When \a format only specifies the last two digits of a year, the 100 years
2785 starting at \a baseYear are the candidates first considered. Prior to 6.7
2786 there was no \a baseYear parameter and 1900 was always used. This is the
2787 default for \a baseYear, selecting a year from then to 1999. In some cases,
2788 other fields may lead to the next or previous century being selected, to get
2789 a result consistent with all fields given. See \l QDate::fromString() for
2790 details.
2791//! [base-year-for-two-digit]
2792
2793 \note Month and day names, where used, must be given in the locale's
2794 language.
2795
2796 If \a format is malformed or \a string does not match it, returns an invalid
2797 date.
2798
2799 \sa dateFormat(), toTime(), toDateTime(), QDate::fromString()
2800*/
2801QDate QLocale::toDate(const QString &string, const QString &format, int baseYear) const
2802{
2803 return toDate(string, format, QCalendar(), baseYear);
2804}
2805
2806/*!
2807 \since 5.14
2808 \overload
2809*/
2810QDate QLocale::toDate(const QString &string, const QString &format, QCalendar cal, int baseYear) const
2811{
2812#if QT_CONFIG(datetimeparser)
2813 QDatePattern pattern = QDatePattern::fromQtFormat(format);
2814 if (pattern.isNull() && !format.isEmpty())
2815 return {};
2816 pattern.setLocale(*this);
2817 pattern.setCalendar(cal);
2818 pattern.setBaseYear(baseYear);
2819 if (auto match = pattern.parse(string, QDate(baseYear, 1, 1, cal));
2820 match.size == string.size()) {
2821 return std::move(match.payload);
2822 }
2823#else
2824 Q_UNUSED(string);
2825 Q_UNUSED(format);
2826 Q_UNUSED(cal);
2827 Q_UNUSED(baseYear);
2828#endif
2829 return {};
2830}
2831
2832/*!
2833 \since 4.4
2834
2835 Reads \a string as a date-time in the given \a format.
2836
2837 Parses \a string and returns the date-time it represents. See
2838 QDateTime::fromString() for the interpretation of \a format.
2839
2840 \include qlocale.cpp base-year-for-two-digit
2841
2842 \note Month and day names, where used, must be given in the locale's
2843 language. Any am/pm indicators used must match \l amText() or \l pmText(),
2844 ignoring case.
2845
2846 If \a format is invalid or \a string does not match it, returns an invalid
2847 QDateTime.
2848
2849 If the string can be parsed and represents an invalid date-time (for
2850 example, in a gap skipped by a time-zone transition), the returned QDateTime
2851 represents a nearby datetime that is valid (typically differing from it by
2852 the width of the gap in valid datetimes - in the example given, the hour
2853 skipped by a transition).
2854
2855 \sa dateTimeFormat(), toTime(), toDate(), QDateTime::fromString()
2856*/
2857QDateTime QLocale::toDateTime(const QString &string, const QString &format, int baseYear) const
2858{
2859 return toDateTime(string, format, QCalendar(), baseYear);
2860}
2861
2862/*!
2863 \since 5.14
2864 \overload
2865*/
2866QDateTime QLocale::toDateTime(const QString &string, const QString &format, QCalendar cal,
2867 int baseYear) const
2868{
2869#if QT_CONFIG(datetimeparser)
2870 QDateTimePattern pattern = QDateTimePattern::fromQtFormat(format);
2871 if (pattern.isNull() && !format.isEmpty())
2872 return {};
2873 pattern.setLocale(*this);
2874 pattern.setCalendar(cal);
2875 pattern.setBaseYear(baseYear);
2876 if (auto match = pattern.parse(string, QDate(baseYear, 1, 1, cal).startOfDay());
2877 match.size == string.size()) {
2878 return std::move(match.payload);
2879 }
2880#else
2881 Q_UNUSED(string);
2882 Q_UNUSED(format);
2883 Q_UNUSED(cal);
2884 Q_UNUSED(baseYear);
2885#endif
2886 return {};
2887}
2888#endif // datestring
2889
2890/*!
2891 \since 4.1
2892
2893 Returns the fractional part separator for this locale.
2894
2895 This is the token that separates the whole number part from the fracional
2896 part in the representation of a number which has a fractional part. This is
2897 commonly called the "decimal point character" - even though, in many
2898 locales, it is not a "point" (or similar dot). It is (since Qt 6.0) returned
2899 as a string in case some locale needs more than one UTF-16 code-point to
2900 represent its separator.
2901
2902 \sa groupSeparator(), toString()
2903*/
2904QString QLocale::decimalPoint() const
2905{
2906 return d->m_data->decimalPoint();
2907}
2908
2909/*!
2910 \since 4.1
2911
2912 Returns the digit-grouping separator for this locale.
2913
2914 This is a token used to break up long sequences of digits, in the
2915 representation of a number, to make it easier to read. In some locales it
2916 may be empty, indicating that digits should not be broken up into groups in
2917 this way. In others it may be a spacing character. It is (since Qt 6.0)
2918 returned as a string in case some locale needs more than one UTF-16
2919 code-point to represent its separator.
2920
2921 \sa decimalPoint(), toString()
2922*/
2923QString QLocale::groupSeparator() const
2924{
2925 return d->m_data->groupSeparator();
2926}
2927
2928/*!
2929 \since 4.1
2930
2931 Returns the percent marker of this locale.
2932
2933 This is a token presumed to be appended to a number to indicate a
2934 percentage. It is (since Qt 6.0) returned as a string because, in some
2935 locales, it is not a single character - for example, because it includes a
2936 text-direction-control character.
2937
2938 \sa toString()
2939*/
2940QString QLocale::percent() const
2941{
2942 return d->m_data->percentSign();
2943}
2944
2945/*!
2946 \since 4.1
2947
2948 Returns the zero digit character of this locale.
2949
2950 This is a single Unicode character but may be encoded as a surrogate pair,
2951 so is (since Qt 6.0) returned as a string. In most locales, other digits
2952 follow it in Unicode ordering - however, some number systems, notably those
2953 using U+3007 as zero, do not have contiguous digits. Use toString() to
2954 obtain suitable representations of numbers, rather than trying to construct
2955 them from this zero digit.
2956
2957 \sa toString()
2958*/
2959QString QLocale::zeroDigit() const
2960{
2961 return d->m_data->zeroDigit();
2962}
2963
2964/*!
2965 \since 4.1
2966
2967 Returns the negative sign indicator of this locale.
2968
2969 This is a token presumed to be used as a prefix to a number to indicate that
2970 it is negative. It is (since Qt 6.0) returned as a string because, in some
2971 locales, it is not a single character - for example, because it includes a
2972 text-direction-control character.
2973
2974 \sa positiveSign(), toString()
2975*/
2976QString QLocale::negativeSign() const
2977{
2978 return d->m_data->negativeSign();
2979}
2980
2981/*!
2982 \since 4.5
2983
2984 Returns the positive sign indicator of this locale.
2985
2986 This is a token presumed to be used as a prefix to a number to indicate that
2987 it is positive. It is (since Qt 6.0) returned as a string because, in some
2988 locales, it is not a single character - for example, because it includes a
2989 text-direction-control character.
2990
2991 \sa negativeSign(), toString()
2992*/
2993QString QLocale::positiveSign() const
2994{
2995 return d->m_data->positiveSign();
2996}
2997
2998/*!
2999 \since 4.1
3000
3001 Returns the exponent separator for this locale.
3002
3003 This is a token used to separate mantissa from exponent in some
3004 floating-point numeric representations. It is (since Qt 6.0) returned as a
3005 string because, in some locales, it is not a single character - for example,
3006 it may consist of a multiplication sign and a representation of the "ten to
3007 the power" operator.
3008
3009 \sa toString(double, char, int)
3010*/
3011QString QLocale::exponential() const
3012{
3013 return d->m_data->exponentSeparator();
3014}
3015
3016/*!
3017 \overload
3018 Returns a string representing the floating-point number \a f.
3019
3020 The form of the representation is controlled by the \a format and \a
3021 precision parameters.
3022
3023 The \a format defaults to \c{'g'}. It can be any of the following:
3024
3025 \table
3026 \header \li Format \li Meaning \li Meaning of \a precision
3027 \row \li \c 'e' \li format as [-]9.9e[+|-]999 \li number of digits \e after the decimal point
3028 \row \li \c 'E' \li format as [-]9.9E[+|-]999 \li "
3029 \row \li \c 'f' \li format as [-]9.9 \li "
3030 \row \li \c 'F' \li same as \c 'f' except for INF and NAN (see below) \li "
3031 \row \li \c 'g' \li use \c 'e' or \c 'f' format, whichever is more concise \li maximum number of significant digits (trailing zeroes are omitted)
3032 \row \li \c 'G' \li use \c 'E' or \c 'F' format, whichever is more concise \li "
3033 \endtable
3034
3035 The special \a precision value QLocale::FloatingPointShortest selects the
3036 shortest representation that, when read as a number, gets back the original floating-point
3037 value. Aside from that, any negative \a precision is ignored in favor of the
3038 default, 6.
3039
3040 For the \c 'e', \c 'f' and \c 'g' formats, positive infinity is represented
3041 as "inf", negative infinity as "-inf" and floating-point NaN (not-a-number)
3042 values are represented as "nan". For the \c 'E', \c 'F' and \c 'G' formats,
3043 "INF" and "NAN" are used instead. This does not vary with locale.
3044
3045 \sa toDouble(), numberOptions(), exponential(), decimalPoint(), zeroDigit(),
3046 positiveSign(), percent(), toCurrencyString(), formattedDataSize(),
3047 QLocale::FloatingPointPrecisionOption
3048*/
3049
3050QString QLocale::toString(double f, char format, int precision) const
3051{
3052 QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
3053 uint flags = isAsciiUpper(format) ? QLocaleData::CapitalEorX : 0;
3054
3055 switch (QtMiscUtils::toAsciiLower(format)) {
3056 case 'f':
3057 form = QLocaleData::DFDecimal;
3058 break;
3059 case 'e':
3060 form = QLocaleData::DFExponent;
3061 break;
3062 case 'g':
3063 form = QLocaleData::DFSignificantDigits;
3064 break;
3065 default:
3066 break;
3067 }
3068
3069 if (!(d->m_numberOptions & OmitGroupSeparator))
3070 flags |= QLocaleData::GroupDigits;
3071 if (!(d->m_numberOptions & OmitLeadingZeroInExponent))
3072 flags |= QLocaleData::ZeroPadExponent;
3073 if (d->m_numberOptions & IncludeTrailingZeroesAfterDot)
3074 flags |= QLocaleData::AddTrailingZeroes;
3075 return d->m_data->doubleToString(f, precision, form, -1, flags);
3076}
3077
3078/*!
3079 Returns a QLocale object initialized to the "C" locale.
3080
3081 This locale is based on en_US but with various quirks of its own, such as
3082 simplified number formatting and its own date formatting. It implements the
3083 POSIX standards that describe the behavior of standard library functions of
3084 the "C" programming language.
3085
3086 Among other things, this means its collation order is based on the ASCII
3087 values of letters, so that (for case-sensitive sorting) all upper-case
3088 letters sort before any lower-case one (rather than each letter's upper- and
3089 lower-case forms sorting adjacent to one another, before the next letter's
3090 two forms).
3091
3092 \sa system()
3093*/
3094QLocale QLocale::c() noexcept
3095{
3096 return QLocale(*c_private());
3097}
3098
3099/*!
3100 Returns a QLocale object initialized to the system locale.
3101
3102 The system locale may use system-specific sources for locale data, where
3103 available, otherwise falling back on QLocale's built-in database entry for
3104 the language, script and territory the system reports.
3105
3106 For example, on Windows and Mac, this locale will use the decimal/grouping
3107 characters and date/time formats specified in the system configuration
3108 panel.
3109
3110 \sa c()
3111*/
3112
3113QLocale QLocale::system()
3114{
3115 constexpr auto sysData = []() {
3116 // Same return as systemData(), but leave the setup to the actual call to it.
3117#ifdef QT_NO_SYSTEMLOCALE
3118 return locale_data;
3119#else
3120 return &systemLocaleData;
3121#endif
3122 };
3123 Q_CONSTINIT static QLocalePrivate locale(sysData(), -1, DefaultNumberOptions, 1);
3124 // Calling systemData() ensures system data is up to date; we also need it
3125 // to ensure that locale's index stays up to date:
3126 systemData(&locale.m_index);
3127 Q_ASSERT(locale.m_index >= 0 && locale.m_index < locale_data_size);
3128 locale.m_numberOptions = defaultNumberOptions(locale.m_data->m_language_id);
3129
3130 return QLocale(locale);
3131}
3132
3133/*!
3134 Returns a list of valid locale objects that match the given \a language, \a
3135 script and \a territory.
3136
3137 Getting a list of all locales:
3138 QList<QLocale> allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript,
3139 QLocale::AnyTerritory);
3140
3141 Getting a list of locales suitable for Russia:
3142 QList<QLocale> locales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript,
3143 QLocale::Russia);
3144*/
3145QList<QLocale> QLocale::matchingLocales(Language language, Script script, Territory territory)
3146{
3147 QList<QLocale> result;
3148
3149 const QLocaleId filter { language, script, territory };
3150 if (!filter.isValid())
3151 return result;
3152
3153 if (language == C) {
3154 result.emplace_back(C);
3155 return result;
3156 }
3157
3158 if (filter.matchesAll())
3159 result.reserve(locale_data_size);
3160
3161 quint16 index = locale_index[language];
3162 // There may be no matches, for some languages (e.g. Abkhazian at CLDR v39).
3163 while (index < locale_data_size
3164 && filter.acceptLanguage(locale_data[index].m_language_id)) {
3165 const QLocaleId id = locale_data[index].id();
3166 if (filter.acceptScriptTerritory(id)) {
3167 result.append(QLocale(*(id.language_id == C ? c_private()
3168 : new QLocalePrivate(locale_data + index, index))));
3169 }
3170 ++index;
3171 }
3172
3173 // Add current system locale, if it matches
3174 const auto syslocaledata = systemData();
3175
3176 if (filter.acceptLanguage(syslocaledata->m_language_id)) {
3177 const QLocaleId id = syslocaledata->id();
3178 if (filter.acceptScriptTerritory(id))
3179 result.append(system());
3180 }
3181
3182 return result;
3183}
3184
3185#if QT_DEPRECATED_SINCE(6, 6)
3186/*!
3187 \deprecated [6.6] Use \l matchingLocales() instead and consult the \l territory() of each.
3188 \since 4.3
3189
3190 Returns the list of countries that have entries for \a language in Qt's locale
3191 database. If the result is an empty list, then \a language is not represented in
3192 Qt's locale database.
3193
3194 \sa matchingLocales()
3195*/
3196QList<QLocale::Country> QLocale::countriesForLanguage(Language language)
3197{
3198 const auto locales = matchingLocales(language, AnyScript, AnyCountry);
3199 QList<Country> result;
3200 result.reserve(locales.size());
3201 for (const auto &locale : locales)
3202 result.append(locale.territory());
3203 return result;
3204}
3205#endif
3206
3207/*!
3208 \since 4.2
3209
3210 Returns the localized name of \a month, in the format specified
3211 by \a type.
3212
3213 For example, if the locale is \c en_US and \a month is 1,
3214 \l LongFormat will return \c January. \l ShortFormat \c Jan,
3215 and \l NarrowFormat \c J.
3216
3217 \sa dayName(), standaloneMonthName()
3218*/
3219QString QLocale::monthName(int month, FormatType type) const
3220{
3221 return QCalendar().monthName(*this, month, QCalendar::Unspecified, type);
3222}
3223
3224/*!
3225 \since 4.5
3226
3227 Returns the localized name of \a month that is used as a
3228 standalone text, in the format specified by \a type.
3229
3230 If the locale information doesn't specify the standalone month
3231 name then return value is the same as in monthName().
3232
3233 \sa monthName(), standaloneDayName()
3234*/
3235QString QLocale::standaloneMonthName(int month, FormatType type) const
3236{
3237 return QCalendar().standaloneMonthName(*this, month, QCalendar::Unspecified, type);
3238}
3239
3240/*!
3241 \since 4.2
3242
3243 Returns the localized name of the \a day (where 1 represents
3244 Monday, 2 represents Tuesday and so on), in the format specified
3245 by \a type.
3246
3247 For example, if the locale is \c en_US and \a day is 1,
3248 \l LongFormat will return \c Monday, \l ShortFormat \c Mon,
3249 and \l NarrowFormat \c M.
3250
3251 \sa monthName(), standaloneDayName()
3252*/
3253QString QLocale::dayName(int day, FormatType type) const
3254{
3255 return QCalendar().weekDayName(*this, day, type);
3256}
3257
3258/*!
3259 \since 4.5
3260
3261 Returns the localized name of the \a day (where 1 represents
3262 Monday, 2 represents Tuesday and so on) that is used as a
3263 standalone text, in the format specified by \a type.
3264
3265 If the locale information does not specify the standalone day
3266 name then return value is the same as in dayName().
3267
3268 \sa dayName(), standaloneMonthName()
3269*/
3270QString QLocale::standaloneDayName(int day, FormatType type) const
3271{
3272 return QCalendar().standaloneWeekDayName(*this, day, type);
3273}
3274
3275// Calendar look-up of month and day names:
3276
3277// Get locale-specific month name data:
3279 const QCalendarLocale *table)
3280{
3281 // Only used in assertions
3282 [[maybe_unused]] const auto sameLocale = [](const QLocaleData &locale,
3283 const QCalendarLocale &cal) {
3284 return locale.m_language_id == cal.m_language_id
3285 && locale.m_script_id == cal.m_script_id
3286 && locale.m_territory_id == cal.m_territory_id;
3287 };
3288 const QCalendarLocale &monthly = table[loc->m_index];
3289#ifdef QT_NO_SYSTEMLOCALE
3290 [[maybe_unused]] constexpr bool isSys = false;
3291#else // Can't have preprocessor directives in a macro's parameter list, so use local.
3292 [[maybe_unused]] const bool isSys = loc->m_data == &systemLocaleData;
3293#endif
3294 Q_ASSERT(loc->m_data == &locale_data[loc->m_index] || isSys);
3295 // Compare monthly to locale_data[] entry, as the m_index used with
3296 // systemLocaleData is a best fit, not necessarily an exact match.
3297 Q_ASSERT(sameLocale(locale_data[loc->m_index], monthly));
3298 return monthly;
3299}
3300
3301/*!
3302 \internal
3303 */
3304
3305static QString rawMonthName(const QCalendarLocale &localeData,
3306 const char16_t *monthsData, int month,
3307 QLocale::FormatType type)
3308{
3309 const QLocaleData::DataRange range = localeData.monthName(type);
3310 return range.getListEntry(monthsData, month - 1);
3311}
3312
3313/*!
3314 \internal
3315 */
3316
3317static QString rawStandaloneMonthName(const QCalendarLocale &localeData,
3318 const char16_t *monthsData, int month,
3319 QLocale::FormatType type)
3320{
3321 const QLocaleData::DataRange range = localeData.standaloneMonthName(type);
3322 if (QString name = range.getListEntry(monthsData, month - 1); !name.isEmpty())
3323 return name;
3324 return rawMonthName(localeData, monthsData, month, type);
3325}
3326
3327/*!
3328 \internal
3329 */
3330
3331static QString rawWeekDayName(const QLocaleData *data, const int day,
3332 QLocale::FormatType type)
3333{
3334 QLocaleData::DataRange range;
3335 switch (type) {
3336 case QLocale::LongFormat:
3337 range = data->longDayNames();
3338 break;
3339 case QLocale::ShortFormat:
3340 range = data->shortDayNames();
3341 break;
3342 case QLocale::NarrowFormat:
3343 range = data->narrowDayNames();
3344 break;
3345 default:
3346 return QString();
3347 }
3348 return range.getListEntry(days_data, day == 7 ? 0 : day);
3349}
3350
3351/*!
3352 \internal
3353 */
3354
3355static QString rawStandaloneWeekDayName(const QLocaleData *data, const int day,
3356 QLocale::FormatType type)
3357{
3358 QLocaleData::DataRange range;
3359 switch (type) {
3360 case QLocale::LongFormat:
3361 range =data->longDayNamesStandalone();
3362 break;
3363 case QLocale::ShortFormat:
3364 range = data->shortDayNamesStandalone();
3365 break;
3366 case QLocale::NarrowFormat:
3367 range = data->narrowDayNamesStandalone();
3368 break;
3369 default:
3370 return QString();
3371 }
3372 QString name = range.getListEntry(days_data, day == 7 ? 0 : day);
3373 if (name.isEmpty())
3374 return rawWeekDayName(data, day, type);
3375 return name;
3376}
3377
3378// Refugees from qcalendar.cpp that need functions above:
3379
3380QString QCalendarBackend::monthName(const QLocale &locale, int month, int,
3381 QLocale::FormatType format) const
3382{
3383 Q_ASSERT(month >= 1 && month <= maximumMonthsInYear());
3384 return rawMonthName(getMonthDataFor(locale.d, localeMonthIndexData()),
3385 localeMonthData(), month, format);
3386}
3387
3388QString QRomanCalendar::monthName(const QLocale &locale, int month, int year,
3389 QLocale::FormatType format) const
3390{
3391#ifndef QT_NO_SYSTEMLOCALE
3392 if (locale.d->m_data == &systemLocaleData) {
3393 Q_ASSERT(month >= 1 && month <= 12);
3394 QSystemLocale::QueryType queryType = QSystemLocale::MonthNameLong;
3395 switch (format) {
3396 case QLocale::LongFormat:
3397 queryType = QSystemLocale::MonthNameLong;
3398 break;
3399 case QLocale::ShortFormat:
3400 queryType = QSystemLocale::MonthNameShort;
3401 break;
3402 case QLocale::NarrowFormat:
3403 queryType = QSystemLocale::MonthNameNarrow;
3404 break;
3405 }
3406 QVariant res = systemLocale()->query(queryType, month);
3407 if (!res.isNull())
3408 return res.toString();
3409 }
3410#endif
3411
3412 return QCalendarBackend::monthName(locale, month, year, format);
3413}
3414
3415QString QCalendarBackend::standaloneMonthName(const QLocale &locale, int month, int,
3416 QLocale::FormatType format) const
3417{
3418 Q_ASSERT(month >= 1 && month <= maximumMonthsInYear());
3419 return rawStandaloneMonthName(getMonthDataFor(locale.d, localeMonthIndexData()),
3420 localeMonthData(), month, format);
3421}
3422
3423QString QRomanCalendar::standaloneMonthName(const QLocale &locale, int month, int year,
3424 QLocale::FormatType format) const
3425{
3426#ifndef QT_NO_SYSTEMLOCALE
3427 if (locale.d->m_data == &systemLocaleData) {
3428 Q_ASSERT(month >= 1 && month <= 12);
3429 QSystemLocale::QueryType queryType = QSystemLocale::StandaloneMonthNameLong;
3430 switch (format) {
3431 case QLocale::LongFormat:
3432 queryType = QSystemLocale::StandaloneMonthNameLong;
3433 break;
3434 case QLocale::ShortFormat:
3435 queryType = QSystemLocale::StandaloneMonthNameShort;
3436 break;
3437 case QLocale::NarrowFormat:
3438 queryType = QSystemLocale::StandaloneMonthNameNarrow;
3439 break;
3440 }
3441 QVariant res = systemLocale()->query(queryType, month);
3442 if (!res.isNull())
3443 return res.toString();
3444 }
3445#endif
3446
3447 return QCalendarBackend::standaloneMonthName(locale, month, year, format);
3448}
3449
3450// Most calendars share the common week-day naming, modulo locale.
3451// Calendars that don't must override these methods.
3452QString QCalendarBackend::weekDayName(const QLocale &locale, int day,
3453 QLocale::FormatType format) const
3454{
3455 if (day < 1 || day > 7)
3456 return QString();
3457
3458#ifndef QT_NO_SYSTEMLOCALE
3459 if (locale.d->m_data == &systemLocaleData) {
3460 QSystemLocale::QueryType queryType = QSystemLocale::DayNameLong;
3461 switch (format) {
3462 case QLocale::LongFormat:
3463 queryType = QSystemLocale::DayNameLong;
3464 break;
3465 case QLocale::ShortFormat:
3466 queryType = QSystemLocale::DayNameShort;
3467 break;
3468 case QLocale::NarrowFormat:
3469 queryType = QSystemLocale::DayNameNarrow;
3470 break;
3471 }
3472 QVariant res = systemLocale()->query(queryType, day);
3473 if (!res.isNull())
3474 return res.toString();
3475 }
3476#endif
3477
3478 return rawWeekDayName(locale.d->m_data, day, format);
3479}
3480
3481QString QCalendarBackend::standaloneWeekDayName(const QLocale &locale, int day,
3482 QLocale::FormatType format) const
3483{
3484 if (day < 1 || day > 7)
3485 return QString();
3486
3487#ifndef QT_NO_SYSTEMLOCALE
3488 if (locale.d->m_data == &systemLocaleData) {
3489 QSystemLocale::QueryType queryType = QSystemLocale::StandaloneDayNameLong;
3490 switch (format) {
3491 case QLocale::LongFormat:
3492 queryType = QSystemLocale::StandaloneDayNameLong;
3493 break;
3494 case QLocale::ShortFormat:
3495 queryType = QSystemLocale::StandaloneDayNameShort;
3496 break;
3497 case QLocale::NarrowFormat:
3498 queryType = QSystemLocale::StandaloneDayNameNarrow;
3499 break;
3500 }
3501 QVariant res = systemLocale()->query(queryType, day);
3502 if (!res.isNull())
3503 return res.toString();
3504 }
3505#endif
3506
3507 return rawStandaloneWeekDayName(locale.d->m_data, day, format);
3508}
3509
3510// End of this block of qcalendar.cpp refugees. (One more follows.)
3511
3512/*!
3513 \since 4.8
3514
3515 Returns the first day of the week according to the current locale.
3516*/
3517Qt::DayOfWeek QLocale::firstDayOfWeek() const
3518{
3519#ifndef QT_NO_SYSTEMLOCALE
3520 if (d->m_data == &systemLocaleData) {
3521 const auto res = systemLocale()->query(QSystemLocale::FirstDayOfWeek);
3522 if (!res.isNull())
3523 return static_cast<Qt::DayOfWeek>(res.toUInt());
3524 }
3525#endif
3526 return static_cast<Qt::DayOfWeek>(d->m_data->m_first_day_of_week);
3527}
3528
3530{
3531 /* Unicode CLDR's information about measurement systems doesn't say which to
3532 use by default in each locale. Even if it did, adding another entry in
3533 every locale's row of locale_data[] would take up much more memory than
3534 the small table below.
3535 */
3536 struct TerritoryLanguage
3537 {
3538 quint16 languageId;
3539 quint16 territoryId;
3540 QLocale::MeasurementSystem system;
3541 };
3542 // TODO: research how realistic and/or complete this is:
3543 constexpr TerritoryLanguage ImperialMeasurementSystems[] = {
3544 { QLocale::English, QLocale::UnitedStates, QLocale::ImperialUSSystem },
3545 { QLocale::English, QLocale::UnitedStatesMinorOutlyingIslands, QLocale::ImperialUSSystem },
3546 { QLocale::Spanish, QLocale::UnitedStates, QLocale::ImperialUSSystem },
3547 { QLocale::Hawaiian, QLocale::UnitedStates, QLocale::ImperialUSSystem },
3548 { QLocale::English, QLocale::UnitedKingdom, QLocale::ImperialUKSystem }
3549 };
3550
3551 for (const auto &system : ImperialMeasurementSystems) {
3552 if (system.languageId == m_data->m_language_id
3553 && system.territoryId == m_data->m_territory_id) {
3554 return system.system;
3555 }
3556 }
3557 return QLocale::MetricSystem;
3558}
3559
3560/*!
3561 \since 4.8
3562
3563 Returns a list of days that are considered weekdays according to the current locale.
3564*/
3565QList<Qt::DayOfWeek> QLocale::weekdays() const
3566{
3567#ifndef QT_NO_SYSTEMLOCALE
3568 if (d->m_data == &systemLocaleData) {
3569 auto res
3570 = qvariant_cast<QList<Qt::DayOfWeek> >(systemLocale()->query(QSystemLocale::Weekdays));
3571 if (!res.isEmpty())
3572 return res;
3573 }
3574#endif
3575 QList<Qt::DayOfWeek> weekdays;
3576 quint16 weekendStart = d->m_data->m_weekend_start;
3577 quint16 weekendEnd = d->m_data->m_weekend_end;
3578 for (int day = Qt::Monday; day <= Qt::Sunday; day++) {
3579 if ((weekendEnd >= weekendStart && (day < weekendStart || day > weekendEnd)) ||
3580 (weekendEnd < weekendStart && (day > weekendEnd && day < weekendStart)))
3581 weekdays << static_cast<Qt::DayOfWeek>(day);
3582 }
3583 return weekdays;
3584}
3585
3586/*!
3587 \since 4.4
3588
3589 Returns the measurement system for the locale.
3590*/
3591QLocale::MeasurementSystem QLocale::measurementSystem() const
3592{
3593#ifndef QT_NO_SYSTEMLOCALE
3594 if (d->m_data == &systemLocaleData) {
3595 const auto res = systemLocale()->query(QSystemLocale::MeasurementSystem);
3596 if (!res.isNull())
3597 return MeasurementSystem(res.toInt());
3598 }
3599#endif
3600
3601 return d->measurementSystem();
3602}
3603
3604/*!
3605 \since 4.7
3606
3607 Returns the text direction of the language.
3608*/
3609Qt::LayoutDirection QLocale::textDirection() const
3610{
3611 switch (script()) {
3612 case AdlamScript:
3613 case ArabicScript:
3614 case AvestanScript:
3615 case CypriotScript:
3616 case HatranScript:
3617 case HebrewScript:
3618 case ImperialAramaicScript:
3619 case InscriptionalPahlaviScript:
3620 case InscriptionalParthianScript:
3621 case KharoshthiScript:
3622 case LydianScript:
3623 case MandaeanScript:
3624 case ManichaeanScript:
3625 case MendeKikakuiScript:
3626 case MeroiticCursiveScript:
3627 case MeroiticScript:
3628 case NabataeanScript:
3629 case NkoScript:
3630 case OldHungarianScript:
3631 case OldNorthArabianScript:
3632 case OldSouthArabianScript:
3633 case OrkhonScript:
3634 case PalmyreneScript:
3635 case PhoenicianScript:
3636 case PsalterPahlaviScript:
3637 case SamaritanScript:
3638 case SyriacScript:
3639 case ThaanaScript:
3640 return Qt::RightToLeft;
3641 default:
3642 break;
3643 }
3644 return Qt::LeftToRight;
3645}
3646
3647/*!
3648 \since 4.8
3649
3650 Returns an uppercase copy of \a str.
3651
3652 If Qt Core is using the ICU libraries, they will be used to perform
3653 the transformation according to the rules of the current locale.
3654 Otherwise the conversion may be done in a platform-dependent manner,
3655 with QString::toUpper() as a generic fallback.
3656
3657 \note In some cases the uppercase form of a string may be longer than the
3658 original.
3659
3660 \sa QString::toUpper()
3661*/
3662QString QLocale::toUpper(const QString &str) const
3663{
3664#if !defined(QT_BOOTSTRAPPED) && (QT_CONFIG(icu) || defined(Q_OS_WIN) || defined(Q_OS_APPLE))
3665 bool ok = true;
3666 QString result = d->toUpper(str, &ok);
3667 if (ok)
3668 return result;
3669 // else fall through and use Qt's toUpper
3670#endif
3671 return str.toUpper();
3672}
3673
3674/*!
3675 \since 4.8
3676
3677 Returns a lowercase copy of \a str.
3678
3679 If Qt Core is using the ICU libraries, they will be used to perform
3680 the transformation according to the rules of the current locale.
3681 Otherwise the conversion may be done in a platform-dependent manner,
3682 with QString::toLower() as a generic fallback.
3683
3684 \sa QString::toLower()
3685*/
3686QString QLocale::toLower(const QString &str) const
3687{
3688#if !defined(QT_BOOTSTRAPPED) && (QT_CONFIG(icu) || defined(Q_OS_WIN) || defined(Q_OS_APPLE))
3689 bool ok = true;
3690 const QString result = d->toLower(str, &ok);
3691 if (ok)
3692 return result;
3693 // else fall through and use Qt's toLower
3694#endif
3695 return str.toLower();
3696}
3697
3698
3699/*!
3700 \since 4.5
3701
3702 Returns the localized name of the "AM" suffix for times specified using
3703 the conventions of the 12-hour clock.
3704
3705 \sa pmText()
3706*/
3707QString QLocale::amText() const
3708{
3709#ifndef QT_NO_SYSTEMLOCALE
3710 if (d->m_data == &systemLocaleData) {
3711 auto res = systemLocale()->query(QSystemLocale::AMText).toString();
3712 if (!res.isEmpty())
3713 return res;
3714 }
3715#endif
3716 return d->m_data->anteMeridiem().getData(am_data);
3717}
3718
3719/*!
3720 \since 4.5
3721
3722 Returns the localized name of the "PM" suffix for times specified using
3723 the conventions of the 12-hour clock.
3724
3725 \sa amText()
3726*/
3727QString QLocale::pmText() const
3728{
3729#ifndef QT_NO_SYSTEMLOCALE
3730 if (d->m_data == &systemLocaleData) {
3731 auto res = systemLocale()->query(QSystemLocale::PMText).toString();
3732 if (!res.isEmpty())
3733 return res;
3734 }
3735#endif
3736 return d->m_data->postMeridiem().getData(pm_data);
3737}
3738
3739// For the benefit of QCalendar, below.
3740static QString offsetFromAbbreviation(QString &&text)
3741{
3742 QStringView tail{text};
3743 // May need to strip a prefix:
3744 if (tail.startsWith("UTC"_L1) || tail.startsWith("GMT"_L1))
3745 tail = tail.sliced(3);
3746 // TODO: there may be a locale-specific alternative prefix.
3747 // Hard to know without zone-name L10n details, though.
3748 return (tail.isEmpty() // The Qt::UTC case omits the zero offset:
3749 ? u"+00:00"_s
3750 // Whole-hour offsets may lack the zero minutes:
3751 : (tail.size() <= 3
3752 ? tail + ":00"_L1
3753 : std::move(text).right(tail.size())));
3754}
3755
3756// For the benefit of QCalendar, below, when not provided by QTZL.
3757#if !QT_CONFIG(datestring)
3758// No need for temporal data serialization and parsing code.
3759#elif QT_CONFIG(icu) || !(QT_CONFIG(timezone) && QT_CONFIG(timezone_locale))
3760namespace QtTimeZoneLocale {
3761
3762// TODO: is there a way to get this non-kludgily from ICU ?
3763// If so, that version goes in QTZL.cpp's relevant #if-ery branch.
3764QString zoneOffsetFormat([[maybe_unused]] const QLocale &locale,
3765 qsizetype,
3766 QtTemporalPattern::TemporalFieldFlags,
3767 const QDateTime &when,
3768 int offsetSeconds)
3769{
3770 // Only the non-ICU TZ-locale code uses the prefix forms, so this tacitly
3771 // assumes flags: Numeric | Abbreviated | NeedNoUtcPrefix | ZeroPad.
3772 QString text =
3773#if QT_CONFIG(timezone)
3774 locale != QLocale::system()
3775 ? when.timeRepresentation().displayName(when, QTimeZone::OffsetName, locale)
3776 :
3777#endif
3778 when.toOffsetFromUtc(offsetSeconds).timeZoneAbbreviation();
3779
3780 if (!text.isEmpty())
3781 text = offsetFromAbbreviation(std::move(text));
3782 // else: no suitable representation of the zone.
3783 return text;
3784}
3785
3786} // QtTimeZoneLocale
3787#endif // ICU or no TZ L10n
3788
3789// Another intrusion from QCalendar, using some of the tools above:
3790QString QCalendarBackend::dateTimeToString(QStringView format, const QDateTime &datetime,
3791 QDate dateOnly, QTime timeOnly,
3792 const QLocale &locale) const
3793{
3794 QDate date;
3795 QTime time;
3796 bool formatDate = false;
3797 bool formatTime = false;
3798 if (datetime.isValid()) {
3799 date = datetime.date();
3800 time = datetime.time();
3801 formatDate = true;
3802 formatTime = true;
3803 } else if (dateOnly.isValid()) {
3804 date = dateOnly;
3805 formatDate = true;
3806 } else if (timeOnly.isValid()) {
3807 time = timeOnly;
3808 formatTime = true;
3809 } else {
3810 return QString();
3811 }
3812
3813 QString result;
3814 int year = 0, month = 0, day = 0;
3815 if (formatDate) {
3816 const auto parts = julianDayToDate(date.toJulianDay());
3817 if (!parts.isValid())
3818 return QString();
3819 year = parts.year;
3820 month = parts.month;
3821 day = parts.day;
3822 }
3823
3824 auto appendToResult = [&](int t, int repeat) {
3825 auto data = locale.d->m_data;
3826 if (repeat > 1)
3827 result.append(data->longLongToString(t, -1, 10, repeat, QLocaleData::ZeroPadded));
3828 else
3829 result.append(data->longLongToString(t));
3830 };
3831
3832 auto formatType = [](int repeat) {
3833 return repeat == 3 ? QLocale::ShortFormat : QLocale::LongFormat;
3834 };
3835
3836 qsizetype i = 0;
3837 while (i < format.size()) {
3838 if (format.at(i).unicode() == '\'') {
3839 result.append(qt_readEscapedFormatString(format, &i));
3840 continue;
3841 }
3842
3843 const QChar c = format.at(i);
3844 qsizetype rep = qt_repeatCount(format.mid(i));
3845 Q_ASSERT(rep < std::numeric_limits<int>::max());
3846 int repeat = int(rep);
3847 bool used = false;
3848 if (formatDate) {
3849 switch (c.unicode()) {
3850 case 'y':
3851 used = true;
3852 if (repeat >= 4)
3853 repeat = 4;
3854 else if (repeat >= 2)
3855 repeat = 2;
3856
3857 switch (repeat) {
3858 case 4:
3859 // Years with more than four digits must have a sign:
3860 if (year > 9999)
3861 result.append(locale.positiveSign());
3862 appendToResult(year, (year < 0) ? 5 : 4);
3863 break;
3864 case 2:
3865 appendToResult(year % 100, 2);
3866 break;
3867 default:
3868 repeat = 1;
3869 result.append(c);
3870 break;
3871 }
3872 break;
3873
3874 case 'M':
3875 used = true;
3876 repeat = qMin(repeat, 4);
3877 if (repeat <= 2)
3878 appendToResult(month, repeat);
3879 else
3880 result.append(monthName(locale, month, year, formatType(repeat)));
3881 break;
3882
3883 case 'd':
3884 used = true;
3885 repeat = qMin(repeat, 4);
3886 if (repeat <= 2)
3887 appendToResult(day, repeat);
3888 else
3889 result.append(
3890 locale.dayName(dayOfWeek(date.toJulianDay()), formatType(repeat)));
3891 break;
3892
3893 default:
3894 break;
3895 }
3896 }
3897 if (!used && formatTime) {
3898 switch (c.unicode()) {
3899 case 'h': {
3900 used = true;
3901 repeat = qMin(repeat, 2);
3902 int hour = time.hour();
3903 if (timeFormatContainsAP(format)) {
3904 if (hour > 12)
3905 hour -= 12;
3906 else if (hour == 0)
3907 hour = 12;
3908 }
3909 appendToResult(hour, repeat);
3910 break;
3911 }
3912 case 'H':
3913 used = true;
3914 repeat = qMin(repeat, 2);
3915 appendToResult(time.hour(), repeat);
3916 break;
3917
3918 case 'm':
3919 used = true;
3920 repeat = qMin(repeat, 2);
3921 appendToResult(time.minute(), repeat);
3922 break;
3923
3924 case 's':
3925 used = true;
3926 repeat = qMin(repeat, 2);
3927 appendToResult(time.second(), repeat);
3928 break;
3929
3930 case 'A':
3931 case 'a': {
3932 QString text = time.hour() < 12 ? locale.amText() : locale.pmText();
3933 used = true;
3934 repeat = 1;
3935 if (format.mid(i + 1).startsWith(u'p', Qt::CaseInsensitive))
3936 ++repeat;
3937 if (c.unicode() == 'A' && (repeat == 1 || format.at(i + 1).unicode() == 'P'))
3938 text = std::move(text).toUpper();
3939 else if (c.unicode() == 'a' && (repeat == 1 || format.at(i + 1).unicode() == 'p'))
3940 text = std::move(text).toLower();
3941 // else 'Ap' or 'aP' => use CLDR text verbatim, preserving case
3942 result.append(text);
3943 break;
3944 }
3945
3946 case 'z':
3947 used = true;
3948 repeat = qMin(repeat, 3);
3949
3950 // note: the millisecond component is treated like the decimal part of the seconds
3951 // so ms == 2 is always printed as "002", but ms == 200 can be either "2" or "200"
3952 appendToResult(time.msec(), 3);
3953 if (repeat != 3) {
3954 const QString zero = locale.zeroDigit();
3955 if (result.endsWith(zero))
3956 result.chop(zero.size());
3957 if (result.endsWith(zero))
3958 result.chop(zero.size());
3959 }
3960 break;
3961
3962 case 't': {
3963#if QT_CONFIG(datestring)
3964 // Feature check should really apply to the whole function, but
3965 // this portion of it depends on internals entangled with the
3966 // feature.
3967 enum AbbrType { Long, Offset, Short };
3968 const auto tzAbbr = [locale](const QDateTime &when, AbbrType type) {
3969 QString text;
3970 if (type == Offset) {
3971 using Flag = QtTemporalPattern::TemporalFieldFlag;
3972 constexpr auto noPrefixOffset = Flag::Numeric | Flag::Abbreviated
3973 | Flag::NeedNoUtcPrefix | Flag::ZeroPad;
3974 text = QtTimeZoneLocale::zoneOffsetFormat(locale, locale.d->m_index,
3975 noPrefixOffset,
3976 when, when.offsetFromUtc());
3977 // When using timezone_locale data, this should always succeed:
3978 if (!text.isEmpty())
3979 return text;
3980 }
3981# if QT_CONFIG(timezone)
3982 if (type != Short || locale != QLocale::system()) {
3983 QTimeZone::NameType mode =
3984 type == Short ? QTimeZone::ShortName
3985 : type == Long ? QTimeZone::LongName : QTimeZone::OffsetName;
3986 text = when.timeRepresentation().displayName(when, mode, locale);
3987 if (!text.isEmpty())
3988 return text;
3989 // else fall back to an unlocalized one if we can find one.
3990 }
3991 if (type == Long) {
3992 // If no long name found, use IANA ID:
3993 text = QString::fromLatin1(when.timeZone().id());
3994 if (!text.isEmpty())
3995 return text;
3996 }
3997 // else: prefer QDateTime's abbreviation, for backwards-compatibility.
3998# endif // else, make do with non-localized abbreviation:
3999 // Absent timezone_locale data, Offset might still reach here:
4000 if (type == Offset) // Our prior failure might not have tried this:
4001 text = when.toOffsetFromUtc(when.offsetFromUtc()).timeZoneAbbreviation();
4002 if (text.isEmpty()) // Notably including type != Offset
4003 text = when.timeZoneAbbreviation();
4004 if (type == Offset)
4005 text = offsetFromAbbreviation(std::move(text));
4006 return text;
4007 };
4008
4009 used = true;
4010 repeat = qMin(repeat, 4);
4011 // If we don't have a date-time, use the current system time:
4012 const QDateTime when = formatDate ? datetime : QDateTime::currentDateTime();
4013 QString text;
4014 switch (repeat) {
4015 case 4:
4016 text = tzAbbr(when, Long);
4017 break;
4018 case 3: // ±hh:mm
4019 case 2: // ±hhmm (we'll remove the ':' at the end)
4020 text = tzAbbr(when, Offset);
4021 if (repeat == 2)
4022 text.remove(u':');
4023 break;
4024 default:
4025 text = tzAbbr(when, Short);
4026 // UTC-offset zones only include minutes if non-zero.
4027 if (text.startsWith("UTC"_L1) && text.size() == 6)
4028 text += ":00"_L1;
4029 break;
4030 }
4031 if (!text.isEmpty())
4032 result.append(text);
4033#endif // datestring
4034 break;
4035 }
4036
4037 default:
4038 break;
4039 }
4040 }
4041 if (!used)
4042 result.resize(result.size() + repeat, c);
4043 i += repeat;
4044 }
4045
4046 return result;
4047}
4048// End of QCalendar intrustions
4049
4050QString QLocaleData::doubleToString(double d, int precision, DoubleForm form,
4051 int width, unsigned flags) const
4052{
4053 // Although the special handling of F.P.Shortest below is limited to
4054 // DFSignificantDigits, the double-conversion library does treat it
4055 // specially for the other forms, shedding trailing zeros for DFDecimal and
4056 // using the shortest mantissa that faithfully represents the value for
4057 // DFExponent.
4058 if (precision != QLocale::FloatingPointShortest && precision < 0)
4059 precision = 6;
4060 if (width < 0)
4061 width = 0;
4062
4063 int decpt;
4064 qsizetype bufSize = 1;
4065 if (precision == QLocale::FloatingPointShortest)
4066 bufSize += std::numeric_limits<double>::max_digits10;
4067 else if (form == DFDecimal && qt_is_finite(d))
4068 bufSize += wholePartSpace(qAbs(d)) + precision;
4069 else // Add extra digit due to different interpretations of precision.
4070 bufSize += qMax(2, precision) + 1; // Must also be big enough for "nan" or "inf"
4071
4072 QVarLengthArray<char> buf(bufSize);
4073 int length;
4074 bool negative = false;
4075 qt_doubleToAscii(d, form, precision, buf.data(), bufSize, negative, length, decpt);
4076
4077 const QString prefix = signPrefix(negative && !qIsNull(d), flags);
4078 QString numStr;
4079
4080 if (length == 3
4081 && (qstrncmp(buf.data(), "inf", 3) == 0 || qstrncmp(buf.data(), "nan", 3) == 0)) {
4082 numStr = QString::fromLatin1(buf.data(), length);
4083 } else { // Handle finite values
4084 const QString zero = zeroDigit();
4085 QString digits = QString::fromLatin1(buf.data(), length);
4086
4087 if (zero == u"0") {
4088 // No need to convert digits.
4089 Q_ASSERT(std::all_of(buf.cbegin(), buf.cbegin() + length, isAsciiDigit));
4090 // That check is taken care of in unicodeForDigits, below.
4091 } else if (zero.size() == 2 && zero.at(0).isHighSurrogate()) {
4092 const char32_t zeroUcs4 = QChar::surrogateToUcs4(zero.at(0), zero.at(1));
4093 QString converted;
4094 converted.reserve(2 * digits.size());
4095 for (QChar ch : std::as_const(digits)) {
4096 const char32_t digit = unicodeForDigit(ch.unicode() - '0', zeroUcs4);
4097 Q_ASSERT(QChar::requiresSurrogates(digit));
4098 converted.append(QChar::highSurrogate(digit));
4099 converted.append(QChar::lowSurrogate(digit));
4100 }
4101 digits = std::move(converted);
4102 } else {
4103 Q_ASSERT(zero.size() == 1);
4104 Q_ASSERT(!zero.at(0).isSurrogate());
4105 char16_t z = zero.at(0).unicode();
4106 char16_t *const value = reinterpret_cast<char16_t *>(digits.data());
4107 for (qsizetype i = 0; i < digits.size(); ++i)
4108 value[i] = unicodeForDigit(value[i] - '0', z);
4109 }
4110
4111 const bool mustMarkDecimal = flags & ForcePoint;
4112 const bool groupDigits = flags & GroupDigits;
4113 const int minExponentDigits = flags & ZeroPadExponent ? 2 : 1;
4114 switch (form) {
4115 case DFExponent:
4116 numStr = exponentForm(std::move(digits), decpt, precision, PMDecimalDigits,
4117 mustMarkDecimal, minExponentDigits);
4118 break;
4119 case DFDecimal:
4120 numStr = decimalForm(std::move(digits), decpt, precision, PMDecimalDigits,
4121 mustMarkDecimal, groupDigits);
4122 break;
4123 case DFSignificantDigits: {
4124 PrecisionMode mode
4125 = (flags & AddTrailingZeroes) ? PMSignificantDigits : PMChopTrailingZeros;
4126
4127 /* POSIX specifies sprintf() to follow fprintf(), whose 'g/G' format
4128 says; with P = 6 if precision unspecified else 1 if precision is
4129 0 else precision; when 'e/E' would have exponent X, use:
4130 * 'f/F' if P > X >= -4, with precision P-1-X
4131 * 'e/E' otherwise, with precision P-1
4132 Helpfully, we already have mapped precision < 0 to 6 - except for
4133 F.P.Shortest mode, which is its own story - and those of our
4134 callers with unspecified precision either used 6 or -1 for it.
4135 */
4136 bool useDecimal;
4137 if (precision == QLocale::FloatingPointShortest) {
4138 // Find out which representation is shorter.
4139 // Set bias to everything added to exponent form but not
4140 // decimal, minus the converse.
4141
4142 const QLocaleData::GroupSizes grouping = groupSizes();
4143 // Exponent adds separator, sign and digits:
4144 int bias = 2 + minExponentDigits;
4145 // Decimal form may get grouping separators inserted:
4146 if (groupDigits && decpt >= grouping.first + grouping.least)
4147 bias -= (decpt - grouping.least) / grouping.higher + 1;
4148 // X = decpt - 1 needs two digits if decpt > 10:
4149 if (decpt > 10 && minExponentDigits == 1)
4150 ++bias;
4151 // Assume digitCount < 95, so we can ignore the 3-digit
4152 // exponent case (we'll set useDecimal false anyway).
4153
4154 const qsizetype digitCount = digits.size() / zero.size();
4155 if (!mustMarkDecimal) {
4156 // Decimal separator is skipped if at end; adjust if
4157 // that happens for only one form:
4158 if (digitCount <= decpt && digitCount > 1)
4159 ++bias; // decimal but not exponent
4160 else if (digitCount == 1 && decpt <= 0)
4161 --bias; // exponent but not decimal
4162 }
4163 // When 0 < decpt <= digitCount, the forms have equal digit
4164 // counts, plus things bias has taken into account; otherwise
4165 // decimal form's digit count is right-padded with zeros to
4166 // decpt, when decpt is positive, otherwise it's left-padded
4167 // with 1 - decpt zeros.
4168 useDecimal = (decpt <= 0 ? 1 - decpt <= bias
4169 : decpt <= digitCount ? 0 <= bias : decpt <= digitCount + bias);
4170 } else {
4171 // X == decpt - 1, POSIX's P; -4 <= X < P iff -4 < decpt <= P
4172 Q_ASSERT(precision >= 0);
4173 useDecimal = decpt > -4 && decpt <= (precision ? precision : 1);
4174 }
4175
4176 numStr = useDecimal
4177 ? decimalForm(std::move(digits), decpt, precision, mode,
4178 mustMarkDecimal, groupDigits)
4179 : exponentForm(std::move(digits), decpt, precision, mode,
4180 mustMarkDecimal, minExponentDigits);
4181 break;
4182 }
4183 }
4184
4185 // Pad with zeros. LeftAdjusted overrides ZeroPadded.
4186 if (flags & ZeroPadded && !(flags & LeftAdjusted)) {
4187 for (qsizetype i = numStr.size() / zero.size() + prefix.size(); i < width; ++i)
4188 numStr.prepend(zero);
4189 }
4190 }
4191
4192 return prefix + (flags & CapitalEorX
4193 ? std::move(numStr).toUpper()
4194 : std::move(numStr).toLower());
4195}
4196
4197QString QLocaleData::decimalForm(QString &&digits, int decpt, int precision,
4198 PrecisionMode pm, bool mustMarkDecimal,
4199 bool groupDigits) const
4200{
4201 const QString zero = zeroDigit();
4202 const auto digitWidth = zero.size();
4203 Q_ASSERT(digitWidth == 1 || digitWidth == 2);
4204 Q_ASSERT(digits.size() % digitWidth == 0);
4205
4206 // Separator needs to go at index decpt: so add zeros before or after the
4207 // given digits, if they don't reach that position already:
4208 if (decpt < 0) {
4209 for (; decpt < 0; ++decpt)
4210 digits.prepend(zero);
4211 } else {
4212 for (qsizetype i = digits.size() / digitWidth; i < decpt; ++i)
4213 digits.append(zero);
4214 }
4215
4216 switch (pm) {
4217 case PMDecimalDigits:
4218 for (qsizetype i = digits.size() / digitWidth - decpt; i < precision; ++i)
4219 digits.append(zero);
4220 break;
4221 case PMSignificantDigits:
4222 for (qsizetype i = digits.size() / digitWidth; i < precision; ++i)
4223 digits.append(zero);
4224 break;
4225 case PMChopTrailingZeros:
4226 Q_ASSERT(digits.size() / digitWidth <= qMax(decpt, 1) || !digits.endsWith(zero));
4227 break;
4228 }
4229
4230 if (mustMarkDecimal || decpt < digits.size() / digitWidth)
4231 digits.insert(decpt * digitWidth, decimalPoint());
4232
4233 if (groupDigits) {
4234 const QLocaleData::GroupSizes grouping = groupSizes();
4235 const QString group = groupSeparator();
4236 qsizetype i = decpt - grouping.least;
4237 if (i >= grouping.first) {
4238 digits.insert(i * digitWidth, group);
4239 while ((i -= grouping.higher) > 0)
4240 digits.insert(i * digitWidth, group);
4241 }
4242 }
4243
4244 if (decpt == 0)
4245 digits.prepend(zero);
4246
4247 return std::move(digits);
4248}
4249
4250QString QLocaleData::exponentForm(QString &&digits, int decpt, int precision,
4251 PrecisionMode pm, bool mustMarkDecimal,
4252 int minExponentDigits) const
4253{
4254 const QString zero = zeroDigit();
4255 const auto digitWidth = zero.size();
4256 Q_ASSERT(digitWidth == 1 || digitWidth == 2);
4257 Q_ASSERT(digits.size() % digitWidth == 0);
4258
4259 switch (pm) {
4260 case PMDecimalDigits:
4261 for (qsizetype i = digits.size() / digitWidth; i < precision + 1; ++i)
4262 digits.append(zero);
4263 break;
4264 case PMSignificantDigits:
4265 for (qsizetype i = digits.size() / digitWidth; i < precision; ++i)
4266 digits.append(zero);
4267 break;
4268 case PMChopTrailingZeros:
4269 Q_ASSERT(digits.size() / digitWidth <= 1 || !digits.endsWith(zero));
4270 break;
4271 }
4272
4273 if (mustMarkDecimal || digits.size() > digitWidth)
4274 digits.insert(digitWidth, decimalPoint());
4275
4276 digits.append(exponentSeparator());
4277 digits.append(longLongToString(decpt - 1, minExponentDigits, 10, -1, AlwaysShowSign));
4278
4279 return std::move(digits);
4280}
4281
4282QString QLocaleData::signPrefix(bool negative, unsigned flags) const
4283{
4284 if (negative)
4285 return negativeSign();
4286 if (flags & AlwaysShowSign)
4287 return positiveSign();
4288 if (flags & BlankBeforePositive)
4289 return u" "_s;
4290 return {};
4291}
4292
4293QString QLocaleData::longLongToString(qlonglong n, int precision,
4294 int base, int width, unsigned flags) const
4295{
4296 bool negative = n < 0;
4297
4298 /*
4299 Negating std::numeric_limits<qlonglong>::min() hits undefined behavior, so
4300 taking an absolute value has to take a slight detour.
4301 */
4302 QString numStr = qulltoa(negative ? 1u + qulonglong(-(n + 1)) : qulonglong(n),
4303 base, zeroDigit());
4304
4305 return applyIntegerFormatting(std::move(numStr), negative, precision, base, width, flags);
4306}
4307
4308QString QLocaleData::unsLongLongToString(qulonglong l, int precision,
4309 int base, int width, unsigned flags) const
4310{
4311 return applyIntegerFormatting(qulltoa(l, base, zeroDigit()),
4312 false, precision, base, width, flags);
4313}
4314
4315QString QLocaleData::applyIntegerFormatting(QString &&numStr, bool negative, int precision,
4316 int base, int width, unsigned flags) const
4317{
4318 const QString zero = base == 10 ? zeroDigit() : QStringLiteral("0");
4319 const auto digitWidth = zero.size();
4320 const auto digitCount = numStr.size() / digitWidth;
4321
4322 const auto basePrefix = [&] () -> QStringView {
4323 if (flags & ShowBase) {
4324 const bool upper = flags & UppercaseBase;
4325 if (base == 16)
4326 return upper ? u"0X" : u"0x";
4327 if (base == 2)
4328 return upper ? u"0B" : u"0b";
4329 if (base == 8 && !numStr.startsWith(zero))
4330 return zero;
4331 }
4332 return {};
4333 }();
4334
4335 const QString prefix = signPrefix(negative, flags) + basePrefix;
4336 // Count how much of width we've used up. Each digit counts as one
4337 qsizetype usedWidth = digitCount + prefix.size();
4338
4339 if (base == 10 && flags & GroupDigits) {
4340 const QLocaleData::GroupSizes grouping = groupSizes();
4341 const QString group = groupSeparator();
4342 qsizetype i = digitCount - grouping.least;
4343 if (i >= grouping.first) {
4344 numStr.insert(i * digitWidth, group);
4345 ++usedWidth;
4346 while ((i -= grouping.higher) > 0) {
4347 numStr.insert(i * digitWidth, group);
4348 ++usedWidth;
4349 }
4350 }
4351 // TODO: should we group any zero-padding we add later ?
4352 }
4353
4354 const bool noPrecision = precision == -1;
4355 if (noPrecision)
4356 precision = 1;
4357
4358 for (qsizetype i = numStr.size(); i < precision; ++i) {
4359 numStr.prepend(zero);
4360 usedWidth++;
4361 }
4362
4363 // LeftAdjusted overrides ZeroPadded; and sprintf() only pads when
4364 // precision is not specified in the format string.
4365 if (noPrecision && flags & ZeroPadded && !(flags & LeftAdjusted)) {
4366 for (qsizetype i = usedWidth; i < width; ++i)
4367 numStr.prepend(zero);
4368 }
4369
4370 QString result(flags & CapitalEorX ? std::move(numStr).toUpper() : std::move(numStr));
4371 if (prefix.size())
4372 result.prepend(prefix);
4373 return result;
4374}
4375
4377 : grouping(data->groupSizes()), isC(data == c())
4378 // Note: actually test pointer equality to c(), not language == C, as
4379 // system locale might be configured as C with tweaks.
4380{
4381 if (isC)
4382 return;
4383 setZero(data->zero().viewData(single_character_data));
4384 group = data->groupDelim().viewData(single_character_data);
4385 // Note: minus, plus and exponent might not actually be single characters.
4386 minus = data->minus().viewData(single_character_data);
4387 plus = data->plus().viewData(single_character_data);
4388 if (mode != IntegerMode)
4389 decimal = data->decimalSeparator().viewData(single_character_data);
4390 if (mode == DoubleScientificMode) {
4391 exponent = data->exponential().viewData(single_character_data);
4392 // exponentCyrillic means "apply the Cyrrilic-specific exponent hack"
4393 exponentCyrillic = data->m_script_id == QLocale::CyrillicScript;
4394 }
4395#ifndef QT_NO_SYSTEMLOCALE
4396 if (data == &systemLocaleData) {
4397 const auto getString = [sys = systemLocale()](QSystemLocale::QueryType query) {
4398 return sys->query(query).toString();
4399 };
4400 if (mode != IntegerMode) {
4401 sysDecimal = getString(QSystemLocale::DecimalPoint);
4402 if (sysDecimal.size())
4403 decimal = QStringView{sysDecimal};
4404 }
4405 sysGroup = getString(QSystemLocale::GroupSeparator);
4406 if (sysGroup.size())
4407 group = QStringView{sysGroup};
4408 sysMinus = getString(QSystemLocale::NegativeSign);
4409 if (sysMinus.size())
4410 minus = QStringView{sysMinus};
4411 sysPlus = getString(QSystemLocale::PositiveSign);
4412 if (sysPlus.size())
4413 plus = QStringView{sysPlus};
4414 setZero(getString(QSystemLocale::ZeroDigit));
4415 }
4416#endif
4417}
4418
4419namespace {
4420// A bit like QStringIterator but rather specialized ... and some of the tokens
4421// it recognizes aren't single Unicode code-points (but it does map each to a
4422// single character).
4423class NumericTokenizer
4424{
4425 // TODO: use deterministic finite-state-automata.
4426 // TODO QTBUG-95460: CLDR has Inf/NaN representations per locale.
4427 static constexpr char lettersInfNaN[] = "afin"; // Letters of Inf, NaN
4428 static constexpr auto matchInfNaN = QtPrivate::makeCharacterSetMatch<lettersInfNaN>();
4429 const QStringView m_text;
4430 const QLocaleData::NumericData m_guide;
4431 qsizetype m_index;
4432 const QLocaleData::NumberMode m_mode;
4433 static_assert('+' + 1 == ',' && ',' + 1 == '-' && '-' + 1 == '.');
4434 char lastMark; // C locale accepts '+' through lastMark.
4435public:
4436 NumericTokenizer(QStringView text, QLocaleData::NumericData &&guide,
4437 QLocaleData::NumberMode mode, qsizetype from = 0)
4438 : m_text(text), m_guide(guide), m_index(from), m_mode(mode),
4439 lastMark(mode == QLocaleData::IntegerMode ? '-' : '.')
4440 {
4441 Q_ASSERT(m_guide.isValid(mode));
4442 }
4443 bool done() const { return !(m_index < m_text.size()); }
4444 qsizetype index() const { return m_index; }
4445 int digitValue(char32_t digit) const { return m_guide.digitValue(digit); }
4446 bool isInfNanChar(char ch) const { return matchInfNaN.matches(ch); }
4447 char nextToken();
4448 bool fractionGroupClash() const
4449 {
4450 // If the user's hand-configuration of the system makes group and
4451 // fractional part separators coincide, we have some kludges to apply,
4452 // though we can skip them in integer mode.
4453 return Q_UNLIKELY(m_mode != QLocaleData::IntegerMode && m_guide.fractionalIsGroup());
4454 }
4455 const QLocaleData::GroupSizes &groupSizes() { return m_guide.groupSizes(); }
4456};
4457
4458char NumericTokenizer::nextToken()
4459{
4460 // As long as caller stops iterating on a zero return, those don't need to
4461 // keep m_index correctly updated.
4462 Q_ASSERT(!done());
4463 do {
4464 // Mauls non-letters above 'Z' but we don't care:
4465 const auto asciiLower = [](unsigned char c) { return c >= 'A' ? c | 0x20 : c; };
4466 const QStringView tail = m_text.sliced(m_index);
4467 const QChar ch = tail.front();
4468 if (ch == u'\u2212') {
4469 // Special case: match the "proper" minus sign, for all locales.
4470 ++m_index;
4471 return '-';
4472 }
4473 if (m_guide.isC) {
4474 // "Conversion" to C locale is just a filter:
4475 if (Q_LIKELY(ch.unicode() < 256)) {
4476 unsigned char ascii = asciiLower(ch.toLatin1());
4477 if (Q_LIKELY(isAsciiDigit(ascii) || ('+' <= ascii && ascii <= lastMark)
4478 // No caller presently (6.5) passes DoubleStandardMode,
4479 // so !IntegerMode implies scientific, for now.
4480 || (m_mode != QLocaleData::IntegerMode && isInfNanChar(ascii))
4481 || (m_mode == QLocaleData::DoubleScientificMode && ascii == 'e'))) {
4482 ++m_index;
4483 return ascii;
4484 }
4485 }
4486 return 0;
4487 }
4488 if (ch.unicode() < 256) {
4489 // Accept the C locale's digits and signs in all locales:
4490 char ascii = asciiLower(ch.toLatin1());
4491 if (isAsciiDigit(ascii) || ascii == '-' || ascii == '+'
4492 // Also its Inf and NaN letters:
4493 || (m_mode != QLocaleData::IntegerMode && isInfNanChar(ascii))) {
4494 ++m_index;
4495 return ascii;
4496 }
4497 }
4498
4499 // Other locales may be trickier:
4500 if (tail.startsWith(m_guide.minus)) {
4501 m_index += m_guide.minus.size();
4502 return '-';
4503 }
4504 if (tail.startsWith(m_guide.plus)) {
4505 m_index += m_guide.plus.size();
4506 return '+';
4507 }
4508 if (!m_guide.group.isEmpty() && tail.startsWith(m_guide.group)) {
4509 m_index += m_guide.group.size();
4510 // When group and decimal coincide, and a fractional part is not
4511 // unexpected, treat the last as a fractional part separator (and leave
4512 // the caller to special-case the situations where that causes a
4513 // parse-fail that we can dodge by not reading it that way).
4514 if (fractionGroupClash() && tail.indexOf(m_guide.decimal, m_guide.group.size()) == -1)
4515 return '.';
4516 return ',';
4517 }
4518 if (m_mode != QLocaleData::IntegerMode && tail.startsWith(m_guide.decimal)) {
4519 m_index += m_guide.decimal.size();
4520 return '.';
4521 }
4523 && tail.startsWith(m_guide.exponent, Qt::CaseInsensitive)) {
4524 m_index += m_guide.exponent.size();
4525 return 'e';
4526 }
4527
4528 // Must match qlocale_tools.h's unicodeForDigit()
4529 if (m_guide.zeroLen == 1) {
4530 if (!ch.isSurrogate()) {
4531 if (const int gap = digitValue(char32_t(ch.unicode())); gap >= 0) {
4532 ++m_index;
4533 return '0' + gap;
4534 }
4535 } else if (ch.isHighSurrogate() && tail.size() > 1 && tail.at(1).isLowSurrogate()) {
4536 return 0;
4537 }
4538 // There remain one or two things a non-surrogate might be ...
4539 } else if (ch.isHighSurrogate()) {
4540 // None of the corner cases below matches a surrogate, so return
4541 // early if we don't have a digit.
4542 if (tail.size() > 1) {
4543 if (const QChar low = tail.at(1); low.isLowSurrogate()) {
4544 if (const int gap = digitValue(QChar::surrogateToUcs4(ch, low)); gap >= 0) {
4545 m_index += 2;
4546 return '0' + gap;
4547 }
4548 }
4549 }
4550 return 0;
4551 }
4552
4553 // All cases where tail starts with properly-matched surrogate pair
4554 // have been handled by this point.
4555 Q_ASSERT(!(ch.isHighSurrogate() && tail.size() > 1 && tail.at(1).isLowSurrogate()));
4556
4557 // Weird corner cases (code above assumes these match no surrogates):
4558 switch (ch.unicode()) {
4559 // Skip over inivisble marks commonly found in numeric forms:
4560 case 0x061C: // Arabic Letter Mark (before signs in standard Arabic)
4561 case 0x200E: // Left-to-Right marker
4562 case 0x200F: // Right-to-Left marker
4563 ++m_index;
4564 continue;
4565
4566 case u' ':
4567 // Some locales use a non-breaking space (U+00A0) or its thin
4568 // version (U+202f) for grouping. These look like spaces, so people
4569 // (and thus some of our tests) use a regular space instead and
4570 // complain if it doesn't work.
4571 // Should this be extended generally to any case where group is a space ?
4572 if (m_guide.group == u"\u00a0" || m_guide.group == u"\u202f") {
4573 ++m_index;
4574 return ',';
4575 }
4576 break;
4577
4578 // Case-insensitive match:
4579 case u'E':
4580 case u'e':
4581 case u'\u0415': // Cyrillic E
4582 case u'\u0435': // Cyrillic e
4583 // Cyrillic E is used by Ukrainian as exponent; but others writing
4584 // Cyrillic may well use that; and Ukrainians might well use E.
4585 // All other Cyrillic locales (officially) use plain ASCII E.
4586 if (m_guide.exponentCyrillic) { // Only true in scientific float mode.
4587 ++m_index;
4588 return 'e';
4589 }
4590 break;
4591 }
4592
4593 break;
4594 } while (!done());
4595 return 0;
4596}
4597} // namespace with no name
4598
4599/*!
4600 \internal
4601 \since 6.12
4602 \class QLocaleData::DigitSequence
4603 \brief Descriptor for a digit sequence within a text.
4604
4605 Packages the ASCII equivalent (optional sign and) digit sequence, along with
4606 a description of which parts come from where in the original text.
4607
4608 Supports construction or assignment by moving or copying. Modifying its
4609 members, other than by assigning a newly constructed value or a result of
4610 taking a subsequence, may lead to undefined behaviour.
4611
4612 \sa sliced(), first(), last()
4613*/
4614// Exists for the benefit of date-time parsing, but could be used for anything
4615// else that doesn't do fractional parts, exponents or digit-grouping.
4616
4617/*!
4618 \fn qsizetype QLocaleData::DigitSequence::size()
4619
4620 Returns the number of ASCII characters describing the digit sequence.
4621
4622 This is the number of digits plus, if present, one for the sign. It is the
4623 number of characters \l transcribeTo() will transcribe. For the number of
4624 digits found, use \c {digits.size()}. Note that this may be less than the
4625 length of the text parsed, for example when the digits are surrogate pairs
4626 or the sign includes special Unicode markers, such as those for text
4627 direction.
4628
4629 \sa isEmpty()
4630*/
4631
4632/*!
4633 \fn void QLocaleData::DigitSequence::transcribeTo(CharBuff *buff)
4634
4635 Transcribes the ASCII form of this digit sequence to \a buff.
4636
4637 \sa size()
4638*/
4639
4640/*!
4641 \since 6.12
4642 \enum QLocaleData::DigitSequence::Option
4643
4644 Options to modify how digit sequences are parsed.
4645
4646 \value Default The null option value.
4647 \value AllowSign A leading sign character may be present.
4648
4649 In the numeric fields of a date, only a year field ever has a sign, all
4650 others use ungrouped digits. Zero-padding on the left of day and month
4651 fields is common (and it may also appear in year fields). The hour field of
4652 a zone-offset may also have a sign. Otherwise all numeric time fields are
4653 similar to numeric month and day fields.
4654
4655 In numeric fields of a time, the least-significant given (be it hour, minute
4656 or second) may have a fractional part in some formats. The handling of this
4657 is left for the caller to take care of. Likewise, the caller is expected to
4658 deal with leading and trailing space appropriately.
4659*/
4660
4661/*!
4662 \fn bool QLocaleData::DigitSequence::isEmpty() const
4663
4664 Returns true precisely if this digit sequence represents nothing.
4665
4666 This arises when the constructor found no digits and (when allowed) not even
4667 a sign. It may also result from extracting an empty subsequence of a digit
4668 sequence that was originally parsed. It is equivalent to \l
4669 {QLocaleData::DigitSequence::}{size()} == 0. To test whether any digits were
4670 found, use \c {digits.isEmpty()}, which may be true even though \c
4671 {isEmpty()} is false. That arises when only a sign was found (making
4672 \c{size() == 1}).
4673
4674 \sa size()
4675*/
4676
4677/*!
4678 \fn bool QLocaleData::DigitSequence::hasSign() const
4679
4680 Returns true precisely if the digit sequence parsed includes a leading sign.
4681 It is equivalent to \c{sign != '\0'}.
4682*/
4683
4684/*!
4685 \fn QStringView QLocaleData::DigitSequence::used(QStringView text, qsizetype from) const
4686 \fn QStringView QLocaleData::DigitSequence::used(QStringView text) const
4687
4688 Returns the slice of \a text described by this digit sequence.
4689
4690 The given \a text should be the one passed to the constructor either of this
4691 digit sequence or of one from which it was obtained by some combination of
4692 \l first(), \l sliced() and \l last(). In the directly-constructed case, or
4693 in the case of (optionally repeatedly) applying only \l first(), \a from may
4694 be passed: it should be the like-named offset passed to the original
4695 constructor, or 0 if no offset was passed. In that case, the whole text
4696 parsed for this digit sequence (alibeit possibly a prefix of the text
4697 originally parsed) is returned. Otherwise, \a from should be omitted and
4698 this function returns the text described by just the digits of this
4699 sequence, omitting (even when relevant) the sign.
4700
4701 \sa {QLocaleData::DigitSequence::}{DigitSequence()}
4702*/
4703
4704/*!
4705 \fn QLocaleData::DigitSequence QLocaleData::DigitSequence::first(qsizetype count) const
4706
4707 Returns a DigitSequence describing a prefix of this.
4708
4709 The result describes the first \a count ASCII characters to which the
4710 sequence corresponds and their positions within the parsed text. The value
4711 of \a count must not be negative or exceed \c size().
4712*/
4713
4714/*!
4715 \fn QLocaleData::DigitSequence QLocaleData::DigitSequence::last(qsizetype count) const
4716
4717 Returns a DigitSequence describing a tail of this.
4718
4719 The result describes the last \a count ASCII characters to which the
4720 sequence corresponds. The value of \a count must not be negative or exceed
4721 \c size(). The result is equivalent to \c{sliced(size() - count)}.
4722*/
4723
4724/*!
4725 \fn QLocaleData::DigitSequence QLocaleData::DigitSequence::sliced(qsizetype from) const
4726
4727 Returns a DigitSequence describing a tail of this.
4728
4729 This skips over the text to which the first \a from ASCII characters of the
4730 sequence correspond, to describe the remainder and their positions within
4731 the parsed text. The value of \a from must not be negative or exceed \c
4732 size().
4733*/
4734
4735/*!
4736 \overload
4737 \fn QLocaleData::DigitSequence QLocaleData::DigitSequence::sliced(qsizetype from, qsizetype count) const
4738
4739 Returns a DigitSequence describing a subsequence of this.
4740
4741 This skips over the portion of the text to which first \a from ASCII
4742 characters correspond and describes the portion described by the next \a
4743 count ASCII characters. The value of \a from must not be negative or exceed
4744 \c size(). The value of \a count must not be negative or exceed \c{size() -
4745 from}. The result is equivalent to \c{sliced(from).first(count)}.
4746*/
4747
4748/*!
4749 Scan \a text for an initial sequence of digits.
4750
4751 The given \a numeric provides data relevant to number-parsing, including
4752 what constitute digits. Options in \a flags control whether a leading sign
4753 may be included. If \a from is passed, the scan starts at this index in \a
4754 text, otherwise from the start. If \a maxDigits is given and not negative,
4755 the scan stops after this many digits.
4756
4757 The resulting \l {QLocaleData::}{DigitSequence} contains the parsed digit
4758 sequence, \c digits, describes the positions of digits within \a text, by \c
4759 digitBounds, and (where allowed) reports any sign. Differences between
4760 entries in digitBounds are the UTF-16 lengths of the successive digits in
4761 the source text. These may be any mixture of locale-appropriate digits and
4762 the C locale's ASCII digits.
4763
4764 The end of the text parsed is always \c {digitBounds.back()}. When \c digits
4765 is empty, this is \c digitBounds[0]: this is either where the sign ended,
4766 when \c hasSign(), or the value of \c from passed to the
4767 constructor. Otherwise, each \c{digits[i]} represents
4768 \c{text.first(digitBounds[i+1]).sliced(digitBounds[i])} and the whole text
4769 parsed is \c{text.first(digitBounds.back()).sliced(from)}. Either way, if \c
4770 hasSign(), its \c sign represents
4771 \c{text.first(digitBounds.front()).sliced(from)}.
4772
4773 \sa {QLocaleData::DigitSequence::}{used()}, QLocaleData::digitSequence()
4774*/
4775QLocaleData::DigitSequence::DigitSequence(QStringView text, NumericData &&numeric,
4776 Options flags, qsizetype from, qsizetype maxDigits)
4777 : digitBounds({ from })
4778{
4779 NumericTokenizer tokens(text, std::move(numeric), IntegerMode, from);
4780 if (tokens.done())
4781 return;
4782 char currentToken = tokens.nextToken();
4783 if (!currentToken)
4784 return;
4785
4786 // Handle any leading sign:
4787 if (currentToken == '+' || currentToken == '-') {
4788 if (!flags.testFlag(Option::AllowSign))
4789 return;
4790 digitBounds[0] = tokens.index();
4791 sign = currentToken;
4792 currentToken = '\0';
4793 }
4794
4795 // Iterate what remains:
4796 while ((currentToken || !tokens.done())
4797 && (maxDigits < 0 || digits.size() < maxDigits)) {
4798 if (!currentToken)
4799 currentToken = tokens.nextToken();
4800 if (!currentToken)
4801 return;
4802
4803 if (currentToken < '0' || currentToken > '9')
4804 return; // What we got was not a digit in our locale.
4805
4806 // We have a digit.
4807 digits.push_back(currentToken);
4808 digitBounds.push_back(tokens.index());
4809 currentToken = '\0';
4810 }
4811 Q_ASSERT(digitBounds.size() == digits.size() + 1); // Class invariant.
4812}
4813
4814/*!
4815 \internal
4816 QLocaleData::DigitSequence QLocaleData::digitSequence(QStringView text, QLocaleData::DigitSequence::Options, qsizetype from, qsizetype maxDigits)
4817 \brief Returns a DigitSequence describing some portion of \a text starting at \a from.
4818
4819 As for the \l{QLocaleData::}{DigitSequence} constructor, supplying the
4820 \l{QLocaleData::}{NumericData} for this QLocaleData instance and the
4821 IntegerMode as the relevant argument to it.
4822
4823 If \a maxDigits is not passed, this will scan as many digits as it finds
4824 (after, where relevant, a sign) in a prefix of \a text and allocate space in
4825 which to store the results. If \a text is not known to be of sensible length
4826 for the data it is expected to contain, this may involve unbounded scanning
4827 and allocation. Callers should consider how many digits they can possibly
4828 have a use for and pass that, or a conservative upper-bound estimate of it,
4829 for \a maxDigits whenever they reasonably can.
4830
4831 If digits beyond that are technically acceptable (albeit useless), for
4832 example surplus digits in a fractional part, the caller can use a
4833 QStringIterator on \a text, starting at the return's endIndex(), and
4834 iterating as long as NumericData::digitValue() >= 0, to skip over the
4835 surplus. (You can also use digitValue() > 0 to resolve the case where a
4836 trailing 5 followed by 0s leaves open the possibility of an exact half in
4837 need of rounding according to the parity of the digit before the 5.)
4838*/
4839
4840/*
4841 Converts a number in locale representation to the C locale equivalent.
4842
4843 Only has to guarantee that a string that is a correct representation of a
4844 number will be converted. Checks signs, separators and digits appear in all
4845 the places they should, and nowhere else.
4846
4847 Returns true precisely if the number appears to be well-formed, modulo
4848 things a parser for C Locale strings (without digit-grouping separators;
4849 they're stripped) will catch. When it returns true, it records (and
4850 '\0'-terminates) the C locale representation in *result.
4851
4852 Note: only QString integer-parsing methods have a base parameter (hence need
4853 to cope with letters as possible digits); but these are now all routed via
4854 byteArrayToU?LongLong(), so no longer come via here. The QLocale
4855 number-parsers only work in decimal, so don't have to cope with any digits
4856 other than 0 through 9.
4857*/
4858bool QLocaleData::numberToCLocale(QStringView s, QLocale::NumberOptions number_options,
4859 NumberMode mode, CharBuff *result) const
4860{
4861 s = s.trimmed();
4862 if (s.size() < 1)
4863 return false;
4864 NumericTokenizer tokens(s, NumericData(this, mode), mode);
4865
4866 // Reflects order constraints on possible parts of a number:
4867 enum { Whole, Grouped, Fraction, Exponent, Name } stage = Whole;
4868 // Grouped is just Whole with some digit-grouping separators in it.
4869 // Name is Inf or NaN; excludes all others (so none can be after it).
4870
4871 // Fractional part *or* whole-number part can be empty, but not both, unless
4872 // we have Name. Exponent must have some digits in it.
4873 bool wantDigits = true;
4874
4875 // Digit-grouping details (all modes):
4876 bool needHigherGroup = false; // Set when first group is too short to be the only one
4877 qsizetype digitsInGroup = 0;
4878 const QLocaleData::GroupSizes &grouping = tokens.groupSizes();
4879 const auto badLeastGroup = [&]() {
4880 // In principle we could object to a complete absence of grouping, when
4881 // digitsInGroup >= qMax(grouping.first, grouping.least), unless the
4882 // locale itself would omit them. However, when merely not rejecting
4883 // grouping separators, we have historically accepted ungrouped digits,
4884 // so objecting now would break existing code.
4885 if (stage == Grouped) {
4886 Q_ASSERT(!number_options.testFlag(QLocale::RejectGroupSeparator));
4887 // First group was invalid if it was short and we've not seen a separator since:
4888 if (needHigherGroup)
4889 return true;
4890 // Were there enough digits since the last group separator?
4891 if (digitsInGroup != grouping.least)
4892 return true;
4893 }
4894 return false;
4895 };
4896
4897 char last = '\0';
4898 while (!tokens.done()) {
4899 char out = tokens.nextToken();
4900 if (out == 0)
4901 return false;
4902
4903 // Note that out can only be '.', 'e' or an inf/NaN character if the
4904 // mode allows it (else nextToken() would return 0 instead), so we don't
4905 // need to check mode.
4906 if (out == '.') {
4907 if (stage > Grouped) // Too late to start a fractional part.
4908 return false;
4909
4910 if (tokens.fractionGroupClash() && badLeastGroup()
4911 && digitsInGroup == grouping.higher) {
4912 // Reinterpret '.' as ',' (as they're indistinguishable) to
4913 // interpret the recent digits as a group, with the least to
4914 // follow (hopefully of a suitable length):
4915 out = ',';
4916 stage = Grouped;
4917 needHigherGroup = false;
4918 digitsInGroup = 0;
4919 } else {
4920 // That's the end of the integral part - check size of last group:
4921 if (badLeastGroup())
4922 return false;
4923 stage = Fraction;
4924 }
4925 } else if (out == 'e') {
4926 if (wantDigits || stage == Name || stage > Fraction)
4927 return false;
4928
4929 if (stage < Fraction) {
4930 // The 'e' ends the whole-number part, so check its last group:
4931 if (badLeastGroup())
4932 return false;
4933 } else if (number_options.testFlag(QLocale::RejectTrailingZeroesAfterDot)) {
4934 // In a fractional part, a 0 just before the exponent is trailing:
4935 if (last == '0')
4936 return false;
4937 }
4938 stage = Exponent;
4939 wantDigits = true; // We need some in the exponent
4940 } else if (out == ',') {
4941 // (If tokens.fractionGroupClash(), a comma only comes out of
4942 // nextToken() if there's a later separator, since the last is
4943 // always treated as dot. So if we have a comma here, treating it as
4944 // a dot wouldn't save the parse: the later dot-or-comma would make
4945 // the text malformed.)
4946 if (number_options.testFlag(QLocale::RejectGroupSeparator))
4947 return false;
4948
4949 switch (stage) {
4950 case Whole:
4951 // Check size of most significant group
4952 if (digitsInGroup == 0
4953 || digitsInGroup > qMax(grouping.first, grouping.higher)) {
4954 return false;
4955 }
4956 Q_ASSERT(!needHigherGroup);
4957 // First group is only allowed fewer than grouping.first digits
4958 // if it's followed by a grouping.higher group, i.e. there's a
4959 // later group separator:
4960 if (grouping.first > digitsInGroup)
4961 needHigherGroup = true;
4962 stage = Grouped;
4963 break;
4964 case Grouped:
4965 // Check size of group between two separators:
4966 if (digitsInGroup != grouping.higher)
4967 return false;
4968 needHigherGroup = false; // We just found it, if needed.
4969 break;
4970 // Only allow group chars within the whole-number part:
4971 case Fraction:
4972 case Exponent:
4973 case Name:
4974 return false;
4975 }
4976 digitsInGroup = 0;
4977 } else if (isAsciiDigit(out)) {
4978 if (stage == Name)
4979 return false;
4980 if (out == '0' && number_options.testFlag(QLocale::RejectLeadingZeroInExponent)
4981 && stage > Fraction && !tokens.done() && !isAsciiDigit(last)) {
4982 // After the exponent there can only be '+', '-' or digits. If
4983 // we find a '0' directly after some non-digit, then that is a
4984 // leading zero, acceptable only if it is the whole exponent.
4985 return false;
4986 }
4987 wantDigits = false;
4988 ++digitsInGroup;
4989 } else if (stage == Whole && tokens.isInfNanChar(out)) {
4990 if (!wantDigits) // Mixed digits with Inf/NaN
4991 return false;
4992 wantDigits = false;
4993 stage = Name;
4994 }
4995 // else: nothing special to do.
4996
4997 last = out;
4998 if (out != ',') // Leave group separators out of the result.
4999 result->append(out);
5000 }
5001 if (wantDigits)
5002 return false;
5003
5004 if (!number_options.testFlag(QLocale::RejectGroupSeparator)) {
5005 // If this is the end of the whole-part, check least significant group:
5006 if (stage < Fraction && badLeastGroup())
5007 return false;
5008 }
5009
5010 if (number_options.testFlag(QLocale::RejectTrailingZeroesAfterDot) && stage == Fraction) {
5011 // In the fractional part, a final zero is trailing:
5012 if (last == '0')
5013 return false;
5014 }
5015
5016 return true;
5017}
5018
5020QLocaleData::validateChars(QStringView str, NumberMode numMode, int decDigits,
5021 QLocale::NumberOptions number_options) const
5022{
5023 ParsingResult result;
5024 result.buff.reserve(str.size());
5025
5026 enum { Whole, Fractional, Exponent } state = Whole;
5027 const bool scientific = numMode == DoubleScientificMode;
5028 NumericTokenizer tokens(str, NumericData(this, numMode), numMode);
5029 char last = '\0';
5030
5031 while (!tokens.done()) {
5032 char c = tokens.nextToken();
5033
5034 if (isAsciiDigit(c)) {
5035 switch (state) {
5036 case Whole:
5037 // Nothing special to do (unless we want to check grouping sizes).
5038 break;
5039 case Fractional:
5040 // If a double has too many digits in its fractional part it is Invalid.
5041 if (decDigits-- == 0)
5042 return {};
5043 break;
5044 case Exponent:
5045 if (!isAsciiDigit(last)) {
5046 // This is the first digit in the exponent (there may have beena '+'
5047 // or '-' in before). If it's a zero, the exponent is zero-padded.
5048 if (c == '0' && (number_options & QLocale::RejectLeadingZeroInExponent))
5049 return {};
5050 }
5051 break;
5052 }
5053
5054 } else {
5055 switch (c) {
5056 case '.':
5057 // If an integer has a decimal point, it is Invalid.
5058 // A double can only have one, at the end of its whole-number part.
5059 if (numMode == IntegerMode || state != Whole)
5060 return {};
5061 // Even when decDigits is 0, we do allow the decimal point to be
5062 // present - just as long as no digits follow it.
5063
5064 state = Fractional;
5065 break;
5066
5067 case '+':
5068 case '-':
5069 // A sign can only appear at the start or after the e of scientific:
5070 if (last != '\0' && !(scientific && last == 'e'))
5071 return {};
5072 break;
5073
5074 case ',':
5075 // Grouping is only allowed after a digit in the whole-number portion:
5076 if ((number_options & QLocale::RejectGroupSeparator) || state != Whole
5077 || !isAsciiDigit(last)) {
5078 return {};
5079 }
5080 // We could check grouping sizes are correct, but fixup()s are
5081 // probably better off correcting any misplacement instead.
5082 break;
5083
5084 case 'e':
5085 // Only one e is allowed and only in scientific:
5086 if (!scientific || state == Exponent)
5087 return {};
5088 state = Exponent;
5089 break;
5090
5091 default:
5092 // Nothing else can validly appear in a number.
5093 // NumericTokenizer allows letters of "inf" and "nan", but
5094 // validators don't accept those values.
5095 // For anything else, tokens.nextToken() must have returned 0.
5096 Q_ASSERT(!c || c == 'a' || c == 'f' || c == 'i' || c == 'n');
5097 return {};
5098 }
5099 }
5100
5101 last = c;
5102 if (c != ',') // Skip grouping
5103 result.buff.append(c);
5104 }
5105
5107
5108 // Intermediate if it ends with any character that requires a digit after
5109 // it to be valid e.g. group separator, sign, or exponent
5110 if (last == ',' || last == '-' || last == '+' || last == 'e')
5112
5113 return result;
5114}
5115
5116double QLocaleData::stringToDouble(QStringView str, bool *ok,
5117 QLocale::NumberOptions number_options) const
5118{
5119 CharBuff buff;
5120 if (!numberToCLocale(str, number_options, DoubleScientificMode, &buff)) {
5121 if (ok != nullptr)
5122 *ok = false;
5123 return 0.0;
5124 }
5125 auto r = qt_asciiToDouble(buff.constData(), buff.size());
5126 if (ok != nullptr)
5127 *ok = r.ok();
5128 return r.result;
5129}
5130
5132QLocaleData::stringToLongLong(QStringView str, int base,
5133 QLocale::NumberOptions number_options) const
5134{
5135 CharBuff buff;
5136 if (!numberToCLocale(str, number_options, IntegerMode, &buff))
5137 return {};
5138
5139 return bytearrayToLongLong(QByteArrayView(buff), base);
5140}
5141
5143QLocaleData::stringToUnsLongLong(QStringView str, int base,
5144 QLocale::NumberOptions number_options) const
5145{
5146 CharBuff buff;
5147 if (!numberToCLocale(str, number_options, IntegerMode, &buff))
5148 return {};
5149
5150 return bytearrayToUnsLongLong(QByteArrayView(buff), base);
5151}
5152
5153static bool checkParsed(QByteArrayView num, qsizetype used)
5154{
5155 if (used <= 0)
5156 return false;
5157
5158 const qsizetype len = num.size();
5159 if (used < len && num[used] != '\0') {
5160 while (used < len && ascii_isspace(num[used]))
5161 ++used;
5162 }
5163
5164 if (used < len && num[used] != '\0')
5165 // we stopped at a non-digit character after converting some digits
5166 return false;
5167
5168 return true;
5169}
5170
5171QSimpleParsedNumber<qint64> QLocaleData::bytearrayToLongLong(QByteArrayView num, int base)
5172{
5173 auto r = qstrntoll(num.data(), num.size(), base);
5174 if (!checkParsed(num, r.used))
5175 return {};
5176 return r;
5177}
5178
5179QSimpleParsedNumber<quint64> QLocaleData::bytearrayToUnsLongLong(QByteArrayView num, int base)
5180{
5181 auto r = qstrntoull(num.data(), num.size(), base);
5182 if (!checkParsed(num, r.used))
5183 return {};
5184 return r;
5185}
5186
5187/*!
5188 \since 4.8
5189
5190 \enum QLocale::CurrencySymbolFormat
5191
5192 Specifies the format of the currency symbol.
5193
5194 \value CurrencyIsoCode a ISO-4217 code of the currency.
5195 \value CurrencySymbol a currency symbol.
5196 \value CurrencyDisplayName a user readable name of the currency.
5197*/
5198
5199/*!
5200 \since 4.8
5201 Returns a currency symbol according to the \a format.
5202*/
5203QString QLocale::currencySymbol(CurrencySymbolFormat format) const
5204{
5205#ifndef QT_NO_SYSTEMLOCALE
5206 if (d->m_data == &systemLocaleData) {
5207 auto res = systemLocale()->query(QSystemLocale::CurrencySymbol, format).toString();
5208 if (!res.isEmpty())
5209 return res;
5210 }
5211#endif
5212 switch (format) {
5213 case CurrencySymbol:
5214 return d->m_data->currencySymbol().getData(currency_symbol_data);
5215 case CurrencyDisplayName:
5216 return d->m_data->currencyDisplayName().getData(currency_display_name_data);
5217 case CurrencyIsoCode: {
5218 const char *code = d->m_data->m_currency_iso_code;
5219 if (auto len = qstrnlen(code, 3))
5220 return QString::fromLatin1(code, qsizetype(len));
5221 break;
5222 }
5223 }
5224 return QString();
5225}
5226
5227/*!
5228 \since 4.8
5229
5230 Returns a localized string representation of \a value as a currency.
5231 If the \a symbol is provided it is used instead of the default currency symbol.
5232
5233 \sa currencySymbol()
5234*/
5235QString QLocale::toCurrencyString(qlonglong value, const QString &symbol) const
5236{
5237#ifndef QT_NO_SYSTEMLOCALE
5238 if (d->m_data == &systemLocaleData) {
5239 QSystemLocale::CurrencyToStringArgument arg(value, symbol);
5240 auto res = systemLocale()->query(QSystemLocale::CurrencyToString,
5241 QVariant::fromValue(arg)).toString();
5242 if (!res.isEmpty())
5243 return res;
5244 }
5245#endif
5246 QLocaleData::DataRange range = d->m_data->currencyFormatNegative();
5247 if (!range.size || value >= 0)
5248 range = d->m_data->currencyFormat();
5249 else
5250 value = -value;
5251 QString str = toString(value);
5252 QString sym = symbol.isNull() ? currencySymbol() : symbol;
5253 if (sym.isEmpty())
5254 sym = currencySymbol(CurrencyIsoCode);
5255 return range.viewData(currency_format_data).arg(str, sym);
5256}
5257
5258/*!
5259 \since 4.8
5260 \overload
5261*/
5262QString QLocale::toCurrencyString(qulonglong value, const QString &symbol) const
5263{
5264#ifndef QT_NO_SYSTEMLOCALE
5265 if (d->m_data == &systemLocaleData) {
5266 QSystemLocale::CurrencyToStringArgument arg(value, symbol);
5267 auto res = systemLocale()->query(QSystemLocale::CurrencyToString,
5268 QVariant::fromValue(arg)).toString();
5269 if (!res.isEmpty())
5270 return res;
5271 }
5272#endif
5273 QString str = toString(value);
5274 QString sym = symbol.isNull() ? currencySymbol() : symbol;
5275 if (sym.isEmpty())
5276 sym = currencySymbol(CurrencyIsoCode);
5277 return d->m_data->currencyFormat().getData(currency_format_data).arg(str, sym);
5278}
5279
5280/*!
5281 \since 5.7
5282 \overload toCurrencyString()
5283
5284 Returns a localized string representation of \a value as a currency.
5285 If the \a symbol is provided it is used instead of the default currency symbol.
5286 If the \a precision is provided it is used to set the precision of the currency value.
5287
5288 \sa currencySymbol()
5289 */
5290QString QLocale::toCurrencyString(double value, const QString &symbol, int precision) const
5291{
5292#ifndef QT_NO_SYSTEMLOCALE
5293 if (d->m_data == &systemLocaleData) {
5294 QSystemLocale::CurrencyToStringArgument arg(value, symbol);
5295 auto res = systemLocale()->query(QSystemLocale::CurrencyToString,
5296 QVariant::fromValue(arg)).toString();
5297 if (!res.isEmpty())
5298 return res;
5299 }
5300#endif
5301 QLocaleData::DataRange range = d->m_data->currencyFormatNegative();
5302 if (!range.size || value >= 0)
5303 range = d->m_data->currencyFormat();
5304 else
5305 value = -value;
5306 QString str = toString(value, 'f', precision == -1 ? d->m_data->m_currency_digits : precision);
5307 QString sym = symbol.isNull() ? currencySymbol() : symbol;
5308 if (sym.isEmpty())
5309 sym = currencySymbol(CurrencyIsoCode);
5310 return range.viewData(currency_format_data).arg(str, sym);
5311}
5312
5313/*!
5314 \fn QString QLocale::toCurrencyString(float i, const QString &symbol, int precision) const
5315 \overload toCurrencyString()
5316*/
5317
5318/*!
5319 \since 5.10
5320
5321 \enum QLocale::DataSizeFormat
5322
5323 Specifies the format for representation of data quantities.
5324
5325 \omitvalue DataSizeBase1000
5326 \omitvalue DataSizeSIQuantifiers
5327 \value DataSizeIecFormat format using base 1024 and IEC prefixes: KiB, MiB, GiB, ...
5328 \value DataSizeTraditionalFormat format using base 1024 and SI prefixes: kB, MB, GB, ...
5329 \value DataSizeSIFormat format using base 1000 and SI prefixes: kB, MB, GB, ...
5330
5331 \sa formattedDataSize()
5332*/
5333
5334/*!
5335 \since 5.10
5336
5337 Converts a size in bytes to a human-readable localized string, comprising a
5338 number and a quantified unit. The quantifier is chosen such that the number
5339 is at least one, and as small as possible. For example if \a bytes is
5340 16384, \a precision is 2, and \a format is \l DataSizeIecFormat (the
5341 default), this function returns "16.00 KiB"; for 1330409069609 bytes it
5342 returns "1.21 GiB"; and so on. If \a format is \l DataSizeIecFormat or
5343 \l DataSizeTraditionalFormat, the given number of bytes is divided by a
5344 power of 1024, with result less than 1024; for \l DataSizeSIFormat, it is
5345 divided by a power of 1000, with result less than 1000.
5346 \c DataSizeIecFormat uses the new IEC standard quantifiers Ki, Mi and so on,
5347 whereas \c DataSizeSIFormat uses the older SI quantifiers k, M, etc., and
5348 \c DataSizeTraditionalFormat abuses them.
5349*/
5350QString QLocale::formattedDataSize(qint64 bytes, int precision, DataSizeFormats format) const
5351{
5352 int power, base = 1000;
5353 if (!bytes) {
5354 power = 0;
5355 } else if (format & DataSizeBase1000) {
5356 constexpr auto log10_1000 = 3; // std::log10(1000U)
5357 power = int(std::log10(QtPrivate::qUnsignedAbs(bytes))) / log10_1000;
5358 } else {
5359 constexpr auto log2_1024 = 10; // QtPrivate::log2i(1024U);
5360 power = QtPrivate::log2i(QtPrivate::qUnsignedAbs(bytes)) / log2_1024;
5361 base = 1024;
5362 }
5363 // Only go to doubles if we'll be using a quantifier:
5364 const QString number = power
5365 ? toString(bytes / std::pow(double(base), power), 'f', qMin(precision, 3 * power))
5366 : toString(bytes);
5367
5368 // We don't support sizes in units larger than exbibytes because
5369 // the number of bytes would not fit into qint64.
5370 Q_ASSERT(power <= 6 && power >= 0);
5371 QStringView unit;
5372 if (power > 0) {
5373 QLocaleData::DataRange range = (format & DataSizeSIQuantifiers)
5374 ? d->m_data->byteAmountSI() : d->m_data->byteAmountIEC();
5375 unit = range.viewListEntry(byte_unit_data, power - 1);
5376 } else {
5377 unit = d->m_data->byteCount().viewData(byte_unit_data);
5378 }
5379
5380 return number + u' ' + unit;
5381}
5382
5383/*!
5384 \since 4.8
5385 \brief List of locale names for use in selecting translations
5386
5387 Each entry in the returned list is the name of a locale suitable to the
5388 user's preferences for what to translate the UI into. Where a name in the
5389 list is composed of several tags, they are joined as indicated by \a
5390 separator. Prior to Qt 6.7 a dash was used as separator.
5391
5392 For example, using the default separator QLocale::TagSeparator::Dash, if the
5393 user has configured their system to use English as used in the USA, the list
5394 would be "en-Latn-US", "en-US", "en-Latn", "en". The order of entries is the
5395 order in which to check for translations; earlier items in the list are to
5396 be preferred over later ones. If your translation files (or other resources
5397 specific to locale) use underscores, rather than dashes, to separate locale
5398 tags, pass QLocale::TagSeparator::Underscore as \a separator.
5399
5400 Returns a list of locale names. This may include multiple languages,
5401 especially for the system locale when multiple UI translation languages are
5402 configured. The order of entries is significant. For example, for the system
5403 locale, it reflects user preferences.
5404
5405 Prior to Qt 6.9, the list only contained explicitly configured locales and
5406 their equivalents. This led some callers to add truncations (such as from
5407 'en-Latn-DE' to 'en') as fallbacks. This could sometimes result in
5408 inappropriate choices, especially if these were tried before later entries
5409 that would be more appropriate fallbacks.
5410
5411 Starting from Qt 6.9, reasonable truncations are included in the returned
5412 list \e after all entries equivalent to the explicitly specified
5413 locales. This change allows for more accurate fallback options without
5414 callers needing to do any truncation.
5415
5416 Users can explicitly include preferred fallback locales (such as en-US) in
5417 their system configuration to control the order of preference. You are
5418 advised to rely on the order of entries in uiLanguages() rather than using
5419 custom fallback methods.
5420
5421 Most likely you do not need to use this function directly, but just pass the
5422 QLocale object to the QTranslator::load() function.
5423
5424 \sa QTranslator, bcp47Name()
5425*/
5426QStringList QLocale::uiLanguages(TagSeparator separator) const
5427{
5428 const char sep = char(separator);
5429 QStringList uiLanguages;
5430 if (uchar(sep) > 0x7f) {
5431 badSeparatorWarning("uiLanguages", sep);
5432 return uiLanguages;
5433 }
5434 QList<QLocaleId> localeIds;
5435#ifdef QT_NO_SYSTEMLOCALE
5436 constexpr bool isSystem = false;
5437#else
5438 const bool isSystem = d->m_data == &systemLocaleData;
5439 if (isSystem) {
5440 uiLanguages = systemLocale()->query(QSystemLocale::UILanguages).toStringList();
5441 if (separator != TagSeparator::Dash) {
5442 // Map from default separator, Dash, used by backends:
5443 const QChar join = QLatin1Char(sep);
5444 uiLanguages.replaceInStrings(u"-", QStringView(&join, 1));
5445 }
5446 // ... but we need to include likely-adjusted forms of each of those, too.
5447 // For now, collect up locale Ids representing the entries, for later processing:
5448 for (const auto &entry : std::as_const(uiLanguages))
5449 localeIds.append(QLocaleId::fromName(entry));
5450 if (localeIds.isEmpty())
5451 localeIds.append(systemLocale()->fallbackLocale().d->m_data->id());
5452 /* Note: Darwin allows entirely independent choice of locale and of
5453 preferred languages, so it's possible the locale implied by
5454 LanguageId, ScriptId and TerritoryId is absent from the UILanguages
5455 list and that this faithfully reflects the user's wishes. None the
5456 less, we include it (if it isn't C) in the list below, after the last
5457 with the same language and script or (if none has) at the end, in
5458 case there is no better option available. (See, QTBUG-104930.)
5459 */
5460 const QString name = QString::fromLatin1(d->m_data->id().name(sep)); // Raw name
5461 if (!name.isEmpty() && language() != C && !uiLanguages.contains(name)) {
5462 // That uses contains(name) as a cheap pre-test, but there may be an
5463 // entry that matches this on purging likely subtags.
5464 const QLocaleId id = d->m_data->id();
5465 const QLocaleId max = id.withLikelySubtagsAdded();
5466 const QLocaleId mine = max.withLikelySubtagsRemoved();
5467 // Default to putting at the end:
5468 qsizetype lastAlike = uiLanguages.size() - 1;
5469 bool seen = false;
5470 for (qsizetype i = 0; !seen && i < uiLanguages.size(); ++i) {
5471 const auto its = QLocaleId::fromName(uiLanguages.at(i)).withLikelySubtagsAdded();
5472 seen = its.withLikelySubtagsRemoved() == mine;
5473 if (!seen && its.language_id == max.language_id && its.script_id == max.script_id)
5474 lastAlike = i;
5475 }
5476 if (!seen) {
5477 localeIds.insert(lastAlike + 1, id);
5478 uiLanguages.insert(lastAlike + 1, QString::fromLatin1(id.name(sep)));
5479 }
5480 }
5481 } else
5482#endif
5483 {
5484 localeIds.append(d->m_data->id());
5485 }
5486
5487 // First pass: add all likely-equivalents of each entry immediately after
5488 // it, in decreasing order of specificity.
5489 for (qsizetype i = localeIds.size(); i-- > 0; ) {
5490 const QLocaleId id = localeIds.at(i);
5491 Q_ASSERT(id.language_id);
5492 if (id.language_id == C) {
5493 if (!uiLanguages.contains(u"C"_s))
5494 uiLanguages.append(u"C"_s);
5495 // Attempt no likely sub-tag amendments to C.
5496 continue;
5497 }
5498
5499 qsizetype j;
5500 const QByteArray prior = id.name(sep);
5501 bool faithful = true; // prior matches uiLanguages.at(j - 1)
5502 if (isSystem && i < uiLanguages.size()) {
5503 // Adding likely-adjusted forms to system locale's list.
5504 faithful = uiLanguages.at(i) == QLatin1StringView(prior);
5505 Q_ASSERT(faithful
5506 // A legacy code may get mapped to an ID with a different name:
5507 || QLocaleId::fromName(uiLanguages.at(i)).name(sep) == prior);
5508 // Insert just after the entry we're supplementing:
5509 j = i + 1;
5510 } else {
5511 // Plain locale or empty system uiLanguages; just append.
5512 if (!uiLanguages.contains(QLatin1StringView(prior)))
5513 uiLanguages.append(QString::fromLatin1(prior));
5514 j = uiLanguages.size();
5515 }
5516
5517 const QLocaleId max = id.withLikelySubtagsAdded();
5518 Q_ASSERT(max.language_id);
5519 Q_ASSERT(max.language_id == id.language_id);
5520 // We can't say the same for script or territory, though.
5521
5522 // We have various candidates to consider.
5523 const auto addIfEquivalent = [&j, &uiLanguages, max, sep, &prior, faithful](QLocaleId cid) {
5524 if (cid.withLikelySubtagsAdded() == max) {
5525 if (const QByteArray name = cid.name(sep); name != prior)
5526 uiLanguages.insert(j, QString::fromLatin1(name));
5527 else if (faithful) // Later candidates are more specific, so go before.
5528 --j;
5529 }
5530 };
5531 // language
5532 addIfEquivalent({ max.language_id, 0, 0 });
5533 // language-script
5534 if (max.script_id)
5535 addIfEquivalent({ max.language_id, max.script_id, 0 });
5536 if (id.script_id && id.script_id != max.script_id)
5537 addIfEquivalent({ id.language_id, id.script_id, 0 });
5538 // language-territory
5539 if (max.territory_id)
5540 addIfEquivalent({ max.language_id, 0, max.territory_id });
5541 if (id.territory_id && id.territory_id != max.territory_id)
5542 addIfEquivalent({ id.language_id, 0, id.territory_id });
5543 // full
5544 if (max.territory_id && max.script_id)
5545 addIfEquivalent(max);
5546 if (max.territory_id && id.script_id && id.script_id != max.script_id)
5547 addIfEquivalent({ id.language_id, id.script_id, max.territory_id });
5548 if (max.script_id && id.territory_id && id.territory_id != max.territory_id)
5549 addIfEquivalent({ id.language_id, max.script_id, id.territory_id });
5550 if (id.territory_id && id.territory_id != max.territory_id
5551 && id.script_id && id.script_id != max.script_id) {
5552 addIfEquivalent(id);
5553 }
5554 }
5555
5556 // Second pass: deduplicate.
5557 // Can't use QStringList::removeDuplicates() here, because we still need
5558 // the QDuplicateTracker, later.
5559 QDuplicateTracker<QString> known(uiLanguages.size());
5560 uiLanguages.removeIf([&](const QString &s) { return known.hasSeen(s); });
5561
5562 // Third pass: add truncations, when not already present.
5563 // Cubic in list length, but hopefully that's at most a dozen or so.
5564 const QLatin1Char cut(sep);
5565 const auto hasPrefix = [cut](auto name, QStringView stem) {
5566 // A prefix only counts if it's either full or followed by a separator.
5567 return name.startsWith(stem)
5568 && (name.size() == stem.size() || name.at(stem.size()) == cut);
5569 };
5570 // As we now forward-traverse the list, add each truncation after the last
5571 // existing entry that matches its (likely-implied) language and script, if
5572 // there is one. If not, append it to the current end.
5573 //
5574 // Thus [en-NL, nl-NL, en-GB] will append en but [en-NL, en-GB, nl-NL]
5575 // will put it before nl-NL, for example. We require a script match so
5576 // we don't pick translations that the user cannot read, despite knowing
5577 // the language. (Ideally that would be a constraint the caller can opt
5578 // into / out of. See QTBUG-112765.)
5579 for (qsizetype i = 0; i < uiLanguages.size(); ++i) {
5580 const QString entry = uiLanguages.at(i);
5581 if (hasPrefix(entry, u"C") || hasPrefix(entry, u"und"))
5582 continue;
5583 qsizetype at = entry.size(); // if 0, calls lastIndexOf(cut, -1), which is in-contract
5584 while ((at = entry.lastIndexOf(cut, at - 1)) > 0) {
5585 QString prefix = entry.first(at);
5586 // Don't test with hasSeen() as we might defer adding to later, when
5587 // we'll need known to see the later entry's offering of this prefix
5588 // as a new entry.
5589 bool found = known.contains(prefix);
5590 for (qsizetype j = i + 1; !found && j < uiLanguages.size(); ++j) {
5591 QString later = uiLanguages.at(j);
5592 if (hasPrefix(later, prefix)) {
5593 // Prefix match. Leave this for later to add.
5594 found = true;
5595 break;
5596 }
5597 }
5598 if (found) // Don't duplicate.
5599 continue; // Some shorter truncations may still be missing.
5600 // Now we're committed to adding it, get it into known:
5601 (void) known.hasSeen(prefix);
5602 const QLocaleId max = QLocaleId::fromName(prefix).withLikelySubtagsAdded();
5603 bool justAfter = true;
5604 for (qsizetype j = uiLanguages.size(); j > i; ) {
5605 --j;
5606 if (QLocaleId::fromName(uiLanguages.at(j))
5607 .withLikelySubtagsAdded()
5608 .sameLanguageScript(max)) {
5609 justAfter = false;
5610 uiLanguages.insert(j + 1, std::move(prefix));
5611 break;
5612 }
5613 }
5614 if (justAfter)
5615 uiLanguages.append(std::move(prefix));
5616 }
5617 }
5618
5619 return uiLanguages;
5620}
5621
5622/*!
5623 \since 5.13
5624
5625 Returns the locale to use for collation.
5626
5627 The result is usually this locale; however, the system locale (which is
5628 commonly the default locale) will return the system collation locale.
5629 The result is suitable for passing to QCollator's constructor.
5630
5631 \sa QCollator
5632*/
5633QLocale QLocale::collation() const
5634{
5635#ifndef QT_NO_SYSTEMLOCALE
5636 if (d->m_data == &systemLocaleData) {
5637 const auto res = systemLocale()->query(QSystemLocale::Collation).toString();
5638 if (!res.isEmpty())
5639 return QLocale(res);
5640 }
5641#endif
5642 return *this;
5643}
5644
5645/*!
5646 \since 4.8
5647
5648 Returns a native name of the language for the locale. For example
5649 "Schweizer Hochdeutsch" for the Swiss-German locale.
5650
5651 \sa nativeTerritoryName(), languageToString()
5652*/
5653QString QLocale::nativeLanguageName() const
5654{
5655#ifndef QT_NO_SYSTEMLOCALE
5656 if (d->m_data == &systemLocaleData) {
5657 auto res = systemLocale()->query(QSystemLocale::NativeLanguageName).toString();
5658 if (!res.isEmpty())
5659 return res;
5660 }
5661#endif
5662 return d->m_data->endonymLanguage().getData(endonyms_data);
5663}
5664
5665/*!
5666 \since 6.2
5667
5668 Returns a native name of the territory for the locale. For example
5669 "España" for Spanish/Spain locale.
5670
5671 \sa nativeLanguageName(), territoryToString()
5672*/
5673QString QLocale::nativeTerritoryName() const
5674{
5675#ifndef QT_NO_SYSTEMLOCALE
5676 if (d->m_data == &systemLocaleData) {
5677 auto res = systemLocale()->query(QSystemLocale::NativeTerritoryName).toString();
5678 if (!res.isEmpty())
5679 return res;
5680 }
5681#endif
5682 return d->m_data->endonymTerritory().getData(endonyms_data);
5683}
5684
5685#if QT_DEPRECATED_SINCE(6, 6)
5686/*!
5687 \deprecated [6.6] Use \l nativeTerritoryName() instead.
5688 \since 4.8
5689
5690 Returns a native name of the territory for the locale. For example
5691 "España" for Spanish/Spain locale.
5692
5693 \sa nativeLanguageName(), territoryToString()
5694*/
5695QString QLocale::nativeCountryName() const
5696{
5697 return nativeTerritoryName();
5698}
5699#endif
5700
5701#ifndef QT_NO_DEBUG_STREAM
5702QDebug operator<<(QDebug dbg, const QLocale &l)
5703{
5704 QDebugStateSaver saver(dbg);
5705 const bool isSys = l == QLocale::system();
5706 dbg.nospace().noquote()
5707 << (isSys ? "QLocale::system()/* " : "QLocale(")
5708 << QLocale::languageToString(l.language()) << ", "
5709 << QLocale::scriptToString(l.script()) << ", "
5710 << QLocale::territoryToString(l.territory()) << (isSys ? " */" : ")");
5711 return dbg;
5712}
5713#endif
5714QT_END_NAMESPACE
5715
5716#ifndef QT_NO_QOBJECT
5717#include "moc_qlocale.cpp"
5718#endif
const QLocaleData *const m_data
Definition qlocale_p.h:718
QLocale::MeasurementSystem measurementSystem() const
Definition qlocale.cpp:3529
QByteArray bcp47Name(char separator='-') const
Definition qlocale.cpp:496
char32_t next(char32_t invalidAs=QChar::ReplacementCharacter)
bool hasNext() const
Combined button and popup list for selecting options.
Definition qcompare.h:111
CaseSensitivity
@ CaseInsensitive
@ CaseSensitive
Q_GLOBAL_STATIC(DefaultRoleNames, qDefaultRoleNames, { { Qt::DisplayRole, "display" }, { Qt::DecorationRole, "decoration" }, { Qt::EditRole, "edit" }, { Qt::ToolTipRole, "toolTip" }, { Qt::StatusTipRole, "statusTip" }, { Qt::WhatsThisRole, "whatsThis" }, }) const QHash< int
static unsigned calculateFlags(int fieldWidth, char32_t fillChar, const QLocale &locale)
Definition qlocale.cpp:2211
static QString calculateFiller(qsizetype padding, char32_t fillChar, qsizetype fieldWidth, const QLocaleData *localeData)
Definition qlocale.cpp:2225
QDebug operator<<(QDebug dbg, const QLocale &l)
Definition qlocale.cpp:5702
static QLocalePrivate * findLocalePrivate(QLocale::Language language, QLocale::Script script, QLocale::Territory territory)
Definition qlocale.cpp:976
static std::optional< QString > systemLocaleString(const QLocaleData *that, QSystemLocale::QueryType type)
Definition qlocale.cpp:1023
static const QSystemLocale * systemLocale()
Definition qlocale.cpp:831
static bool checkParsed(QByteArrayView num, qsizetype used)
Definition qlocale.cpp:5153
static QString rawWeekDayName(const QLocaleData *data, const int day, QLocale::FormatType type)
Definition qlocale.cpp:3331
QDataStream & operator>>(QDataStream &ds, QLocale &l)
Definition qlocale.cpp:954
#define CheckCandidate(id)
static Q_DECL_COLD_FUNCTION void badSeparatorWarning(const char *method, char sep)
Definition qlocale.cpp:1512
static QString rawStandaloneWeekDayName(const QLocaleData *data, const int day, QLocale::FormatType type)
Definition qlocale.cpp:3355
static constexpr QLocale::NumberOptions defaultNumberOptions(QLocale::Language forLanguage)
Definition qlocale.cpp:770
static QStringView findTag(QStringView name) noexcept
Definition qlocale.cpp:644
static bool validTag(QStringView tag)
Definition qlocale.cpp:653
static qsizetype scriptIndex(QStringView code, Qt::CaseSensitivity cs) noexcept
Definition qlocale.cpp:185
static const QCalendarLocale & getMonthDataFor(const QLocalePrivate *loc, const QCalendarLocale *table)
Definition qlocale.cpp:3278
static T toIntegral_helper(const QLocalePrivate *d, QStringView str, bool *ok)
Definition qlocale.cpp:1560
static bool timeFormatContainsAP(QStringView format)
Definition qlocale.cpp:2428
size_t qHash(const QLocale &key, size_t seed) noexcept
Definition qlocale.cpp:1293
bool comparesEqual(const QLocale &loc, QLocale::Language lang)
Definition qlocale.cpp:997
static qsizetype findLocaleIndexById(QLocaleId localeId) noexcept
Definition qlocale.cpp:506
static constexpr qsizetype locale_data_size
Definition qlocale.cpp:525
static void updateSystemPrivate()
Definition qlocale.cpp:843
static QString rawMonthName(const QCalendarLocale &localeData, const char16_t *monthsData, int month, QLocale::FormatType type)
Definition qlocale.cpp:3305
static qsizetype stringWidth(QStringView text)
Definition qlocale.cpp:2200
static QLocalePrivate * c_private() noexcept
Definition qlocale.cpp:764
static const QLocaleData * defaultData()
Definition qlocale.cpp:918
static QString rawStandaloneMonthName(const QCalendarLocale &localeData, const char16_t *monthsData, int month, QLocale::FormatType type)
Definition qlocale.cpp:3317
static QString localeString(const QLocaleData *that, QSystemLocale::QueryType type, QLocaleData::DataRange range)
Definition qlocale.cpp:1041
static const QLocaleData * systemData(qsizetype *sysIndex=nullptr)
Definition qlocale.cpp:878
static QString offsetFromAbbreviation(QString &&text)
Definition qlocale.cpp:3740
static qsizetype defaultIndex()
Definition qlocale.cpp:925
static constexpr char16_t single_character_data[]
static constexpr char16_t days_data[]
static constexpr QLocaleData locale_data[]
static constexpr QLocaleId likely_subtags[]
static constexpr unsigned char territory_code_list[]
static constexpr unsigned char script_code_list[]
bool qt_splitLocaleName(QStringView name, QStringView *lang=nullptr, QStringView *script=nullptr, QStringView *cntry=nullptr) noexcept
Definition qlocale.cpp:664
QString qt_readEscapedFormatString(QStringView format, qsizetype *idx)
Definition qlocale.cpp:727
#define QStringLiteral(str)
Definition qstring.h:1859
char32_t ucsFirst(const char16_t *table) const
Definition qlocale_p.h:591
Descriptor for a digit sequence within a text.
Definition qlocale_p.h:458
const GroupSizes grouping
Definition qlocale_p.h:376
QString positiveSign() const
Definition qlocale.cpp:1095
QString groupSeparator() const
Definition qlocale.cpp:1054
QSimpleParsedNumber< qint64 > stringToLongLong(QStringView str, int base, QLocale::NumberOptions options) const
Definition qlocale.cpp:5132
Q_AUTOTEST_EXPORT char32_t zeroUcs() const
Definition qlocale.cpp:1074
QString zeroDigit() const
Definition qlocale.cpp:1069
bool numberToCLocale(QStringView s, QLocale::NumberOptions number_options, NumberMode mode, CharBuff *result) const
Returns a DigitSequence describing some portion of text starting at from.
Definition qlocale.cpp:4858
QString decimalPoint() const
Definition qlocale.cpp:1049
QString doubleToString(double d, int precision=-1, DoubleForm form=DFSignificantDigits, int width=-1, unsigned flags=NoFlags) const
Definition qlocale.cpp:4050
QLocaleId id() const
Definition qlocale_p.h:554
QString listSeparator() const
Definition qlocale.cpp:1064
QString percentSign() const
Definition qlocale.cpp:1059
@ AddTrailingZeroes
Definition qlocale_p.h:272
double stringToDouble(QStringView str, bool *ok, QLocale::NumberOptions options) const
Definition qlocale.cpp:5116
QString longLongToString(qint64 l, int precision=-1, int base=10, int width=-1, unsigned flags=NoFlags) const
Definition qlocale.cpp:4293
@ DoubleScientificMode
Definition qlocale_p.h:286
@ DFSignificantDigits
Definition qlocale_p.h:266
QString exponentSeparator() const
Definition qlocale.cpp:1100
QString negativeSign() const
Definition qlocale.cpp:1090
QSimpleParsedNumber< quint64 > stringToUnsLongLong(QStringView str, int base, QLocale::NumberOptions options) const
Definition qlocale.cpp:5143
QString unsLongLongToString(quint64 l, int precision=-1, int base=10, int width=-1, unsigned flags=NoFlags) const
Definition qlocale.cpp:4308
QLocaleId withLikelySubtagsAdded() const noexcept
Definition qlocale.cpp:328
QLocaleId withLikelySubtagsRemoved() const noexcept
Definition qlocale.cpp:417
ushort script_id
Definition qlocale_p.h:247
bool operator==(QLocaleId other) const noexcept
Definition qlocale_p.h:211
ushort territory_id
Definition qlocale_p.h:247
ushort language_id
Definition qlocale_p.h:247