summaryrefslogtreecommitdiffstats
path: root/src/corelib/text/qlocale.cpp
blob: c5c6603960a37922e7e64785ea39a45c3071c048 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
// Copyright (C) 2022 The Qt Company Ltd.
// Copyright (C) 2021 Intel Corporation.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qglobal.h"

#if (defined(QT_STATIC) || defined(QT_BOOTSTRAPPED)) && defined(Q_CC_GNU_ONLY) && Q_CC_GNU >= 1000
QT_WARNING_DISABLE_GCC("-Wfree-nonheap-object") // false positive tracking
#endif

#if defined(Q_OS_MACOS)
#   include "private/qcore_mac_p.h"
#   include <CoreFoundation/CoreFoundation.h>
#endif

#include "qplatformdefs.h"

#include "qdatastream.h"
#include "qdebug.h"
#include "qhashfunctions.h"
#include "qstring.h"
#include "qlocale.h"
#include "qlocale_p.h"
#include "qlocale_tools_p.h"
#include <private/qtools_p.h>
#if QT_CONFIG(datetimeparser)
#include "private/qdatetimeparser_p.h"
#endif
#include "qnamespace.h"
#include "qdatetime.h"
#include "qstringlist.h"
#include "qvariant.h"
#include "qvarlengtharray.h"
#include "qstringbuilder.h"
#if QT_CONFIG(timezone)
#   include "qtimezone.h"
#endif
#include "private/qnumeric_p.h"
#include "private/qtools_p.h"
#include <cmath>
#ifndef QT_NO_SYSTEMLOCALE
#   include "qmutex.h"
#endif
#ifdef Q_OS_WIN
#   include <qt_windows.h>
#   include <time.h>
#endif

#include "private/qcalendarbackend_p.h"
#include "private/qgregoriancalendar_p.h"
#include "qcalendar.h"

#include <q20iterator.h>

QT_BEGIN_NAMESPACE

constexpr int QLocale::DefaultTwoDigitBaseYear;

QT_IMPL_METATYPE_EXTERN_TAGGED(QList<Qt::DayOfWeek>, QList_Qt__DayOfWeek)
#ifndef QT_NO_SYSTEMLOCALE
QT_IMPL_METATYPE_EXTERN_TAGGED(QSystemLocale::CurrencyToStringArgument,
                               QSystemLocale__CurrencyToStringArgument)
#endif

using namespace Qt::StringLiterals;
using namespace QtMiscUtils;

#ifndef QT_NO_SYSTEMLOCALE
Q_CONSTINIT static QSystemLocale *_systemLocale = nullptr;
Q_CONSTINIT static QLocaleData systemLocaleData = {};
#endif

static_assert(ascii_isspace(' '));
static_assert(ascii_isspace('\t'));
static_assert(ascii_isspace('\n'));
static_assert(ascii_isspace('\v'));
static_assert(ascii_isspace('\f'));
static_assert(ascii_isspace('\r'));
static_assert(!ascii_isspace('\0'));
static_assert(!ascii_isspace('\a'));
static_assert(!ascii_isspace('a'));
static_assert(!ascii_isspace('\177'));
static_assert(!ascii_isspace(uchar('\200')));
static_assert(!ascii_isspace(uchar('\xA0')));   // NBSP (is a space but Latin 1, not ASCII)
static_assert(!ascii_isspace(uchar('\377')));

/******************************************************************************
** Helpers for accessing Qt locale database
*/

QT_BEGIN_INCLUDE_NAMESPACE
#include "qlocale_data_p.h"
QT_END_INCLUDE_NAMESPACE

QLocale::Language QLocalePrivate::codeToLanguage(QStringView code,
                                                 QLocale::LanguageCodeTypes codeTypes) noexcept
{
    const auto len = code.size();
    if (len != 2 && len != 3)
        return QLocale::AnyLanguage;

    const char16_t uc1 = code[0].toLower().unicode();
    const char16_t uc2 = code[1].toLower().unicode();
    const char16_t uc3 = len > 2 ? code[2].toLower().unicode() : 0;

    // All language codes are ASCII.
    if (uc1 > 0x7F || uc2 > 0x7F || uc3 > 0x7F)
        return QLocale::AnyLanguage;

    const AlphaCode codeBuf = { char(uc1), char(uc2), char(uc3) };

    auto searchCode = [codeBuf](auto f) {
        return std::find_if(languageCodeList.begin(), languageCodeList.end(),
                            [=](const LanguageCodeEntry &i) { return f(i) == codeBuf; });
    };

    if (codeTypes.testFlag(QLocale::ISO639Part1) && uc3 == 0) {
        auto i = searchCode([](const LanguageCodeEntry &i) { return i.part1; });
        if (i != languageCodeList.end())
            return QLocale::Language(std::distance(languageCodeList.begin(), i));
    }

    if (uc3 != 0) {
        if (codeTypes.testFlag(QLocale::ISO639Part2B)) {
            auto i = searchCode([](const LanguageCodeEntry &i) { return i.part2B; });
            if (i != languageCodeList.end())
                return QLocale::Language(std::distance(languageCodeList.begin(), i));
        }

        // Optimization: Part 2T code if present is always the same as Part 3 code.
        // This is asserted in iso639_3.LanguageCodeData.
        if (codeTypes.testFlag(QLocale::ISO639Part2T)
            && !codeTypes.testFlag(QLocale::ISO639Part3)) {
            auto i = searchCode([](const LanguageCodeEntry &i) { return i.part2T; });
            if (i != languageCodeList.end())
                return QLocale::Language(std::distance(languageCodeList.begin(), i));
        }

        if (codeTypes.testFlag(QLocale::ISO639Part3)) {
            auto i = searchCode([](const LanguageCodeEntry &i) { return i.part3; });
            if (i != languageCodeList.end())
                return QLocale::Language(std::distance(languageCodeList.begin(), i));
        }
    }

    if (codeTypes.testFlag(QLocale::LegacyLanguageCode) && uc3 == 0) {
        // legacy codes
        if (uc1 == 'n' && uc2 == 'o') // no -> nb
            return QLocale::NorwegianBokmal;
        if (uc1 == 't' && uc2 == 'l') // tl -> fil
            return QLocale::Filipino;
        if (uc1 == 's' && uc2 == 'h') // sh -> sr[_Latn]
            return QLocale::Serbian;
        if (uc1 == 'm' && uc2 == 'o') // mo -> ro
            return QLocale::Romanian;
        // Android uses the following deprecated codes
        if (uc1 == 'i' && uc2 == 'w') // iw -> he
            return QLocale::Hebrew;
        if (uc1 == 'i' && uc2 == 'n') // in -> id
            return QLocale::Indonesian;
        if (uc1 == 'j' && uc2 == 'i') // ji -> yi
            return QLocale::Yiddish;
    }
    return QLocale::AnyLanguage;
}

QLocale::Script QLocalePrivate::codeToScript(QStringView code) noexcept
{
    const auto len = code.size();
    if (len != 4)
        return QLocale::AnyScript;

    // script is titlecased in our data
    unsigned char c0 = code[0].toUpper().toLatin1();
    unsigned char c1 = code[1].toLower().toLatin1();
    unsigned char c2 = code[2].toLower().toLatin1();
    unsigned char c3 = code[3].toLower().toLatin1();

    const unsigned char *c = script_code_list;
    for (qsizetype i = 0; i < QLocale::LastScript; ++i, c += 4) {
        if (c0 == c[0] && c1 == c[1] && c2 == c[2] && c3 == c[3])
            return QLocale::Script(i);
    }
    return QLocale::AnyScript;
}

QLocale::Territory QLocalePrivate::codeToTerritory(QStringView code) noexcept
{
    const auto len = code.size();
    if (len != 2 && len != 3)
        return QLocale::AnyTerritory;

    char16_t uc1 = code[0].toUpper().unicode();
    char16_t uc2 = code[1].toUpper().unicode();
    char16_t uc3 = len > 2 ? code[2].toUpper().unicode() : 0;

    const unsigned char *c = territory_code_list;
    for (; *c != 0; c += 3) {
        if (uc1 == c[0] && uc2 == c[1] && uc3 == c[2])
            return QLocale::Territory((c - territory_code_list)/3);
    }

    return QLocale::AnyTerritory;
}

std::array<char, 4> QLocalePrivate::languageToCode(QLocale::Language language,
                                                   QLocale::LanguageCodeTypes codeTypes)
{
    if (language == QLocale::AnyLanguage || language > QLocale::LastLanguage)
        return {};
    if (language == QLocale::C)
        return {'C'};

    const LanguageCodeEntry &i = languageCodeList[language];

    if (codeTypes.testFlag(QLocale::ISO639Part1) && i.part1.isValid())
        return i.part1.decode();

    if (codeTypes.testFlag(QLocale::ISO639Part2B) && i.part2B.isValid())
        return i.part2B.decode();

    if (codeTypes.testFlag(QLocale::ISO639Part2T) && i.part2T.isValid())
        return i.part2T.decode();

    if (codeTypes.testFlag(QLocale::ISO639Part3))
        return i.part3.decode();

    return {};
}

QLatin1StringView QLocalePrivate::scriptToCode(QLocale::Script script)
{
    if (script == QLocale::AnyScript || script > QLocale::LastScript)
        return {};
    const unsigned char *c = script_code_list + 4 * script;
    return {reinterpret_cast<const char *>(c), 4};
}

QLatin1StringView QLocalePrivate::territoryToCode(QLocale::Territory territory)
{
    if (territory == QLocale::AnyTerritory || territory > QLocale::LastTerritory)
        return {};

    const unsigned char *c = territory_code_list + 3 * territory;
    return {reinterpret_cast<const char*>(c), c[2] == 0 ? 2 : 3};
}

namespace {
struct LikelyPair
{
    QLocaleId key; // Search key.
    QLocaleId value = QLocaleId { 0, 0, 0 };
};

bool operator<(const LikelyPair &lhs, const LikelyPair &rhs)
{
    // Must match the comparison LocaleDataWriter.likelySubtags() uses when
    // sorting, see qtbase/util/locale_database.qlocalexml2cpp.py
    const auto compare = [](int lhs, int rhs) {
        // 0 sorts after all other values; lhs and rhs are passed ushort values.
        const int huge = 0x10000;
        return (lhs ? lhs : huge) - (rhs ? rhs : huge);
    };
    const auto &left = lhs.key;
    const auto &right = rhs.key;
    // Comparison order: language, region, script:
    if (int cmp = compare(left.language_id, right.language_id))
        return cmp < 0;
    if (int cmp = compare(left.territory_id, right.territory_id))
        return cmp < 0;
    return compare(left.script_id, right.script_id) < 0;
}
} // anonymous namespace

/*!
    Fill in blank fields of a locale ID.

    An ID in which some fields are zero stands for any locale that agrees with
    it in its non-zero fields.  CLDR's likely-subtag data is meant to help us
    chose which candidate to prefer.  (Note, however, that CLDR does have some
    cases where it maps an ID to a "best match" for which CLDR does not provide
    data, even though there are locales for which CLDR does provide data that do
    match the given ID.  It's telling us, unhelpfully but truthfully, what
    locale would (most likely) be meant by (someone using) the combination
    requested, even when that locale isn't yet supported.)  It may also map an
    obsolete or generic tag to a modern or more specific replacement, possibly
    filling in some of the other fields in the process (presently only for
    countries).  Note that some fields of the result may remain blank, but there
    is no more specific recommendation available.

    For the formal specification, see
    https://www.unicode.org/reports/tr35/#Likely_Subtags

    \note We also search und_script_region and und_region; they're not mentioned
    in the spec, but the examples clearly presume them and CLDR does provide
    such likely matches.
*/
QLocaleId QLocaleId::withLikelySubtagsAdded() const
{
    /* Each pattern that appears in a comments below, language_script_region and
       similar, indicates which of this's fields (even if blank) are being
       attended to in a given search; for fields left out of the pattern, the
       search uses 0 regardless of whether this has specified the field.

       If a key matches what we're searching for (possibly with a wildcard in
       the key matching a non-wildcard in our search), the tags from this that
       are specified in the key are replaced by the match (even if different);
       but the other tags of this replace what's in the match (even when the
       match does specify a value).
    */
    static_assert(std::size(likely_subtags) % 2 == 0);
    auto *pairs = reinterpret_cast<const LikelyPair *>(likely_subtags);
    auto *const afterPairs = pairs + std::size(likely_subtags) / 2;
    LikelyPair sought { *this };
    // Our array is sorted in the order that puts all candidate matches in the
    // order we would want them; ones we should prefer appear before the others.
    if (language_id) {
        // language_script_region, language_region, language_script, language:
        pairs = std::lower_bound(pairs, afterPairs, sought);
        // Single language's block isn't long enough to warrant more binary
        // chopping within it - just traverse it all:
        for (; pairs < afterPairs && pairs->key.language_id == language_id; ++pairs) {
            const QLocaleId &key = pairs->key;
            if (key.territory_id && key.territory_id != territory_id)
                continue;
            if (key.script_id && key.script_id != script_id)
                continue;
            QLocaleId value = pairs->value;
            if (territory_id && !key.territory_id)
                value.territory_id = territory_id;
            if (script_id && !key.script_id)
                value.script_id = script_id;
            return value;
        }
    }
    // und_script_region or und_region (in that order):
    if (territory_id) {
        sought.key = QLocaleId { 0, script_id, territory_id };
        pairs = std::lower_bound(pairs, afterPairs, sought);
        // Again, individual und_?_region block isn't long enough to make binary
        // chop a win:
        for (; pairs < afterPairs && pairs->key.territory_id == territory_id; ++pairs) {
            const QLocaleId &key = pairs->key;
            Q_ASSERT(!key.language_id);
            if (key.script_id && key.script_id != script_id)
                continue;
            QLocaleId value = pairs->value;
            if (language_id)
                value.language_id = language_id;
            if (script_id && !key.script_id)
                value.script_id = script_id;
            return value;
        }
    }
    // und_script:
    if (script_id) {
        sought.key = QLocaleId { 0, script_id, 0 };
        pairs = std::lower_bound(pairs, afterPairs, sought);
        if (pairs < afterPairs && pairs->key.script_id == script_id) {
            Q_ASSERT(!pairs->key.language_id && !pairs->key.territory_id);
            QLocaleId value = pairs->value;
            if (language_id)
                value.language_id = language_id;
            if (territory_id)
                value.territory_id = territory_id;
            return value;
        }
    }
    if (matchesAll()) { // Skipped all of the above.
        // CLDR has no match-all at v37, but might get one some day ...
        pairs = std::lower_bound(pairs, afterPairs, sought);
        if (pairs < afterPairs) {
            // All other keys are < match-all.
            Q_ASSERT(pairs + 1 == afterPairs);
            Q_ASSERT(pairs->key.matchesAll());
            return pairs->value;
        }
    }
    return *this;
}

QLocaleId QLocaleId::withLikelySubtagsRemoved() const
{
    QLocaleId max = withLikelySubtagsAdded();
    // language
    {
        QLocaleId id { language_id, 0, 0 };
        if (id.withLikelySubtagsAdded() == max)
            return id;
    }
    // language_region
    if (territory_id) {
        QLocaleId id { language_id, 0, territory_id };
        if (id.withLikelySubtagsAdded() == max)
            return id;
    }
    // language_script
    if (script_id) {
        QLocaleId id { language_id, script_id, 0 };
        if (id.withLikelySubtagsAdded() == max)
            return id;
    }
    return max;
}

QByteArray QLocaleId::name(char separator) const
{
    if (language_id == QLocale::AnyLanguage)
        return QByteArray();
    if (language_id == QLocale::C)
        return QByteArrayLiteral("C");

    const LanguageCodeEntry &language = languageCodeList[language_id];
    AlphaCode lang;
    qsizetype langLen;

    if (language.part1.isValid()) {
        lang = language.part1;
        langLen = 2;
    } else {
        lang = language.part2B.isValid() ? language.part2B : language.part3;
        langLen = 3;
    }

    const unsigned char *script =
            (script_id != QLocale::AnyScript ? script_code_list + 4 * script_id : nullptr);
    const unsigned char *country =
            (territory_id != QLocale::AnyTerritory
             ? territory_code_list + 3 * territory_id : nullptr);
    qsizetype len = langLen + (script ? 4 + 1 : 0) + (country ? (country[2] != 0 ? 3 : 2) + 1 : 0);
    QByteArray name(len, Qt::Uninitialized);
    char *uc = name.data();

    auto langArray = lang.decode();

    *uc++ = langArray[0];
    *uc++ = langArray[1];
    if (langLen > 2)
        *uc++ = langArray[2];

    if (script) {
        *uc++ = separator;
        *uc++ = script[0];
        *uc++ = script[1];
        *uc++ = script[2];
        *uc++ = script[3];
    }
    if (country) {
        *uc++ = separator;
        *uc++ = country[0];
        *uc++ = country[1];
        if (country[2] != 0)
            *uc++ = country[2];
    }
    return name;
}

QByteArray QLocalePrivate::bcp47Name(char separator) const
{
    if (m_data->m_language_id == QLocale::AnyLanguage)
        return QByteArray();
    if (m_data->m_language_id == QLocale::C)
        return QByteArrayLiteral("en");

    return m_data->id().withLikelySubtagsRemoved().name(separator);
}

static qsizetype findLocaleIndexById(const QLocaleId &localeId)
{
    qsizetype idx = locale_index[localeId.language_id];
    // If there are no locales for specified language (so we we've got the
    // default language, which has no associated script or country), give up:
    if (localeId.language_id && idx == 0)
        return idx;

    Q_ASSERT(localeId.acceptLanguage(locale_data[idx].m_language_id));

    do {
        if (localeId.acceptScriptTerritory(locale_data[idx].id()))
            return idx;
        ++idx;
    } while (localeId.acceptLanguage(locale_data[idx].m_language_id));

    return -1;
}

qsizetype QLocaleData::findLocaleIndex(QLocaleId lid)
{
    QLocaleId localeId = lid;
    QLocaleId likelyId = localeId.withLikelySubtagsAdded();
    const ushort fallback = likelyId.language_id;

    // Try a straight match with the likely data:
    qsizetype index = findLocaleIndexById(likelyId);
    if (index >= 0)
        return index;
    QVarLengthArray<QLocaleId, 6> tried;
    tried.push_back(likelyId);

#define CheckCandidate(id) do { \
        if (!tried.contains(id)) { \
            index = findLocaleIndexById(id); \
            if (index >= 0) \
                return index; \
            tried.push_back(id); \
        } \
    } while (false) // end CheckCandidate

    // No match; try again with raw data:
    CheckCandidate(localeId);

    // No match; try again with likely country for language_script
    if (lid.territory_id && (lid.language_id || lid.script_id)) {
        localeId.territory_id = 0;
        likelyId = localeId.withLikelySubtagsAdded();
        CheckCandidate(likelyId);

        // No match; try again with any country
        CheckCandidate(localeId);
    }

    // No match; try again with likely script for language_region
    if (lid.script_id && (lid.language_id || lid.territory_id)) {
        localeId = QLocaleId { lid.language_id, 0, lid.territory_id };
        likelyId = localeId.withLikelySubtagsAdded();
        CheckCandidate(likelyId);

        // No match; try again with any script
        CheckCandidate(localeId);
    }
#undef CheckCandidate

    // No match; return base index for initial likely language:
    return locale_index[fallback];
}

static QStringView findTag(QStringView name) noexcept
{
    const std::u16string_view v(name.utf16(), size_t(name.size()));
    const auto i = v.find_first_of(u"_-.@");
    if (i == std::string_view::npos)
        return name;
    return name.first(qsizetype(i));
}

static bool validTag(QStringView tag)
{
    // Is tag is a non-empty sequence of ASCII letters and/or digits ?
    for (QChar uc : tag) {
        const char16_t ch = uc.unicode();
        if (!isAsciiLetterOrNumber(ch))
            return false;
    }
    return tag.size() > 0;
}

static bool isScript(QStringView tag)
{
    // Every script name is 4 characters, a capital followed by three lower-case;
    // so a search for tag in allScripts *can* only match if it's aligned.
    static const QString allScripts =
        QString::fromLatin1(reinterpret_cast<const char *>(script_code_list),
                            sizeof(script_code_list) - 1);
    return tag.size() == 4 && allScripts.indexOf(tag) % 4 == 0;
}

bool qt_splitLocaleName(QStringView name, QStringView *lang, QStringView *script, QStringView *land)
{
    // Assume each of lang, script and land is nullptr or points to an empty QStringView.
    enum ParserState { NoState, LangState, ScriptState, CountryState };
    ParserState state = LangState;
    while (name.size() && state != NoState) {
        const QStringView tag = findTag(name);
        if (!validTag(tag))
            break;
        name = name.sliced(tag.size());
        const bool sep = name.size() > 0;
        if (sep) // tag wasn't all that remained; there was a separator
            name = name.sliced(1);

        switch (state) {
        case LangState:
            if (tag.size() != 2 && tag.size() != 3)
                return false;
            if (lang)
                *lang = tag;
            state = sep ? ScriptState : NoState;
            break;
        case ScriptState:
            if (isScript(tag)) {
                if (script)
                    *script = tag;
                state = sep ? CountryState : NoState;
                break;
            }
            // It wasn't a script, assume it's a country.
            Q_FALLTHROUGH();
        case CountryState:
            if (land)
                *land = tag;
            state = NoState;
            break;
        case NoState: // Precluded by loop condition !
            Q_UNREACHABLE();
            break;
        }
    }
    return state != LangState;
}

QLocaleId QLocaleId::fromName(QStringView name)
{
    QStringView lang;
    QStringView script;
    QStringView land;
    if (!qt_splitLocaleName(name, &lang, &script, &land))
        return { QLocale::C, 0, 0 };

    QLocale::Language langId = QLocalePrivate::codeToLanguage(lang);
    if (langId == QLocale::AnyLanguage)
        return { QLocale::C, 0, 0 };
    return { langId, QLocalePrivate::codeToScript(script), QLocalePrivate::codeToTerritory(land) };
}

QString qt_readEscapedFormatString(QStringView format, qsizetype *idx)
{
    qsizetype &i = *idx;

    Q_ASSERT(format.at(i) == u'\'');
    ++i;
    if (i == format.size())
        return QString();
    if (format.at(i).unicode() == '\'') { // "''" outside of a quoted string
        ++i;
        return "'"_L1;
    }

    QString result;

    while (i < format.size()) {
        if (format.at(i).unicode() == '\'') {
            if (format.mid(i + 1).startsWith(u'\'')) {
                // "''" inside a quoted string
                result.append(u'\'');
                i += 2;
            } else {
                break;
            }
        } else {
            result.append(format.at(i++));
        }
    }
    if (i < format.size())
        ++i;

    return result;
}

/*!
    \internal

    Counts the number of identical leading characters in \a s.

    If \a s is empty, returns 0.

    Otherwise, returns the number of consecutive \c{s.front()}
    characters at the start of \a s.

    \code
    qt_repeatCount(u"a");   // == 1
    qt_repeatCount(u"ab");  // == 1
    qt_repeatCount(u"aab"); // == 2
    \endcode
*/
qsizetype qt_repeatCount(QStringView s)
{
    if (s.isEmpty())
        return 0;
    const QChar c = s.front();
    qsizetype j = 1;
    while (j < s.size() && s.at(j) == c)
        ++j;
    return j;
}

Q_CONSTINIT static const QLocaleData *default_data = nullptr;
Q_CONSTINIT QBasicAtomicInt QLocalePrivate::s_generation = Q_BASIC_ATOMIC_INITIALIZER(0);

static QLocalePrivate *c_private()
{
    static QLocalePrivate c_locale(locale_data, 0, QLocale::OmitGroupSeparator, 1);
    return &c_locale;
}

#ifndef QT_NO_SYSTEMLOCALE
/******************************************************************************
** Default system locale behavior
*/

/*!
    \internal
    Constructs a QSystemLocale object.

    The constructor will automatically install this object as the system locale.
    It and the destructor maintain a stack of system locales, with the
    most-recently-created instance (that hasn't yet been deleted) used as the
    system locale. This is only intended as a way to let a platform plugin
    install its own system locale, overriding what might otherwise be provided
    for its class of platform (as Android does, differing from Linux), and to
    let tests transiently override the system or plugin-supplied one. As such,
    there should not be diverse threads creating and destroying QSystemLocale
    instances concurrently, so no attempt is made at thread-safety in managing
    the stack.

    This constructor also resets the flag that'll prompt QLocale::system() to
    re-initialize its data, so that instantiating a QSystemLocale (even
    transiently) triggers a refresh of the system locale's data. This is
    exploited by some test code.
*/
QSystemLocale::QSystemLocale() : next(_systemLocale)
{
    _systemLocale = this;

    systemLocaleData.m_language_id = 0;
}

/*!
    \internal
    Deletes the object.
*/
QSystemLocale::~QSystemLocale()
{
    if (_systemLocale == this) {
        _systemLocale = next;

        // Change to system locale => force refresh.
        systemLocaleData.m_language_id = 0;
    } else {
        for (QSystemLocale *p = _systemLocale; p; p = p->next) {
            if (p->next == this)
                p->next = next;
        }
    }
}

static const QSystemLocale *systemLocale()
{
    if (_systemLocale)
        return _systemLocale;

    // As this is only ever instantiated with _systemLocale null, it is
    // necessarily the ->next-most in any chain that may subsequently develop;
    // and it won't be destructed until exit()-time.
    static QSystemLocale globalInstance;
    return &globalInstance;
}

static void updateSystemPrivate()
{
    // This function is NOT thread-safe!
    // It *should not* be called by anything but systemData()
    // It *is* called before {system,default}LocalePrivate exist.
    const QSystemLocale *sys_locale = systemLocale();

    // tell the object that the system locale has changed.
    sys_locale->query(QSystemLocale::LocaleChanged);

    // Populate system locale with fallback as basis
    systemLocaleData = locale_data[sys_locale->fallbackLocaleIndex()];

    QVariant res = sys_locale->query(QSystemLocale::LanguageId);
    if (!res.isNull()) {
        systemLocaleData.m_language_id = res.toInt();
        systemLocaleData.m_script_id = QLocale::AnyScript; // default for compatibility
    }
    res = sys_locale->query(QSystemLocale::TerritoryId);
    if (!res.isNull()) {
        systemLocaleData.m_territory_id = res.toInt();
        systemLocaleData.m_script_id = QLocale::AnyScript; // default for compatibility
    }
    res = sys_locale->query(QSystemLocale::ScriptId);
    if (!res.isNull())
        systemLocaleData.m_script_id = res.toInt();

    // Should we replace Any values based on likely sub-tags ?

    // If system locale is default locale, update the default collator's generation:
    if (default_data == &systemLocaleData)
        QLocalePrivate::s_generation.fetchAndAddRelaxed(1);
}
#endif // !QT_NO_SYSTEMLOCALE

static const QLocaleData *systemData(qsizetype *sysIndex = nullptr)
{
#ifndef QT_NO_SYSTEMLOCALE
    /*
      Copy over the information from the fallback locale and modify.

      If sysIndex is passed, it should be the m_index of the system locale's
      QLocalePrivate, which we'll update if it needs it.

      This modifies (cross-thread) global state, so is mutex-protected.
    */
    {
        Q_CONSTINIT static QLocaleId sysId;
        bool updated = false;

        Q_CONSTINIT static QBasicMutex systemDataMutex;
        systemDataMutex.lock();
        if (systemLocaleData.m_language_id == 0) {
            updateSystemPrivate();
            updated = true;
        }
        // Initialization of system private has *sysIndex == -1 to hit this.
        if (sysIndex && (updated || *sysIndex < 0)) {
            const QLocaleId nowId = systemLocaleData.id();
            if (sysId != nowId || *sysIndex < 0) {
                // This look-up may be expensive:
                *sysIndex = QLocaleData::findLocaleIndex(nowId);
                sysId = nowId;
            }
        }
        systemDataMutex.unlock();
    }

    return &systemLocaleData;
#else
    Q_UNUSED(sysIndex);
    return locale_data;
#endif
}

static const QLocaleData *defaultData()
{
    if (!default_data)
        default_data = systemData();
    return default_data;
}

static qsizetype defaultIndex()
{
    const QLocaleData *const data = defaultData();
#ifndef QT_NO_SYSTEMLOCALE
    if (data == &systemLocaleData) {
        // Work out a suitable index matching the system data, for use when
        // accessing calendar data, when not fetched from system.
        return QLocaleData::findLocaleIndex(data->id());
    }
#endif

    using QtPrivate::q_points_into_range;
    Q_ASSERT(q_points_into_range(data, locale_data));
    return data - locale_data;
}

const QLocaleData *QLocaleData::c()
{
    Q_ASSERT(locale_index[QLocale::C] == 0);
    return locale_data;
}

#ifndef QT_NO_DATASTREAM
QDataStream &operator<<(QDataStream &ds, const QLocale &l)
{
    ds << l.name();
    return ds;
}

QDataStream &operator>>(QDataStream &ds, QLocale &l)
{
    QString s;
    ds >> s;
    l = QLocale(s);
    return ds;
}
#endif // QT_NO_DATASTREAM

static constexpr qsizetype locale_data_size = q20::ssize(locale_data) - 1; // trailing guard

Q_GLOBAL_STATIC(QSharedDataPointer<QLocalePrivate>, defaultLocalePrivate,
                new QLocalePrivate(defaultData(), defaultIndex()))

static QLocalePrivate *localePrivateByName(QStringView name)
{
    if (name == u"C")
        return c_private();
    const qsizetype index = QLocaleData::findLocaleIndex(QLocaleId::fromName(name));
    Q_ASSERT(index >= 0 && index < locale_data_size);
    return new QLocalePrivate(locale_data + index, index,
                              locale_data[index].m_language_id == QLocale::C
                              ? QLocale::OmitGroupSeparator : QLocale::DefaultNumberOptions);
}

static QLocalePrivate *findLocalePrivate(QLocale::Language language, QLocale::Script script,
                                         QLocale::Territory territory)
{
    if (language == QLocale::C)
        return c_private();

    qsizetype index = QLocaleData::findLocaleIndex(QLocaleId { language, script, territory });
    Q_ASSERT(index >= 0 && index < locale_data_size);
    const QLocaleData *data = locale_data + index;

    QLocale::NumberOptions numberOptions = QLocale::DefaultNumberOptions;

    // If not found, should use default locale:
    if (data->m_language_id == QLocale::C) {
        if (defaultLocalePrivate.exists())
            numberOptions = defaultLocalePrivate->data()->m_numberOptions;
        data = defaultData();
        index = defaultIndex();
    }
    return new QLocalePrivate(data, index, numberOptions);
}

static std::optional<QString>
systemLocaleString(const QLocaleData *that, QSystemLocale::QueryType type)
{
#ifndef QT_NO_SYSTEMLOCALE
    if (that != &systemLocaleData)
        return std::nullopt;

    QVariant v = systemLocale()->query(type);
    if (v.metaType() != QMetaType::fromType<QString>())
        return std::nullopt;

    return v.toString();
#else
    Q_UNUSED(that)
    Q_UNUSED(type)
    return std::nullopt;
#endif
}

static QString localeString(const QLocaleData *that, QSystemLocale::QueryType type,
                            QLocaleData::DataRange range)
{
    if (auto opt = systemLocaleString(that, type))
        return *opt;
    return range.getData(single_character_data);
}

QString QLocaleData::decimalPoint() const
{
    return localeString(this, QSystemLocale::DecimalPoint, decimalSeparator());
}

QString QLocaleData::groupSeparator() const
{
    return localeString(this, QSystemLocale::GroupSeparator, groupDelim());
}

QString QLocaleData::percentSign() const
{
    return percent().getData(single_character_data);
}

QString QLocaleData::listSeparator() const
{
    return listDelimit().getData(single_character_data);
}

QString QLocaleData::zeroDigit() const
{
    return localeString(this, QSystemLocale::ZeroDigit, zero());
}

char32_t QLocaleData::zeroUcs() const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (this == &systemLocaleData) {
        const auto text = systemLocale()->query(QSystemLocale::ZeroDigit).toString();
        if (!text.isEmpty()) {
            if (text.size() == 1 && !text.at(0).isSurrogate())
                return text.at(0).unicode();
            if (text.size() == 2 && text.at(0).isHighSurrogate())
                return QChar::surrogateToUcs4(text.at(0), text.at(1));
        }
    }
#endif
    return zero().ucsFirst(single_character_data);
}

QString QLocaleData::negativeSign() const
{
    return localeString(this, QSystemLocale::NegativeSign, minus());
}

QString QLocaleData::positiveSign() const
{
    return localeString(this, QSystemLocale::PositiveSign, plus());
}

QString QLocaleData::exponentSeparator() const
{
    return exponential().getData(single_character_data);
}

/*!
 \internal
*/
QLocale::QLocale(QLocalePrivate &dd)
    : d(&dd)
{}

/*!
    \variable QLocale::DefaultTwoDigitBaseYear
    \since 6.7

    \brief The default start year of the century within which a format taking
    a two-digit year will select. The value of the constant is \c {1900}.

    Some locales use, particularly for ShortFormat, only the last two digits of
    the year. Proir to 6.7 the year 1900 was always used as a base year for
    such cases. Now various QLocale and QDate functions have the overloads that
    allow callers to specify the base year, and this constant is used as its
    default value.

    \sa toDate(), toDateTime(), QDate::fromString(), QDateTime::fromString()
*/

/*!
    \since 6.3

    Constructs a QLocale object with the specified \a name.

    The name has the format "language[_script][_territory][.codeset][@modifier]"
    or "C", where:

    \list
    \li language is a lowercase, two-letter, ISO 639 language code (some
        three-letter codes are also recognized),
    \li script is a capitalized, four-letter, ISO 15924 script code,
    \li territory is an uppercase, two-letter, ISO 3166 territory code
        (some numeric codes are also recognized), and
    \li codeset and modifier are ignored.
    \endlist

    The separator can be either underscore \c{'_'} (U+005F, "low line") or a
    dash \c{'-'} (U+002D, "hyphen-minus"). If QLocale has no data for the
    specified combination of language, script, and territory, then it uses the
    most suitable match it can find instead. If the string violates the locale
    format, or no suitable data can be found for the specified keys, the "C"
    locale is used instead.

    This constructor is much slower than QLocale(Language, Script, Territory) or
    QLocale(Language, Territory).

    \sa bcp47Name(), {Matching combinations of language, script and territory}
*/
QLocale::QLocale(QStringView name)
    : d(localePrivateByName(name))
{
}

/*!
    \fn QLocale::QLocale(const QString &name)
    \overload
*/

/*!
    Constructs a QLocale object initialized with the default locale.

    If no default locale was set using setDefault(), this locale will be the
    same as the one returned by system().

    \sa setDefault(), system()
*/

QLocale::QLocale()
    : d(*defaultLocalePrivate)
{
    // Make sure system data is up to date:
    systemData();
}

/*!
    Constructs a QLocale object for the specified \a language and \a territory.

    If there is more than one script in use for this combination, a likely
    script will be selected. If QLocale has no data for the specified \a
    language, the default locale is used. If QLocale has no data for the
    specified combination of \a language and \a territory, an alternative
    territory may be used instead.

    \sa setDefault(), {Matching combinations of language, script and territory}
*/

QLocale::QLocale(Language language, Territory territory)
    : d(findLocalePrivate(language, AnyScript, territory))
{
}

/*!
    \since 4.8

    Constructs a QLocale object for the specified \a language, \a script and \a
    territory.

    If QLocale does not have data for the given combination, it will find data
    for as good a match as it can. It falls back on the default locale if

    \list
    \li \a language is \c AnyLanguage and no language can be inferred from \a
        script and \a territory
    \li QLocale has no data for the language, either given as \a language or
        inferred as above.
    \endlist

    \sa setDefault(), {Matching combinations of language, script and territory}
*/

QLocale::QLocale(Language language, Script script, Territory territory)
    : d(findLocalePrivate(language, script, territory))
{
}

/*!
    Constructs a QLocale object as a copy of \a other.
*/

QLocale::QLocale(const QLocale &other) noexcept = default;

/*!
    Destructor
*/

QLocale::~QLocale()
{
}

/*!
    Assigns \a other to this QLocale object and returns a reference
    to this QLocale object.
*/

QLocale &QLocale::operator=(const QLocale &other) noexcept = default;

/*!
    \internal
    Equality comparison.
*/

bool QLocale::equals(const QLocale &other) const
{
    return d->m_data == other.d->m_data && d->m_numberOptions == other.d->m_numberOptions;
}

/*!
    \fn void QLocale::swap(QLocale &other)
    \since 5.6

    Swaps locale \a other with this locale. This operation is very fast and
    never fails.
*/

/*!
    \since 5.6
    \relates QLocale

    Returns the hash value for \a key, using
    \a seed to seed the calculation.
*/
size_t qHash(const QLocale &key, size_t seed) noexcept
{
    return qHashMulti(seed, key.d->m_data, key.d->m_numberOptions);
}

/*!
    \since 4.2

    Sets the \a options related to number conversions for this
    QLocale instance.

    \sa numberOptions(), FloatingPointPrecisionOption
*/
void QLocale::setNumberOptions(NumberOptions options)
{
    d->m_numberOptions = options;
}

/*!
    \since 4.2

    Returns the options related to number conversions for this
    QLocale instance.

    By default, no options are set for the standard locales, except
    for the "C" locale, which has OmitGroupSeparator set by default.

    \sa setNumberOptions(), toString(), groupSeparator(), FloatingPointPrecisionOption
*/
QLocale::NumberOptions QLocale::numberOptions() const
{
    return static_cast<NumberOptions>(d->m_numberOptions);
}

/*!
  \fn QString QLocale::quoteString(const QString &str, QuotationStyle style) const

    \since 4.8

    Returns \a str quoted according to the current locale using the given
    quotation \a style.
*/

/*!
    \since 6.0

    \overload
*/
QString QLocale::quoteString(QStringView str, QuotationStyle style) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QVariant res;
        if (style == AlternateQuotation)
            res = systemLocale()->query(QSystemLocale::StringToAlternateQuotation,
                                        QVariant::fromValue(str));
        if (res.isNull() || style == StandardQuotation)
            res = systemLocale()->query(QSystemLocale::StringToStandardQuotation,
                                        QVariant::fromValue(str));
        if (!res.isNull())
            return res.toString();
    }
#endif

    QLocaleData::DataRange start, end;
    if (style == StandardQuotation) {
        start = d->m_data->quoteStart();
        end = d->m_data->quoteEnd();
    } else {
        start = d->m_data->quoteStartAlternate();
        end = d->m_data->quoteEndAlternate();
    }

    return start.viewData(single_character_data) % str % end.viewData(single_character_data);
}

/*!
    \since 4.8

    Returns a string that represents a join of a given \a list of strings with
    a separator defined by the locale.
*/
QString QLocale::createSeparatedList(const QStringList &list) const
{
    // May be empty if list is empty or sole entry is empty.
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QVariant res =
            systemLocale()->query(QSystemLocale::ListToSeparatedString, QVariant::fromValue(list));

        if (!res.isNull())
            return res.toString();
    }
#endif

    const qsizetype size = list.size();
    if (size < 1)
        return QString();

    if (size == 1)
        return list.at(0);

    if (size == 2)
        return d->m_data->pairListPattern().getData(
            list_pattern_part_data).arg(list.at(0), list.at(1));

    QStringView formatStart = d->m_data->startListPattern().viewData(list_pattern_part_data);
    QStringView formatMid = d->m_data->midListPattern().viewData(list_pattern_part_data);
    QStringView formatEnd = d->m_data->endListPattern().viewData(list_pattern_part_data);
    QString result = formatStart.arg(list.at(0), list.at(1));
    for (qsizetype i = 2; i < size - 1; ++i)
        result = formatMid.arg(result, list.at(i));
    result = formatEnd.arg(result, list.at(size - 1));
    return result;
}

/*!
    \nonreentrant

    Sets the global default locale to \a locale. These
    values are used when a QLocale object is constructed with
    no arguments. If this function is not called, the system's
    locale is used.

    \warning In a multithreaded application, the default locale
    should be set at application startup, before any non-GUI threads
    are created.

    \sa system(), c()
*/

void QLocale::setDefault(const QLocale &locale)
{
    default_data = locale.d->m_data;

    if (defaultLocalePrivate.isDestroyed())
        return; // avoid crash on exit
    if (!defaultLocalePrivate.exists()) {
        // Force it to exist; see QTBUG-83016
        QLocale ignoreme;
        Q_ASSERT(defaultLocalePrivate.exists());
    }

    // update the cached private
    *defaultLocalePrivate = locale.d;
    QLocalePrivate::s_generation.fetchAndAddRelaxed(1);
}

/*!
    Returns the language of this locale.

    \sa script(), territory(), languageToString(), bcp47Name()
*/
QLocale::Language QLocale::language() const
{
    return Language(d->languageId());
}

/*!
    \since 4.8

    Returns the script of this locale.

    \sa language(), territory(), languageToString(), scriptToString(), bcp47Name()
*/
QLocale::Script QLocale::script() const
{
    return Script(d->m_data->m_script_id);
}

/*!
    \since 6.2

    Returns the territory of this locale.

    \sa language(), script(), territoryToString(), bcp47Name()
*/
QLocale::Territory QLocale::territory() const
{
    return Territory(d->territoryId());
}

#if QT_DEPRECATED_SINCE(6, 6)
/*!
    \deprecated [6.6] Use \l territory() instead.

    Returns the territory of this locale.

    \sa language(), script(), territoryToString(), bcp47Name()
*/
QLocale::Country QLocale::country() const
{
    return territory();
}
#endif

/*!
    \since 6.7
    \enum QLocale::TagSeparator

    Indicate how to combine the parts that make up a locale identifier.

    A locale identifier may be made up of several tags, indicating language,
    script and territory (plus, potentially, other details), joined together to
    form the identifier. Various standards and conventional forms use either a
    dash (the Unicode HYPHEN-MINUS, U+002D) or an underscore (LOW LINE, U+005F).
    Different clients of QLocale may thus need one or the other.

    \value Dash Use \c{'-'}, the dash or hyphen character.
    \value Underscore Use \c{'_'}, the underscore character.

    \note Although dash and underscore are the only separators used in public
    standards (as at 2023), it is possible to cast any \l
    {https://en.cppreference.com/w/cpp/language/ascii} {ASCII} character to this
    type if a non-standard ASCII separator is needed. Casting a non-ASCII
    character (with decimal value above 127) is not supported: such values are
    reserved for future use as enum members if some public standard ever uses a
    non-ASCII separator. It is, of course, possible to use QString::replace() to
    replace the separator used by a function taking a parameter of this type
    with an arbitrary Unicode character or string.
*/

Q_DECL_COLD_FUNCTION static void badSeparatorWarning(const char *method, char sep)
{
    qWarning("QLocale::%s(): Using non-ASCII separator '%c' (%02x) is unsupported",
             method, sep, uint(uchar(sep)));
}

/*!
    \brief The short name of this locale.

    Returns the language and territory of this locale as a string of the form
    "language_territory", where language is a lowercase, two-letter ISO 639
    language code, and territory is an uppercase, two- or three-letter ISO 3166
    territory code. If the locale has no specified territory, only the language
    name is returned. Since Qt 6.7 an optional \a separator parameter can be
    supplied to override the default underscore character separating the two
    tags.

    Even if the QLocale object was constructed with an explicit script, name()
    will not contain it for compatibility reasons. Use \l bcp47Name() instead if
    you need a full locale name, or construct the string you want to identify a
    locale by from those returned by passing its \l language() to \l
    languageToCode() and similar for the script and territory.

    \sa QLocale(), language(), script(), territory(), bcp47Name(), uiLanguages()
*/

QString QLocale::name(TagSeparator separator) const
{
    const char sep = char(separator);
    if (uchar(sep) > 0x7f) {
        badSeparatorWarning("name", sep);
        return {};
    }
    const auto code = d->languageCode();
    QLatin1StringView view{code.data()};

    Language l = language();
    if (l == C)
        return view;

    Territory c = territory();
    if (c == AnyTerritory)
        return view;

    return view + QLatin1Char(sep) + d->territoryCode();
}

template <typename T> static inline
T toIntegral_helper(const QLocalePrivate *d, QStringView str, bool *ok)
{
    constexpr bool isUnsigned = std::is_unsigned_v<T>;
    using Int64 = typename std::conditional_t<isUnsigned, quint64, qint64>;

    QSimpleParsedNumber<Int64> r{};
    if constexpr (isUnsigned)
        r = d->m_data->stringToUnsLongLong(str, 10, d->m_numberOptions);
    else
        r = d->m_data->stringToLongLong(str, 10, d->m_numberOptions);

    if (ok)
        *ok = r.ok();

    Int64 val = r.result;
    if (T(val) != val) {
        if (ok != nullptr)
            *ok = false;
        val = 0;
    }
    return T(val);
}


/*!
    \since 4.8

    \brief Returns the BCP47 field names joined with dashes.

    This combines as many of language, script and territory (and possibly other
    BCP47 fields) for this locale as are needed to uniquely specify it. Note
    that fields may be omitted if the Unicode consortium's \l {Matching
    combinations of language, script and territory}{Likely Subtag Rules} imply
    the omitted fields when given those retained. See \l name() for how to
    construct a string from individual fields, if some other format is needed.

    Unlike uiLanguages(), the value returned by bcp47Name() represents the
    locale name of the QLocale data; this need not be the language the
    user-interface should be in.

    This function tries to conform the locale name to the IETF Best Common
    Practice 47, defined by RFC 5646. Since Qt 6.7, it supports an optional \a
    separator parameter which can be used to override the BCP47-specified use of
    a hyphen to separate the tags. For use in IETF-defined protocols, however,
    the default, QLocale::TagSeparator::Dash, should be retained.

    \sa name(), language(), territory(), script(), uiLanguages()
*/
QString QLocale::bcp47Name(TagSeparator separator) const
{
    const char sep = char(separator);
    if (uchar(sep) > 0x7f) {
        badSeparatorWarning("bcp47Name", sep);
        return {};
    }
    return QString::fromLatin1(d->bcp47Name(sep));
}

/*!
    Returns the two- or three-letter language code for \a language, as defined
    in the ISO 639 standards.

    If specified, \a codeTypes selects which set of codes to consider. The first
    code from the set that is defined for \a language is returned. Otherwise,
    all ISO-639 codes are considered. The codes are considered in the following
    order: \c ISO639Part1, \c ISO639Part2B, \c ISO639Part2T, \c ISO639Part3.
    \c LegacyLanguageCode is ignored by this function.

    \note For \c{QLocale::C} the function returns \c{"C"}.
    For \c QLocale::AnyLanguage an empty string is returned.
    If the language has no code in any selected code set, an empty string
    is returned.

    \since 6.3
    \sa codeToLanguage(), language(), name(), bcp47Name(), territoryToCode(), scriptToCode()
*/
QString QLocale::languageToCode(Language language, LanguageCodeTypes codeTypes)
{
    const auto code = QLocalePrivate::languageToCode(language, codeTypes);
    return QLatin1StringView{code.data()};
}

/*!
    Returns the QLocale::Language enum corresponding to the two- or three-letter
    \a languageCode, as defined in the ISO 639 standards.

    If specified, \a codeTypes selects which set of codes to consider for
    conversion. By default all codes known to Qt are considered. The codes are
    matched in the following order: \c ISO639Part1, \c ISO639Part2B,
    \c ISO639Part2T, \c ISO639Part3, \c LegacyLanguageCode.

    If the code is invalid or not known \c QLocale::AnyLanguage is returned.

    \since 6.3
    \sa languageToCode(), codeToTerritory(), codeToScript()
*/
QLocale::Language QLocale::codeToLanguage(QStringView languageCode,
                                          LanguageCodeTypes codeTypes) noexcept
{
    return QLocalePrivate::codeToLanguage(languageCode, codeTypes);
}

/*!
    \since 6.2

    Returns the two-letter territory code for \a territory, as defined
    in the ISO 3166 standard.

    \note For \c{QLocale::AnyTerritory} an empty string is returned.

    \sa codeToTerritory(), territory(), name(), bcp47Name(), languageToCode(), scriptToCode()
*/
QString QLocale::territoryToCode(QLocale::Territory territory)
{
    return QLocalePrivate::territoryToCode(territory);
}

/*!
    \since 6.2

    Returns the QLocale::Territory enum corresponding to the two-letter or
    three-digit \a territoryCode, as defined in the ISO 3166 standard.

    If the code is invalid or not known QLocale::AnyTerritory is returned.

    \sa territoryToCode(), codeToLanguage(), codeToScript()
*/
QLocale::Territory QLocale::codeToTerritory(QStringView territoryCode) noexcept
{
    return QLocalePrivate::codeToTerritory(territoryCode);
}

#if QT_DEPRECATED_SINCE(6, 6)
/*!
    \deprecated [6.6] Use \l territoryToCode() instead.

    Returns the two-letter territory code for \a country, as defined
    in the ISO 3166 standard.

    \note For \c{QLocale::AnyTerritory} or \c{QLocale::AnyCountry} an empty string is returned.

    \sa codeToTerritory(), territory(), name(), bcp47Name(), languageToCode(), scriptToCode()
*/
QString QLocale::countryToCode(Country country)
{
    return territoryToCode(country);
}

/*!
    Returns the QLocale::Territory enum corresponding to the two-letter or
    three-digit \a countryCode, as defined in the ISO 3166 standard.

    If the code is invalid or not known QLocale::AnyTerritory is returned.

    \deprecated [6.6] Use codeToTerritory(QStringView) instead.
    \since 6.1
    \sa territoryToCode(), codeToLanguage(), codeToScript()
*/
QLocale::Country QLocale::codeToCountry(QStringView countryCode) noexcept
{
    return QLocalePrivate::codeToTerritory(countryCode);
}
#endif

/*!
    Returns the four-letter script code for \a script, as defined in the
    ISO 15924 standard.

    \note For \c{QLocale::AnyScript} an empty string is returned.

    \since 6.1
    \sa script(), name(), bcp47Name(), languageToCode(), territoryToCode()
*/
QString QLocale::scriptToCode(Script script)
{
    return QLocalePrivate::scriptToCode(script);
}

/*!
    Returns the QLocale::Script enum corresponding to the four-letter script
    \a scriptCode, as defined in the ISO 15924 standard.

    If the code is invalid or not known QLocale::AnyScript is returned.

    \since 6.1
    \sa scriptToCode(), codeToLanguage(), codeToTerritory()
*/
QLocale::Script QLocale::codeToScript(QStringView scriptCode) noexcept
{
    return QLocalePrivate::codeToScript(scriptCode);
}

/*!
    Returns a QString containing the name of \a language.

    \sa territoryToString(), scriptToString(), bcp47Name()
*/

QString QLocale::languageToString(Language language)
{
    if (language > LastLanguage)
        return "Unknown"_L1;
    return QString::fromUtf8(language_name_list + language_name_index[language]);
}

/*!
    \since 6.2

    Returns a QString containing the name of \a territory.

    \sa languageToString(), scriptToString(), territory(), bcp47Name()
*/
QString QLocale::territoryToString(Territory territory)
{
    if (territory > LastTerritory)
        return "Unknown"_L1;
    return QString::fromUtf8(territory_name_list + territory_name_index[territory]);
}

#if QT_DEPRECATED_SINCE(6, 6)
/*!
    \deprecated [6.6] Use \l territoryToString() instead.

    Returns a QString containing the name of \a country.

    \sa languageToString(), scriptToString(), territory(), bcp47Name()
*/
QString QLocale::countryToString(Country country)
{
    return territoryToString(country);
}
#endif

/*!
    \since 4.8

    Returns a QString containing the name of \a script.

    \sa languageToString(), territoryToString(), script(), bcp47Name()
*/
QString QLocale::scriptToString(Script script)
{
    if (script > LastScript)
        return "Unknown"_L1;
    return QString::fromUtf8(script_name_list + script_name_index[script]);
}

/*!
    \fn short QLocale::toShort(const QString &s, bool *ok) const

    Returns the short int represented by the localized string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toUShort(), toString()
*/

/*!
    \fn ushort QLocale::toUShort(const QString &s, bool *ok) const

    Returns the unsigned short int represented by the localized string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toShort(), toString()
*/

/*!
    \fn int QLocale::toInt(const QString &s, bool *ok) const
    Returns the int represented by the localized string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toUInt(), toString()
*/

/*!
    \fn uint QLocale::toUInt(const QString &s, bool *ok) const
    Returns the unsigned int represented by the localized string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toInt(), toString()
*/

/*!
    \since 5.13
    \fn long QLocale::toLong(const QString &s, bool *ok) const

    Returns the long int represented by the localized string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toInt(), toULong(), toDouble(), toString()
*/

/*!
    \since 5.13
    \fn ulong QLocale::toULong(const QString &s, bool *ok) const

    Returns the unsigned long int represented by the localized
    string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toLong(), toInt(), toDouble(), toString()
*/

/*!
    \fn qlonglong QLocale::toLongLong(const QString &s, bool *ok) const
    Returns the long long int represented by the localized string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toInt(), toULongLong(), toDouble(), toString()
*/

/*!
    \fn qulonglong QLocale::toULongLong(const QString &s, bool *ok) const

    Returns the unsigned long long int represented by the localized
    string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toLongLong(), toInt(), toDouble(), toString()
*/

/*!
    \fn float QLocale::toFloat(const QString &s, bool *ok) const

    Returns the float represented by the localized string \a s.

    Returns an infinity if the conversion overflows or 0.0 if the
    conversion fails for any other reason (e.g. underflow).

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toDouble(), toInt(), toString()
*/

/*!
    \fn double QLocale::toDouble(const QString &s, bool *ok) const
    Returns the double represented by the localized string \a s.

    Returns an infinity if the conversion overflows or 0.0 if the
    conversion fails for any other reason (e.g. underflow).

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    \snippet code/src_corelib_text_qlocale.cpp 3

    Notice that the last conversion returns 1234.0, because '.' is the
    thousands group separator in the German locale.

    This function ignores leading and trailing whitespace.

    \sa toFloat(), toInt(), toString()
*/

/*!
    Returns the short int represented by the localized string \a s.

    If the conversion fails, the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toUShort(), toString()

    \since 5.10
*/

short QLocale::toShort(QStringView s, bool *ok) const
{
    return toIntegral_helper<short>(d, s, ok);
}

/*!
    Returns the unsigned short int represented by the localized string \a s.

    If the conversion fails, the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toShort(), toString()

    \since 5.10
*/

ushort QLocale::toUShort(QStringView s, bool *ok) const
{
    return toIntegral_helper<ushort>(d, s, ok);
}

/*!
    Returns the int represented by the localized string \a s.

    If the conversion fails, the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toUInt(), toString()

    \since 5.10
*/

int QLocale::toInt(QStringView s, bool *ok) const
{
    return toIntegral_helper<int>(d, s, ok);
}

/*!
    Returns the unsigned int represented by the localized string \a s.

    If the conversion fails, the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toInt(), toString()

    \since 5.10
*/

uint QLocale::toUInt(QStringView s, bool *ok) const
{
    return toIntegral_helper<uint>(d, s, ok);
}

/*!
    \since 5.13
    Returns the long int represented by the localized string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toInt(), toULong(), toDouble(), toString()
*/

long QLocale::toLong(QStringView s, bool *ok) const
{
    return toIntegral_helper<long>(d, s, ok);
}

/*!
    \since 5.13
    Returns the unsigned long int represented by the localized
    string \a s.

    If the conversion fails the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toLong(), toInt(), toDouble(), toString()
*/

ulong QLocale::toULong(QStringView s, bool *ok) const
{
    return toIntegral_helper<ulong>(d, s, ok);
}

/*!
    Returns the long long int represented by the localized string \a s.

    If the conversion fails, the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toInt(), toULongLong(), toDouble(), toString()

    \since 5.10
*/


qlonglong QLocale::toLongLong(QStringView s, bool *ok) const
{
    return toIntegral_helper<qlonglong>(d, s, ok);
}

/*!
    Returns the unsigned long long int represented by the localized
    string \a s.

    If the conversion fails, the function returns 0.

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toLongLong(), toInt(), toDouble(), toString()

    \since 5.10
*/

qulonglong QLocale::toULongLong(QStringView s, bool *ok) const
{
    return toIntegral_helper<qulonglong>(d, s, ok);
}

/*!
    Returns the float represented by the localized string \a s.

    Returns an infinity if the conversion overflows or 0.0 if the
    conversion fails for any other reason (e.g. underflow).

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    This function ignores leading and trailing whitespace.

    \sa toDouble(), toInt(), toString()

    \since 5.10
*/

float QLocale::toFloat(QStringView s, bool *ok) const
{
    return QLocaleData::convertDoubleToFloat(toDouble(s, ok), ok);
}

/*!
    Returns the double represented by the localized string \a s.

    Returns an infinity if the conversion overflows or 0.0 if the
    conversion fails for any other reason (e.g. underflow).

    If \a ok is not \nullptr, failure is reported by setting *\a{ok}
    to \c false, and success by setting *\a{ok} to \c true.

    \snippet code/src_corelib_text_qlocale.cpp 3-qstringview

    Notice that the last conversion returns 1234.0, because '.' is the
    thousands group separator in the German locale.

    This function ignores leading and trailing whitespace.

    \sa toFloat(), toInt(), toString()

    \since 5.10
*/

double QLocale::toDouble(QStringView s, bool *ok) const
{
    return d->m_data->stringToDouble(s, ok, d->m_numberOptions);
}

/*!
    Returns a localized string representation of \a i.

    \sa toLongLong(), numberOptions(), zeroDigit(), positiveSign()
*/

QString QLocale::toString(qlonglong i) const
{
    int flags = (d->m_numberOptions & OmitGroupSeparator
                 ? 0 : QLocaleData::GroupDigits);

    return d->m_data->longLongToString(i, -1, 10, -1, flags);
}

/*!
    \overload

    \sa toULongLong(), numberOptions(), zeroDigit(), positiveSign()
*/

QString QLocale::toString(qulonglong i) const
{
    int flags = (d->m_numberOptions & OmitGroupSeparator
                 ? 0 : QLocaleData::GroupDigits);

    return d->m_data->unsLongLongToString(i, -1, 10, -1, flags);
}

/*!
    Returns a localized string representation of the given \a date in the
    specified \a format.
    If \a format is an empty string, an empty string is returned.

    \sa QDate::toString()
*/

QString QLocale::toString(QDate date, const QString &format) const
{
    return toString(date, qToStringViewIgnoringNull(format));
}

/*!
    Returns a localized string representation of the given \a time according
    to the specified \a format.
    If \a format is an empty string, an empty string is returned.

    \sa QTime::toString()
*/

QString QLocale::toString(QTime time, const QString &format) const
{
    return toString(time, qToStringViewIgnoringNull(format));
}

/*!
    \since 4.4
    \fn QString QLocale::toString(const QDateTime &dateTime, const QString &format) const

    Returns a localized string representation of the given \a dateTime according
    to the specified \a format.
    If \a format is an empty string, an empty string is returned.

    \sa QDateTime::toString(), QDate::toString(), QTime::toString()
*/

/*!
    \since 5.14

    Returns a localized string representation of the given \a date in the
    specified \a format, optionally for a specified calendar \a cal.
    If \a format is an empty string, an empty string is returned.

    \sa QDate::toString()
*/
QString QLocale::toString(QDate date, QStringView format, QCalendar cal) const
{
    return cal.dateTimeToString(format, QDateTime(), date, QTime(), *this);
}

/*!
    \since 5.10
    \overload
*/
QString QLocale::toString(QDate date, QStringView format) const
{
    return QCalendar().dateTimeToString(format, QDateTime(), date, QTime(), *this);
}

/*!
    \since 5.14

    Returns a localized string representation of the given \a date according
    to the specified \a format (see dateFormat()), optionally for a specified
    calendar \a cal.

    \note Some locales may use formats that limit the range of years they can
    represent.
*/
QString QLocale::toString(QDate date, FormatType format, QCalendar cal) const
{
    if (!date.isValid())
        return QString();

#ifndef QT_NO_SYSTEMLOCALE
    if (cal.isGregorian() && d->m_data == &systemLocaleData) {
        QVariant res = systemLocale()->query(format == LongFormat
                                             ? QSystemLocale::DateToStringLong
                                             : QSystemLocale::DateToStringShort,
                                             date);
        if (!res.isNull())
            return res.toString();
    }
#endif

    QString format_str = dateFormat(format);
    return toString(date, format_str, cal);
}

/*!
    \since 4.5
    \overload
*/
QString QLocale::toString(QDate date, FormatType format) const
{
    if (!date.isValid())
        return QString();

#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QVariant res = systemLocale()->query(format == LongFormat
                                             ? QSystemLocale::DateToStringLong
                                             : QSystemLocale::DateToStringShort,
                                             date);
        if (!res.isNull())
            return res.toString();
    }
#endif

    QString format_str = dateFormat(format);
    return toString(date, format_str);
}

static bool timeFormatContainsAP(QStringView format)
{
    qsizetype i = 0;
    while (i < format.size()) {
        if (format.at(i).unicode() == '\'') {
            qt_readEscapedFormatString(format, &i);
            continue;
        }

        if (format.at(i).toLower().unicode() == 'a')
            return true;

        ++i;
    }
    return false;
}

/*!
    \since 4.5

    Returns a localized string representation of the given \a time according
    to the specified \a format.
    If \a format is an empty string, an empty string is returned.

    \sa QTime::toString()
*/
QString QLocale::toString(QTime time, QStringView format) const
{
    return QCalendar().dateTimeToString(format, QDateTime(), QDate(), time, *this);
}

/*!
    \since 5.14

    Returns a localized string representation of the given \a dateTime according
    to the specified \a format, optionally for a specified calendar \a cal.
    If \a format is an empty string, an empty string is returned.

    \sa QDateTime::toString(), QDate::toString(), QTime::toString()
*/
QString QLocale::toString(const QDateTime &dateTime, QStringView format, QCalendar cal) const
{
    return cal.dateTimeToString(format, dateTime, QDate(), QTime(), *this);
}

/*!
    \since 5.10
    \overload
*/
QString QLocale::toString(const QDateTime &dateTime, QStringView format) const
{
    return QCalendar().dateTimeToString(format, dateTime, QDate(), QTime(), *this);
}

/*!
    \since 5.14

    Returns a localized string representation of the given \a dateTime according
    to the specified \a format (see dateTimeFormat()), optionally for a
    specified calendar \a cal.

    \note Some locales may use formats that limit the range of years they can
    represent.
*/
QString QLocale::toString(const QDateTime &dateTime, FormatType format, QCalendar cal) const
{
    if (!dateTime.isValid())
        return QString();

#ifndef QT_NO_SYSTEMLOCALE
    if (cal.isGregorian() && d->m_data == &systemLocaleData) {
        QVariant res = systemLocale()->query(format == LongFormat
                                             ? QSystemLocale::DateTimeToStringLong
                                             : QSystemLocale::DateTimeToStringShort,
                                             dateTime);
        if (!res.isNull())
            return res.toString();
    }
#endif

    const QString format_str = dateTimeFormat(format);
    return toString(dateTime, format_str, cal);
}

/*!
    \since 4.4
    \overload
*/
QString QLocale::toString(const QDateTime &dateTime, FormatType format) const
{
    if (!dateTime.isValid())
        return QString();

#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QVariant res = systemLocale()->query(format == LongFormat
                                             ? QSystemLocale::DateTimeToStringLong
                                             : QSystemLocale::DateTimeToStringShort,
                                             dateTime);
        if (!res.isNull())
            return res.toString();
    }
#endif

    const QString format_str = dateTimeFormat(format);
    return toString(dateTime, format_str);
}


/*!
    Returns a localized string representation of the given \a time in the
    specified \a format (see timeFormat()).
*/

QString QLocale::toString(QTime time, FormatType format) const
{
    if (!time.isValid())
        return QString();

#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QVariant res = systemLocale()->query(format == LongFormat
                                             ? QSystemLocale::TimeToStringLong
                                             : QSystemLocale::TimeToStringShort,
                                             time);
        if (!res.isNull())
            return res.toString();
    }
#endif

    QString format_str = timeFormat(format);
    return toString(time, format_str);
}

/*!
    \since 4.1

    Returns the date format used for the current locale.

    If \a format is LongFormat, the format will be elaborate, otherwise it will be short.
    For example, LongFormat for the \c{en_US} locale is \c{dddd, MMMM d, yyyy},
    ShortFormat is \c{M/d/yy}.

    \sa QDate::toString(), QDate::fromString()
*/

QString QLocale::dateFormat(FormatType format) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QVariant res = systemLocale()->query(format == LongFormat
                                             ? QSystemLocale::DateFormatLong
                                             : QSystemLocale::DateFormatShort,
                                             QVariant());
        if (!res.isNull())
            return res.toString();
    }
#endif

    return (format == LongFormat
            ? d->m_data->longDateFormat()
            : d->m_data->shortDateFormat()
           ).getData(date_format_data);
}

/*!
    \since 4.1

    Returns the time format used for the current locale.

    If \a format is LongFormat, the format will be elaborate, otherwise it will be short.
    For example, LongFormat for the \c{en_US} locale is \c{h:mm:ss AP t},
    ShortFormat is \c{h:mm AP}.

    \sa QTime::toString(), QTime::fromString()
*/

QString QLocale::timeFormat(FormatType format) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QVariant res = systemLocale()->query(format == LongFormat
                                             ? QSystemLocale::TimeFormatLong
                                             : QSystemLocale::TimeFormatShort,
                                             QVariant());
        if (!res.isNull())
            return res.toString();
    }
#endif

    return (format == LongFormat
            ? d->m_data->longTimeFormat()
            : d->m_data->shortTimeFormat()
           ).getData(time_format_data);
}

/*!
    \since 4.4

    Returns the date time format used for the current locale.

    If \a format is LongFormat, the format will be elaborate, otherwise it will be short.
    For example, LongFormat for the \c{en_US} locale is \c{dddd, MMMM d, yyyy h:mm:ss AP t},
    ShortFormat is \c{M/d/yy h:mm AP}.

    \sa QDateTime::toString(), QDateTime::fromString()
*/

QString QLocale::dateTimeFormat(FormatType format) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QVariant res = systemLocale()->query(format == LongFormat
                                             ? QSystemLocale::DateTimeFormatLong
                                             : QSystemLocale::DateTimeFormatShort,
                                             QVariant());
        if (!res.isNull()) {
            return res.toString();
        }
    }
#endif
    return dateFormat(format) + u' ' + timeFormat(format);
}

#if QT_CONFIG(datestring)
/*!
    \since 4.4

    Reads \a string as a time in a locale-specific \a format.

    Parses \a string and returns the time it represents. The format of the time
    string is chosen according to the \a format parameter (see timeFormat()).

    \note Any am/pm indicators used must match \l amText() or \l pmText(),
    ignoring case.

    If the time could not be parsed, returns an invalid time.

    \sa timeFormat(), toDate(), toDateTime(), QTime::fromString()
*/
QTime QLocale::toTime(const QString &string, FormatType format) const
{
    return toTime(string, timeFormat(format));
}

/*!
    \since 4.4

    Reads \a string as a date in a locale-specific \a format.

    Parses \a string and returns the date it represents. The format of the date
    string is chosen according to the \a format parameter (see dateFormat()).

//! [base-year-for-short]
    Some locales use, particularly for ShortFormat, only the last two digits of
    the year. In such a case, the 100 years starting at \a baseYear are the
    candidates first considered. Prior to 6.7 there was no \a baseYear parameter
    and 1900 was always used. This is the default for \a baseYear, selecting a
    year from then to 1999. In some cases, other fields may lead to the next or
    previous century being selected, to get a result consistent with all fields
    given. See \l QDate::fromString() for details.
//! [base-year-for-short]

    \note Month and day names, where used, must be given in the locale's
    language.

    If the date could not be parsed, returns an invalid date.

    \sa dateFormat(), toTime(), toDateTime(), QDate::fromString()
*/
QDate QLocale::toDate(const QString &string, FormatType format, int baseYear) const
{
    return toDate(string, dateFormat(format), baseYear);
}

/*!
    \since 5.14
    \overload
*/
QDate QLocale::toDate(const QString &string, FormatType format, QCalendar cal, int baseYear) const
{
    return toDate(string, dateFormat(format), cal, baseYear);
}

/*!
    \since 4.4

    Reads \a string as a date-time in a locale-specific \a format.

    Parses \a string and returns the date-time it represents. The format of the
    date string is chosen according to the \a format parameter (see
    dateFormat()).

    \include qlocale.cpp base-year-for-short

    \note Month and day names, where used, must be given in the locale's
    language. Any am/pm indicators used must match \l amText() or \l pmText(),
    ignoring case.

    If the string could not be parsed, returns an invalid QDateTime.

    \sa dateTimeFormat(), toTime(), toDate(), QDateTime::fromString()
*/
QDateTime QLocale::toDateTime(const QString &string, FormatType format, int baseYear) const
{
    return toDateTime(string, dateTimeFormat(format), baseYear);
}

/*!
    \since 5.14
    \overload
*/
QDateTime QLocale::toDateTime(const QString &string, FormatType format, QCalendar cal,
                              int baseYear) const
{
    return toDateTime(string, dateTimeFormat(format), cal, baseYear);
}

/*!
    \since 4.4

    Reads \a string as a time in the given \a format.

    Parses \a string and returns the time it represents. See QTime::fromString()
    for the interpretation of \a format.

    \note Any am/pm indicators used must match \l amText() or \l pmText(),
    ignoring case.

    If the time could not be parsed, returns an invalid time.

    \sa timeFormat(), toDate(), toDateTime(), QTime::fromString()
*/
QTime QLocale::toTime(const QString &string, const QString &format) const
{
    QTime time;
#if QT_CONFIG(datetimeparser)
    QDateTimeParser dt(QMetaType::QTime, QDateTimeParser::FromString, QCalendar());
    dt.setDefaultLocale(*this);
    if (dt.parseFormat(format))
        dt.fromString(string, nullptr, &time);
#else
    Q_UNUSED(string);
    Q_UNUSED(format);
#endif
    return time;
}

/*!
    \since 4.4

    Reads \a string as a date in the given \a format.

    Parses \a string and returns the date it represents. See QDate::fromString()
    for the interpretation of \a format.

//! [base-year-for-two-digit]
    When \a format only specifies the last two digits of a year, the 100 years
    starting at \a baseYear are the candidates first considered. Prior to 6.7
    there was no \a baseYear parameter and 1900 was always used. This is the
    default for \a baseYear, selecting a year from then to 1999. In some cases,
    other fields may lead to the next or previous century being selected, to get
    a result consistent with all fields given. See \l QDate::fromString() for
    details.
//! [base-year-for-two-digit]

    \note Month and day names, where used, must be given in the locale's
    language.

    If the date could not be parsed, returns an invalid date.

    \sa dateFormat(), toTime(), toDateTime(), QDate::fromString()
*/
QDate QLocale::toDate(const QString &string, const QString &format, int baseYear) const
{
    return toDate(string, format, QCalendar(), baseYear);
}

/*!
    \since 5.14
    \overload
*/
QDate QLocale::toDate(const QString &string, const QString &format, QCalendar cal, int baseYear) const
{
    QDate date;
#if QT_CONFIG(datetimeparser)
    QDateTimeParser dt(QMetaType::QDate, QDateTimeParser::FromString, cal);
    dt.setDefaultLocale(*this);
    if (dt.parseFormat(format))
        dt.fromString(string, &date, nullptr, baseYear);
#else
    Q_UNUSED(string);
    Q_UNUSED(format);
    Q_UNUSED(baseYear);
    Q_UNUSED(cal);
#endif
    return date;
}

/*!
    \since 4.4

    Reads \a string as a date-time in the given \a format.

    Parses \a string and returns the date-time it represents.  See
    QDateTime::fromString() for the interpretation of \a format.

    \include qlocale.cpp base-year-for-two-digit

    \note Month and day names, where used, must be given in the locale's
    language. Any am/pm indicators used must match \l amText() or \l pmText(),
    ignoring case.

    If the string could not be parsed, returns an invalid QDateTime.  If the
    string can be parsed and represents an invalid date-time (e.g. in a gap
    skipped by a time-zone transition), an invalid QDateTime is returned, whose
    toMSecsSinceEpoch() represents a near-by date-time that is valid. Passing
    that to fromMSecsSinceEpoch() will produce a valid date-time that isn't
    faithfully represented by the string parsed.

    \sa dateTimeFormat(), toTime(), toDate(), QDateTime::fromString()
*/
QDateTime QLocale::toDateTime(const QString &string, const QString &format, int baseYear) const
{
    return toDateTime(string, format, QCalendar(), baseYear);
}

/*!
    \since 5.14
    \overload
*/
QDateTime QLocale::toDateTime(const QString &string, const QString &format, QCalendar cal,
                              int baseYear) const
{
#if QT_CONFIG(datetimeparser)
    QDateTime datetime;

    QDateTimeParser dt(QMetaType::QDateTime, QDateTimeParser::FromString, cal);
    dt.setDefaultLocale(*this);
    if (dt.parseFormat(format) && (dt.fromString(string, &datetime, baseYear)
                                   || !datetime.isValid())) {
        return datetime;
    }
#else
    Q_UNUSED(string);
    Q_UNUSED(format);
    Q_UNUSED(baseYear);
    Q_UNUSED(cal);
#endif
    return QDateTime();
}
#endif // datestring

/*!
    \since 4.1

    Returns the fractional part separator for this locale.

    This is the token that separates the whole number part from the fracional
    part in the representation of a number which has a fractional part. This is
    commonly called the "decimal point character" - even though, in many
    locales, it is not a "point" (or similar dot). It is (since Qt 6.0) returned
    as a string in case some locale needs more than one UTF-16 code-point to
    represent its separator.

    \sa groupSeparator(), toString()
*/
QString QLocale::decimalPoint() const
{
    return d->m_data->decimalPoint();
}

/*!
    \since 4.1

    Returns the digit-grouping separator for this locale.

    This is a token used to break up long sequences of digits, in the
    representation of a number, to make it easier to read. In some locales it
    may be empty, indicating that digits should not be broken up into groups in
    this way. In others it may be a spacing character. It is (since Qt 6.0)
    returned as a string in case some locale needs more than one UTF-16
    code-point to represent its separator.

    \sa decimalPoint(), toString()
*/
QString QLocale::groupSeparator() const
{
    return d->m_data->groupSeparator();
}

/*!
    \since 4.1

    Returns the percent marker of this locale.

    This is a token presumed to be appended to a number to indicate a
    percentage. It is (since Qt 6.0) returned as a string because, in some
    locales, it is not a single character - for example, because it includes a
    text-direction-control character.

    \sa toString()
*/
QString QLocale::percent() const
{
    return d->m_data->percentSign();
}

/*!
    \since 4.1

    Returns the zero digit character of this locale.

    This is a single Unicode character but may be encoded as a surrogate pair,
    so is (since Qt 6.0) returned as a string. In most locales, other digits
    follow it in Unicode ordering - however, some number systems, notably those
    using U+3007 as zero, do not have contiguous digits. Use toString() to
    obtain suitable representations of numbers, rather than trying to construct
    them from this zero digit.

    \sa toString()
*/
QString QLocale::zeroDigit() const
{
    return d->m_data->zeroDigit();
}

/*!
    \since 4.1

    Returns the negative sign indicator of this locale.

    This is a token presumed to be used as a prefix to a number to indicate that
    it is negative. It is (since Qt 6.0) returned as a string because, in some
    locales, it is not a single character - for example, because it includes a
    text-direction-control character.

    \sa positiveSign(), toString()
*/
QString QLocale::negativeSign() const
{
    return d->m_data->negativeSign();
}

/*!
    \since 4.5

    Returns the positive sign indicator of this locale.

    This is a token presumed to be used as a prefix to a number to indicate that
    it is positive. It is (since Qt 6.0) returned as a string because, in some
    locales, it is not a single character - for example, because it includes a
    text-direction-control character.

    \sa negativeSign(), toString()
*/
QString QLocale::positiveSign() const
{
    return d->m_data->positiveSign();
}

/*!
    \since 4.1

    Returns the exponent separator for this locale.

    This is a token used to separate mantissa from exponent in some
    floating-point numeric representations. It is (since Qt 6.0) returned as a
    string because, in some locales, it is not a single character - for example,
    it may consist of a multiplication sign and a representation of the "ten to
    the power" operator.

    \sa toString(double, char, int)
*/
QString QLocale::exponential() const
{
    return d->m_data->exponentSeparator();
}

/*!
    \overload
    Returns a string representing the floating-point number \a f.

    The form of the representation is controlled by the \a format and \a
    precision parameters.

    The \a format defaults to \c{'g'}. It can be any of the following:

    \table
    \header \li Format \li Meaning \li Meaning of \a precision
    \row \li \c 'e' \li format as [-]9.9e[+|-]999 \li number of digits \e after the decimal point
    \row \li \c 'E' \li format as [-]9.9E[+|-]999 \li "
    \row \li \c 'f' \li format as [-]9.9 \li "
    \row \li \c 'F' \li same as \c 'f' except for INF and NAN (see below) \li "
    \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)
    \row \li \c 'G' \li use \c 'E' or \c 'F' format, whichever is more concise \li "
    \endtable

    The special \a precision value QLocale::FloatingPointShortest selects the
    shortest representation that, when read as a number, gets back the original floating-point
    value. Aside from that, any negative \a precision is ignored in favor of the
    default, 6.

    For the \c 'e', \c 'f' and \c 'g' formats, positive infinity is represented
    as "inf", negative infinity as "-inf" and floating-point NaN (not-a-number)
    values are represented as "nan". For the \c 'E', \c 'F' and \c 'G' formats,
    "INF" and "NAN" are used instead. This does not vary with locale.

    \sa toDouble(), numberOptions(), exponential(), decimalPoint(), zeroDigit(),
        positiveSign(), percent(), toCurrencyString(), formattedDataSize(),
        QLocale::FloatingPointPrecisionOption
*/

QString QLocale::toString(double f, char format, int precision) const
{
    QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
    uint flags = isAsciiUpper(format) ? QLocaleData::CapitalEorX : 0;

    switch (QtMiscUtils::toAsciiLower(format)) {
    case 'f':
        form = QLocaleData::DFDecimal;
        break;
    case 'e':
        form = QLocaleData::DFExponent;
        break;
    case 'g':
        form = QLocaleData::DFSignificantDigits;
        break;
    default:
        break;
    }

    if (!(d->m_numberOptions & OmitGroupSeparator))
        flags |= QLocaleData::GroupDigits;
    if (!(d->m_numberOptions & OmitLeadingZeroInExponent))
        flags |= QLocaleData::ZeroPadExponent;
    if (d->m_numberOptions & IncludeTrailingZeroesAfterDot)
        flags |= QLocaleData::AddTrailingZeroes;
    return d->m_data->doubleToString(f, precision, form, -1, flags);
}

/*!
    \fn QLocale QLocale::c()

    Returns a QLocale object initialized to the "C" locale.

    This locale is based on en_US but with various quirks of its own, such as
    simplified number formatting and its own date formatting. It implements the
    POSIX standards that describe the behavior of standard library functions of
    the "C" programming language.

    Among other things, this means its collation order is based on the ASCII
    values of letters, so that (for case-sensitive sorting) all upper-case
    letters sort before any lower-case one (rather than each letter's upper- and
    lower-case forms sorting adjacent to one another, before the next letter's
    two forms).

    \sa system()
*/

/*!
    Returns a QLocale object initialized to the system locale.

    The system locale may use system-specific sources for locale data, where
    available, otherwise falling back on QLocale's built-in database entry for
    the language, script and territory the system reports.

    For example, on Windows and Mac, this locale will use the decimal/grouping
    characters and date/time formats specified in the system configuration
    panel.

    \sa c()
*/

QLocale QLocale::system()
{
    constexpr auto sysData = []() {
        // Same return as systemData(), but leave the setup to the actual call to it.
#ifdef QT_NO_SYSTEMLOCALE
        return locale_data;
#else
        return &systemLocaleData;
#endif
    };
    Q_CONSTINIT static QLocalePrivate locale(sysData(), -1, DefaultNumberOptions, 1);
    // Calling systemData() ensures system data is up to date; we also need it
    // to ensure that locale's index stays up to date:
    systemData(&locale.m_index);
    Q_ASSERT(locale.m_index >= 0 && locale.m_index < locale_data_size);

    return QLocale(locale);
}

/*!
    Returns a list of valid locale objects that match the given \a language, \a
    script and \a territory.

    Getting a list of all locales:
    QList<QLocale> allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript,
                                                         QLocale::AnyTerritory);

    Getting a list of locales suitable for Russia:
    QList<QLocale> locales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript,
                                                      QLocale::Russia);
*/
QList<QLocale> QLocale::matchingLocales(Language language, Script script, Territory territory)
{
    const QLocaleId filter { language, script, territory };
    if (!filter.isValid())
        return QList<QLocale>();

    if (language == C)
        return QList<QLocale>{QLocale(C)};

    QList<QLocale> result;
    if (filter.matchesAll())
        result.reserve(locale_data_size);

    quint16 index = locale_index[language];
    // There may be no matches, for some languages (e.g. Abkhazian at CLDR v39).
    while (filter.acceptLanguage(locale_data[index].m_language_id)) {
        const QLocaleId id = locale_data[index].id();
        if (filter.acceptScriptTerritory(id)) {
            result.append(QLocale(*(id.language_id == C ? c_private()
                                    : new QLocalePrivate(locale_data + index, index))));
        }
        ++index;
    }

    // Add current system locale, if it matches
    const auto syslocaledata = systemData();

    if (filter.acceptLanguage(syslocaledata->m_language_id)) {
        const QLocaleId id = syslocaledata->id();
        if (filter.acceptScriptTerritory(id))
            result.append(system());
    }

    return result;
}

#if QT_DEPRECATED_SINCE(6, 6)
/*!
    \deprecated [6.6] Use \l matchingLocales() instead and consult the \l territory() of each.
    \since 4.3

    Returns the list of countries that have entries for \a language in Qt's locale
    database. If the result is an empty list, then \a language is not represented in
    Qt's locale database.

    \sa matchingLocales()
*/
QList<QLocale::Country> QLocale::countriesForLanguage(Language language)
{
    const auto locales = matchingLocales(language, AnyScript, AnyCountry);
    QList<Country> result;
    result.reserve(locales.size());
    for (const auto &locale : locales)
        result.append(locale.territory());
    return result;
}
#endif

/*!
    \since 4.2

    Returns the localized name of \a month, in the format specified
    by \a type.

    For example, if the locale is \c en_US and \a month is 1,
    \l LongFormat will return \c January. \l ShortFormat \c Jan,
    and \l NarrowFormat \c J.

    \sa dayName(), standaloneMonthName()
*/
QString QLocale::monthName(int month, FormatType type) const
{
    return QCalendar().monthName(*this, month, QCalendar::Unspecified, type);
}

/*!
    \since 4.5

    Returns the localized name of \a month that is used as a
    standalone text, in the format specified by \a type.

    If the locale information doesn't specify the standalone month
    name then return value is the same as in monthName().

    \sa monthName(), standaloneDayName()
*/
QString QLocale::standaloneMonthName(int month, FormatType type) const
{
    return QCalendar().standaloneMonthName(*this, month, QCalendar::Unspecified, type);
}

/*!
    \since 4.2

    Returns the localized name of the \a day (where 1 represents
    Monday, 2 represents Tuesday and so on), in the format specified
    by \a type.

    For example, if the locale is \c en_US and \a day is 1,
    \l LongFormat will return \c Monday, \l ShortFormat \c Mon,
    and \l NarrowFormat \c M.

    \sa monthName(), standaloneDayName()
*/
QString QLocale::dayName(int day, FormatType type) const
{
    return QCalendar().weekDayName(*this, day, type);
}

/*!
    \since 4.5

    Returns the localized name of the \a day (where 1 represents
    Monday, 2 represents Tuesday and so on) that is used as a
    standalone text, in the format specified by \a type.

    If the locale information does not specify the standalone day
    name then return value is the same as in dayName().

    \sa dayName(), standaloneMonthName()
*/
QString QLocale::standaloneDayName(int day, FormatType type) const
{
    return QCalendar().standaloneWeekDayName(*this, day, type);
}

// Calendar look-up of month and day names:

/*!
  \internal
 */

static QString rawMonthName(const QCalendarLocale &localeData,
                            const char16_t *monthsData, int month,
                            QLocale::FormatType type)
{
    QLocaleData::DataRange range;
    switch (type) {
    case QLocale::LongFormat:
        range = localeData.longMonth();
        break;
    case QLocale::ShortFormat:
        range = localeData.shortMonth();
        break;
    case QLocale::NarrowFormat:
        range = localeData.narrowMonth();
        break;
    default:
        return QString();
    }
    return range.getListEntry(monthsData, month - 1);
}

/*!
  \internal
 */

static QString rawStandaloneMonthName(const QCalendarLocale &localeData,
                                      const char16_t *monthsData, int month,
                                      QLocale::FormatType type)
{
    QLocaleData::DataRange range;
    switch (type) {
    case QLocale::LongFormat:
        range = localeData.longMonthStandalone();
        break;
    case QLocale::ShortFormat:
        range = localeData.shortMonthStandalone();
        break;
    case QLocale::NarrowFormat:
        range = localeData.narrowMonthStandalone();
        break;
    default:
        return QString();
    }
    QString name = range.getListEntry(monthsData, month - 1);
    return name.isEmpty() ? rawMonthName(localeData, monthsData, month, type) : name;
}

/*!
  \internal
 */

static QString rawWeekDayName(const QLocaleData *data, const int day,
                              QLocale::FormatType type)
{
    QLocaleData::DataRange range;
    switch (type) {
    case QLocale::LongFormat:
        range = data->longDayNames();
        break;
    case QLocale::ShortFormat:
        range = data->shortDayNames();
        break;
    case QLocale::NarrowFormat:
        range = data->narrowDayNames();
        break;
    default:
        return QString();
    }
    return range.getListEntry(days_data, day == 7 ? 0 : day);
}

/*!
  \internal
 */

static QString rawStandaloneWeekDayName(const QLocaleData *data, const int day,
                                        QLocale::FormatType type)
{
    QLocaleData::DataRange range;
    switch (type) {
    case QLocale::LongFormat:
        range =data->longDayNamesStandalone();
        break;
    case QLocale::ShortFormat:
        range = data->shortDayNamesStandalone();
        break;
    case QLocale::NarrowFormat:
        range = data->narrowDayNamesStandalone();
        break;
    default:
        return QString();
    }
    QString name = range.getListEntry(days_data, day == 7 ? 0 : day);
    if (name.isEmpty())
        return rawWeekDayName(data, day, type);
    return name;
}

// Refugees from qcalendar.cpp that need functions above:

QString QCalendarBackend::monthName(const QLocale &locale, int month, int,
                                    QLocale::FormatType format) const
{
    Q_ASSERT(month >= 1 && month <= maximumMonthsInYear());
    return rawMonthName(localeMonthIndexData()[locale.d->m_index],
                        localeMonthData(), month, format);
}

QString QRomanCalendar::monthName(const QLocale &locale, int month, int year,
                                  QLocale::FormatType format) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (locale.d->m_data == &systemLocaleData) {
        Q_ASSERT(month >= 1 && month <= 12);
        QSystemLocale::QueryType queryType = QSystemLocale::MonthNameLong;
        switch (format) {
        case QLocale::LongFormat:
            queryType = QSystemLocale::MonthNameLong;
            break;
        case QLocale::ShortFormat:
            queryType = QSystemLocale::MonthNameShort;
            break;
        case QLocale::NarrowFormat:
            queryType = QSystemLocale::MonthNameNarrow;
            break;
        }
        QVariant res = systemLocale()->query(queryType, month);
        if (!res.isNull())
            return res.toString();
    }
#endif

    return QCalendarBackend::monthName(locale, month, year, format);
}

QString QCalendarBackend::standaloneMonthName(const QLocale &locale, int month, int,
                                              QLocale::FormatType format) const
{
    Q_ASSERT(month >= 1 && month <= maximumMonthsInYear());
    return rawStandaloneMonthName(localeMonthIndexData()[locale.d->m_index],
                                  localeMonthData(), month, format);
}

QString QRomanCalendar::standaloneMonthName(const QLocale &locale, int month, int year,
                                            QLocale::FormatType format) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (locale.d->m_data == &systemLocaleData) {
        Q_ASSERT(month >= 1 && month <= 12);
        QSystemLocale::QueryType queryType = QSystemLocale::StandaloneMonthNameLong;
        switch (format) {
        case QLocale::LongFormat:
            queryType = QSystemLocale::StandaloneMonthNameLong;
            break;
        case QLocale::ShortFormat:
            queryType = QSystemLocale::StandaloneMonthNameShort;
            break;
        case QLocale::NarrowFormat:
            queryType = QSystemLocale::StandaloneMonthNameNarrow;
            break;
        }
        QVariant res = systemLocale()->query(queryType, month);
        if (!res.isNull())
            return res.toString();
    }
#endif

    return QCalendarBackend::standaloneMonthName(locale, month, year, format);
}

// Most calendars share the common week-day naming, modulo locale.
// Calendars that don't must override these methods.
QString QCalendarBackend::weekDayName(const QLocale &locale, int day,
                                      QLocale::FormatType format) const
{
    if (day < 1 || day > 7)
        return QString();

#ifndef QT_NO_SYSTEMLOCALE
    if (locale.d->m_data == &systemLocaleData) {
        QSystemLocale::QueryType queryType = QSystemLocale::DayNameLong;
        switch (format) {
        case QLocale::LongFormat:
            queryType = QSystemLocale::DayNameLong;
            break;
        case QLocale::ShortFormat:
            queryType = QSystemLocale::DayNameShort;
            break;
        case QLocale::NarrowFormat:
            queryType = QSystemLocale::DayNameNarrow;
            break;
        }
        QVariant res = systemLocale()->query(queryType, day);
        if (!res.isNull())
            return res.toString();
    }
#endif

    return rawWeekDayName(locale.d->m_data, day, format);
}

QString QCalendarBackend::standaloneWeekDayName(const QLocale &locale, int day,
                                                QLocale::FormatType format) const
{
    if (day < 1 || day > 7)
        return QString();

#ifndef QT_NO_SYSTEMLOCALE
    if (locale.d->m_data == &systemLocaleData) {
        QSystemLocale::QueryType queryType = QSystemLocale::StandaloneDayNameLong;
        switch (format) {
        case QLocale::LongFormat:
            queryType = QSystemLocale::StandaloneDayNameLong;
            break;
        case QLocale::ShortFormat:
            queryType = QSystemLocale::StandaloneDayNameShort;
            break;
        case QLocale::NarrowFormat:
            queryType = QSystemLocale::StandaloneDayNameNarrow;
            break;
        }
        QVariant res = systemLocale()->query(queryType, day);
        if (!res.isNull())
            return res.toString();
    }
#endif

    return rawStandaloneWeekDayName(locale.d->m_data, day, format);
}

// End of this block of qcalendar.cpp refugees.  (One more follows.)

/*!
    \since 4.8

    Returns the first day of the week according to the current locale.
*/
Qt::DayOfWeek QLocale::firstDayOfWeek() const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        const auto res = systemLocale()->query(QSystemLocale::FirstDayOfWeek);
        if (!res.isNull())
            return static_cast<Qt::DayOfWeek>(res.toUInt());
    }
#endif
    return static_cast<Qt::DayOfWeek>(d->m_data->m_first_day_of_week);
}

QLocale::MeasurementSystem QLocalePrivate::measurementSystem() const
{
    for (const auto &system : ImperialMeasurementSystems) {
        if (system.languageId == m_data->m_language_id
            && system.territoryId == m_data->m_territory_id) {
            return system.system;
        }
    }
    return QLocale::MetricSystem;
}

/*!
    \since 4.8

    Returns a list of days that are considered weekdays according to the current locale.
*/
QList<Qt::DayOfWeek> QLocale::weekdays() const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        auto res
            = qvariant_cast<QList<Qt::DayOfWeek> >(systemLocale()->query(QSystemLocale::Weekdays));
        if (!res.isEmpty())
            return res;
    }
#endif
    QList<Qt::DayOfWeek> weekdays;
    quint16 weekendStart = d->m_data->m_weekend_start;
    quint16 weekendEnd = d->m_data->m_weekend_end;
    for (int day = Qt::Monday; day <= Qt::Sunday; day++) {
        if ((weekendEnd >= weekendStart && (day < weekendStart || day > weekendEnd)) ||
            (weekendEnd < weekendStart && (day > weekendEnd && day < weekendStart)))
                weekdays << static_cast<Qt::DayOfWeek>(day);
    }
    return weekdays;
}

/*!
    \since 4.4

    Returns the measurement system for the locale.
*/
QLocale::MeasurementSystem QLocale::measurementSystem() const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        const auto res = systemLocale()->query(QSystemLocale::MeasurementSystem);
        if (!res.isNull())
            return MeasurementSystem(res.toInt());
    }
#endif

    return d->measurementSystem();
}

/*!
  \since 4.7

  Returns the text direction of the language.
*/
Qt::LayoutDirection QLocale::textDirection() const
{
    switch (script()) {
    case AdlamScript:
    case ArabicScript:
    case AvestanScript:
    case CypriotScript:
    case HatranScript:
    case HebrewScript:
    case ImperialAramaicScript:
    case InscriptionalPahlaviScript:
    case InscriptionalParthianScript:
    case KharoshthiScript:
    case LydianScript:
    case MandaeanScript:
    case ManichaeanScript:
    case MendeKikakuiScript:
    case MeroiticCursiveScript:
    case MeroiticScript:
    case NabataeanScript:
    case NkoScript:
    case OldHungarianScript:
    case OldNorthArabianScript:
    case OldSouthArabianScript:
    case OrkhonScript:
    case PalmyreneScript:
    case PhoenicianScript:
    case PsalterPahlaviScript:
    case SamaritanScript:
    case SyriacScript:
    case ThaanaScript:
        return Qt::RightToLeft;
    default:
        break;
    }
    return Qt::LeftToRight;
}

/*!
  \since 4.8

  Returns an uppercase copy of \a str.

  If Qt Core is using the ICU libraries, they will be used to perform
  the transformation according to the rules of the current locale.
  Otherwise the conversion may be done in a platform-dependent manner,
  with QString::toUpper() as a generic fallback.

  \sa QString::toUpper()
*/
QString QLocale::toUpper(const QString &str) const
{
#if QT_CONFIG(icu)
    bool ok = true;
    QString result = QIcu::toUpper(d->bcp47Name('_'), str, &ok);
    if (ok)
        return result;
    // else fall through and use Qt's toUpper
#endif
    return str.toUpper();
}

/*!
  \since 4.8

  Returns a lowercase copy of \a str.

  If Qt Core is using the ICU libraries, they will be used to perform
  the transformation according to the rules of the current locale.
  Otherwise the conversion may be done in a platform-dependent manner,
  with QString::toLower() as a generic fallback.

  \sa QString::toLower()
*/
QString QLocale::toLower(const QString &str) const
{
#if QT_CONFIG(icu)
    bool ok = true;
    const QString result = QIcu::toLower(d->bcp47Name('_'), str, &ok);
    if (ok)
        return result;
    // else fall through and use Qt's toUpper
#endif
    return str.toLower();
}


/*!
    \since 4.5

    Returns the localized name of the "AM" suffix for times specified using
    the conventions of the 12-hour clock.

    \sa pmText()
*/
QString QLocale::amText() const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        auto res = systemLocale()->query(QSystemLocale::AMText).toString();
        if (!res.isEmpty())
            return res;
    }
#endif
    return d->m_data->anteMeridiem().getData(am_data);
}

/*!
    \since 4.5

    Returns the localized name of the "PM" suffix for times specified using
    the conventions of the 12-hour clock.

    \sa amText()
*/
QString QLocale::pmText() const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        auto res = systemLocale()->query(QSystemLocale::PMText).toString();
        if (!res.isEmpty())
            return res;
    }
#endif
    return d->m_data->postMeridiem().getData(pm_data);
}

// Another intrusion from QCalendar, using some of the tools above:

QString QCalendarBackend::dateTimeToString(QStringView format, const QDateTime &datetime,
                                           QDate dateOnly, QTime timeOnly,
                                           const QLocale &locale) const
{
    QDate date;
    QTime time;
    bool formatDate = false;
    bool formatTime = false;
    if (datetime.isValid()) {
        date = datetime.date();
        time = datetime.time();
        formatDate = true;
        formatTime = true;
    } else if (dateOnly.isValid()) {
        date = dateOnly;
        formatDate = true;
    } else if (timeOnly.isValid()) {
        time = timeOnly;
        formatTime = true;
    } else {
        return QString();
    }

    QString result;
    int year = 0, month = 0, day = 0;
    if (formatDate) {
        const auto parts = julianDayToDate(date.toJulianDay());
        if (!parts.isValid())
            return QString();
        year = parts.year;
        month = parts.month;
        day = parts.day;
    }

    auto appendToResult = [&](int t, int repeat) {
        auto data = locale.d->m_data;
        if (repeat > 1)
            result.append(data->longLongToString(t, -1, 10, repeat, QLocaleData::ZeroPadded));
        else
            result.append(data->longLongToString(t));
    };

    auto formatType = [](int repeat) {
        return repeat == 3 ? QLocale::ShortFormat : QLocale::LongFormat;
    };

    qsizetype i = 0;
    while (i < format.size()) {
        if (format.at(i).unicode() == '\'') {
            result.append(qt_readEscapedFormatString(format, &i));
            continue;
        }

        const QChar c = format.at(i);
        qsizetype rep = qt_repeatCount(format.mid(i));
        Q_ASSERT(rep < std::numeric_limits<int>::max());
        int repeat = int(rep);
        bool used = false;
        if (formatDate) {
            switch (c.unicode()) {
            case 'y':
                used = true;
                if (repeat >= 4)
                    repeat = 4;
                else if (repeat >= 2)
                    repeat = 2;

                switch (repeat) {
                case 4:
                    appendToResult(year, (year < 0) ? 5 : 4);
                    break;
                case 2:
                    appendToResult(year % 100, 2);
                    break;
                default:
                    repeat = 1;
                    result.append(c);
                    break;
                }
                break;

            case 'M':
                used = true;
                repeat = qMin(repeat, 4);
                if (repeat <= 2)
                    appendToResult(month, repeat);
                else
                    result.append(monthName(locale, month, year, formatType(repeat)));
                break;

            case 'd':
                used = true;
                repeat = qMin(repeat, 4);
                if (repeat <= 2)
                    appendToResult(day, repeat);
                else
                    result.append(
                            locale.dayName(dayOfWeek(date.toJulianDay()), formatType(repeat)));
                break;

            default:
                break;
            }
        }
        if (!used && formatTime) {
            switch (c.unicode()) {
            case 'h': {
                used = true;
                repeat = qMin(repeat, 2);
                int hour = time.hour();
                if (timeFormatContainsAP(format)) {
                    if (hour > 12)
                        hour -= 12;
                    else if (hour == 0)
                        hour = 12;
                }
                appendToResult(hour, repeat);
                break;
            }
            case 'H':
                used = true;
                repeat = qMin(repeat, 2);
                appendToResult(time.hour(), repeat);
                break;

            case 'm':
                used = true;
                repeat = qMin(repeat, 2);
                appendToResult(time.minute(), repeat);
                break;

            case 's':
                used = true;
                repeat = qMin(repeat, 2);
                appendToResult(time.second(), repeat);
                break;

            case 'A':
            case 'a': {
                QString text = time.hour() < 12 ? locale.amText() : locale.pmText();
                used = true;
                repeat = 1;
                if (format.mid(i + 1).startsWith(u'p', Qt::CaseInsensitive))
                    ++repeat;
                if (c.unicode() == 'A' && (repeat == 1 || format.at(i + 1).unicode() == 'P'))
                    text = std::move(text).toUpper();
                else if (c.unicode() == 'a' && (repeat == 1 || format.at(i + 1).unicode() == 'p'))
                    text = std::move(text).toLower();
                // else 'Ap' or 'aP' => use CLDR text verbatim, preserving case
                result.append(text);
                break;
            }

            case 'z':
                used = true;
                repeat = qMin(repeat, 3);

                // note: the millisecond component is treated like the decimal part of the seconds
                // so ms == 2 is always printed as "002", but ms == 200 can be either "2" or "200"
                appendToResult(time.msec(), 3);
                if (repeat != 3) {
                    if (result.endsWith(locale.zeroDigit()))
                        result.chop(1);
                    if (result.endsWith(locale.zeroDigit()))
                        result.chop(1);
                }
                break;

            case 't': {
                enum AbbrType { Long, Offset, Short };
                const auto tzAbbr = [locale](const QDateTime &when, AbbrType type) {
#if QT_CONFIG(timezone)
                    if (type != Short || locale != QLocale::system()) {
                        QTimeZone::NameType mode =
                            type == Short ? QTimeZone::ShortName
                            : type == Long ? QTimeZone::LongName : QTimeZone::OffsetName;
                        return when.timeRepresentation().displayName(when, mode, locale);
                    } // else: prefer QDateTime's abbreviation, for backwards-compatibility.
#endif // else, make do with non-localized abbreviation:
                    if (type != Offset)
                        return when.timeZoneAbbreviation();
                    // For Offset, we can coerce to a UTC-based zone's abbreviation:
                    return when.toOffsetFromUtc(when.offsetFromUtc()).timeZoneAbbreviation();
                };
                used = true;
                repeat = qMin(repeat, 4);
                // If we don't have a date-time, use the current system time:
                const QDateTime when = formatDate ? datetime : QDateTime::currentDateTime();
                QString text;
                switch (repeat) {
                case 4:
                    text = tzAbbr(when, Long);
                    break;
                case 3: // ±hh:mm
                case 2: // ±hhmm (we'll remove the ':' at the end)
                    text = tzAbbr(when, Offset);
                    Q_ASSERT(text.startsWith("UTC"_L1)); // Need to strip this.
                    // The Qt::UTC case omits the zero offset:
                    text = (text.size() == 3
                            ? u"+00:00"_s
                            : (text.size() <= 6
                               // Whole-hour offsets may lack the zero minutes:
                               ? QStringView{text}.sliced(3) + ":00"_L1
                               : std::move(text).sliced(3)));
                    if (repeat == 2)
                        text = text.remove(u':');
                    break;
                default:
                    text = tzAbbr(when, Short);
                    // UTC-offset zones only include minutes if non-zero.
                    if (text.startsWith("UTC"_L1) && text.size() == 6)
                        text += ":00"_L1;
                    break;
                }
                if (!text.isEmpty())
                    result.append(text);
                break;
            }

            default:
                break;
            }
        }
        if (!used)
            result.resize(result.size() + repeat, c);
        i += repeat;
    }

    return result;
}

// End of QCalendar intrustions

QString QLocaleData::doubleToString(double d, int precision, DoubleForm form,
                                    int width, unsigned flags) const
{
    // Although the special handling of F.P.Shortest below is limited to
    // DFSignificantDigits, the double-conversion library does treat it
    // specially for the other forms, shedding trailing zeros for DFDecimal and
    // using the shortest mantissa that faithfully represents the value for
    // DFExponent.
    if (precision != QLocale::FloatingPointShortest && precision < 0)
        precision = 6;
    if (width < 0)
        width = 0;

    int decpt;
    qsizetype bufSize = 1;
    if (precision == QLocale::FloatingPointShortest)
        bufSize += std::numeric_limits<double>::max_digits10;
    else if (form == DFDecimal && qt_is_finite(d))
        bufSize += wholePartSpace(qAbs(d)) + precision;
    else // Add extra digit due to different interpretations of precision.
        bufSize += qMax(2, precision) + 1; // Must also be big enough for "nan" or "inf"

    QVarLengthArray<char> buf(bufSize);
    int length;
    bool negative = false;
    qt_doubleToAscii(d, form, precision, buf.data(), bufSize, negative, length, decpt);

    const QString prefix = signPrefix(negative && !isZero(d), flags);
    QString numStr;

    if (length == 3
        && (qstrncmp(buf.data(), "inf", 3) == 0 || qstrncmp(buf.data(), "nan", 3) == 0)) {
        numStr = QString::fromLatin1(buf.data(), length);
    } else { // Handle finite values
        const QString zero = zeroDigit();
        QString digits = QString::fromLatin1(buf.data(), length);

        if (zero == u"0") {
            // No need to convert digits.
            Q_ASSERT(std::all_of(buf.cbegin(), buf.cbegin() + length, isAsciiDigit));
            // That check is taken care of in unicodeForDigits, below.
        } else if (zero.size() == 2 && zero.at(0).isHighSurrogate()) {
            const char32_t zeroUcs4 = QChar::surrogateToUcs4(zero.at(0), zero.at(1));
            QString converted;
            converted.reserve(2 * digits.size());
            for (QChar ch : std::as_const(digits)) {
                const char32_t digit = unicodeForDigit(ch.unicode() - '0', zeroUcs4);
                Q_ASSERT(QChar::requiresSurrogates(digit));
                converted.append(QChar::highSurrogate(digit));
                converted.append(QChar::lowSurrogate(digit));
            }
            digits = converted;
        } else {
            Q_ASSERT(zero.size() == 1);
            Q_ASSERT(!zero.at(0).isSurrogate());
            char16_t z = zero.at(0).unicode();
            char16_t *const value = reinterpret_cast<char16_t *>(digits.data());
            for (qsizetype i = 0; i < digits.size(); ++i)
                value[i] = unicodeForDigit(value[i] - '0', z);
        }

        const bool mustMarkDecimal = flags & ForcePoint;
        const bool groupDigits = flags & GroupDigits;
        const int minExponentDigits = flags & ZeroPadExponent ? 2 : 1;
        switch (form) {
        case DFExponent:
            numStr = exponentForm(std::move(digits), decpt, precision, PMDecimalDigits,
                                  mustMarkDecimal, minExponentDigits);
            break;
        case DFDecimal:
            numStr = decimalForm(std::move(digits), decpt, precision, PMDecimalDigits,
                                 mustMarkDecimal, groupDigits);
            break;
        case DFSignificantDigits: {
            PrecisionMode mode
                = (flags & AddTrailingZeroes) ? PMSignificantDigits : PMChopTrailingZeros;

            /* POSIX specifies sprintf() to follow fprintf(), whose 'g/G' format
               says; with P = 6 if precision unspecified else 1 if precision is
               0 else precision; when 'e/E' would have exponent X, use:
                 * 'f/F' if P > X >= -4, with precision P-1-X
                 * 'e/E' otherwise, with precision P-1
               Helpfully, we already have mapped precision < 0 to 6 - except for
               F.P.Shortest mode, which is its own story - and those of our
               callers with unspecified precision either used 6 or -1 for it.
            */
            bool useDecimal;
            if (precision == QLocale::FloatingPointShortest) {
                // Find out which representation is shorter.
                // Set bias to everything added to exponent form but not
                // decimal, minus the converse.

                // Exponent adds separator, sign and digits:
                int bias = 2 + minExponentDigits;
                // Decimal form may get grouping separators inserted:
                if (groupDigits && decpt >= m_grouping_top + m_grouping_least)
                    bias -= (decpt - m_grouping_least) / m_grouping_higher + 1;
                // X = decpt - 1 needs two digits if decpt > 10:
                if (decpt > 10 && minExponentDigits == 1)
                    ++bias;
                // Assume digitCount < 95, so we can ignore the 3-digit
                // exponent case (we'll set useDecimal false anyway).

                const qsizetype digitCount = digits.size() / zero.size();
                if (!mustMarkDecimal) {
                    // Decimal separator is skipped if at end; adjust if
                    // that happens for only one form:
                    if (digitCount <= decpt && digitCount > 1)
                        ++bias; // decimal but not exponent
                    else if (digitCount == 1 && decpt <= 0)
                        --bias; // exponent but not decimal
                }
                // When 0 < decpt <= digitCount, the forms have equal digit
                // counts, plus things bias has taken into account; otherwise
                // decimal form's digit count is right-padded with zeros to
                // decpt, when decpt is positive, otherwise it's left-padded
                // with 1 - decpt zeros.
                useDecimal = (decpt <= 0 ? 1 - decpt <= bias
                              : decpt <= digitCount ? 0 <= bias : decpt <= digitCount + bias);
            } else {
                // X == decpt - 1, POSIX's P; -4 <= X < P iff -4 < decpt <= P
                Q_ASSERT(precision >= 0);
                useDecimal = decpt > -4 && decpt <= (precision ? precision : 1);
            }

            numStr = useDecimal
                ? decimalForm(std::move(digits), decpt, precision, mode,
                              mustMarkDecimal, groupDigits)
                : exponentForm(std::move(digits), decpt, precision, mode,
                               mustMarkDecimal, minExponentDigits);
            break;
        }
        }

        // Pad with zeros. LeftAdjusted overrides ZeroPadded.
        if (flags & ZeroPadded && !(flags & LeftAdjusted)) {
            for (qsizetype i = numStr.size() / zero.size() + prefix.size(); i < width; ++i)
                numStr.prepend(zero);
        }
    }

    return prefix + (flags & CapitalEorX ? std::move(numStr).toUpper() : numStr);
}

QString QLocaleData::decimalForm(QString &&digits, int decpt, int precision,
                                 PrecisionMode pm, bool mustMarkDecimal,
                                 bool groupDigits) const
{
    const QString zero = zeroDigit();
    const auto digitWidth = zero.size();
    Q_ASSERT(digitWidth == 1 || digitWidth == 2);
    Q_ASSERT(digits.size() % digitWidth == 0);

    // Separator needs to go at index decpt: so add zeros before or after the
    // given digits, if they don't reach that position already:
    if (decpt < 0) {
        for (; decpt < 0; ++decpt)
            digits.prepend(zero);
    } else {
        for (qsizetype i = digits.size() / digitWidth; i < decpt; ++i)
            digits.append(zero);
    }

    switch (pm) {
    case PMDecimalDigits:
        for (qsizetype i = digits.size() / digitWidth - decpt; i < precision; ++i)
            digits.append(zero);
        break;
    case  PMSignificantDigits:
        for (qsizetype i = digits.size() / digitWidth; i < precision; ++i)
            digits.append(zero);
        break;
    case PMChopTrailingZeros:
        Q_ASSERT(digits.size() / digitWidth <= qMax(decpt, 1) || !digits.endsWith(zero));
        break;
    }

    if (mustMarkDecimal || decpt < digits.size() / digitWidth)
        digits.insert(decpt * digitWidth, decimalPoint());

    if (groupDigits) {
        const QString group = groupSeparator();
        qsizetype i = decpt - m_grouping_least;
        if (i >= m_grouping_top) {
            digits.insert(i * digitWidth, group);
            while ((i -= m_grouping_higher) > 0)
                digits.insert(i * digitWidth, group);
        }
    }

    if (decpt == 0)
        digits.prepend(zero);

    return std::move(digits);
}

QString QLocaleData::exponentForm(QString &&digits, int decpt, int precision,
                                  PrecisionMode pm, bool mustMarkDecimal,
                                  int minExponentDigits) const
{
    const QString zero = zeroDigit();
    const auto digitWidth = zero.size();
    Q_ASSERT(digitWidth == 1 || digitWidth == 2);
    Q_ASSERT(digits.size() % digitWidth == 0);

    switch (pm) {
    case PMDecimalDigits:
        for (qsizetype i = digits.size() / digitWidth; i < precision + 1; ++i)
            digits.append(zero);
        break;
    case PMSignificantDigits:
        for (qsizetype i = digits.size() / digitWidth; i < precision; ++i)
            digits.append(zero);
        break;
    case PMChopTrailingZeros:
        Q_ASSERT(digits.size() / digitWidth <= 1 || !digits.endsWith(zero));
        break;
    }

    if (mustMarkDecimal || digits.size() > digitWidth)
        digits.insert(digitWidth, decimalPoint());

    digits.append(exponentSeparator());
    digits.append(longLongToString(decpt - 1, minExponentDigits, 10, -1, AlwaysShowSign));

    return std::move(digits);
}

QString QLocaleData::signPrefix(bool negative, unsigned flags) const
{
    if (negative)
        return negativeSign();
    if (flags & AlwaysShowSign)
        return positiveSign();
    if (flags & BlankBeforePositive)
        return QStringView(u" ").toString();
    return {};
}

QString QLocaleData::longLongToString(qlonglong n, int precision,
                                      int base, int width, unsigned flags) const
{
    bool negative = n < 0;

    /*
      Negating std::numeric_limits<qlonglong>::min() hits undefined behavior, so
      taking an absolute value has to take a slight detour.
     */
    QString numStr = qulltoa(negative ? 1u + qulonglong(-(n + 1)) : qulonglong(n),
                             base, zeroDigit());

    return applyIntegerFormatting(std::move(numStr), negative, precision, base, width, flags);
}

QString QLocaleData::unsLongLongToString(qulonglong l, int precision,
                                         int base, int width, unsigned flags) const
{
    const QString zero = zeroDigit();
    QString resultZero = base == 10 ? zero : QStringLiteral("0");
    return applyIntegerFormatting(l ? qulltoa(l, base, zero) : resultZero,
                                  false, precision, base, width, flags);
}

QString QLocaleData::applyIntegerFormatting(QString &&numStr, bool negative, int precision,
                                            int base, int width, unsigned flags) const
{
    const QString zero = base == 10 ? zeroDigit() : QStringLiteral("0");
    const auto digitWidth = zero.size();
    const auto digitCount = numStr.size() / digitWidth;

    const auto basePrefix = [&] () -> QStringView {
        if (flags & ShowBase) {
            const bool upper = flags & UppercaseBase;
            if (base == 16)
                return upper ? u"0X" : u"0x";
            if (base == 2)
                return upper ? u"0B" : u"0b";
            if (base == 8 && !numStr.startsWith(zero))
                return zero;
        }
        return {};
    }();

    const QString prefix = signPrefix(negative, flags) + basePrefix;
    // Count how much of width we've used up.  Each digit counts as one
    qsizetype usedWidth = digitCount + prefix.size();

    if (base == 10 && flags & GroupDigits) {
        const QString group = groupSeparator();
        qsizetype i = digitCount - m_grouping_least;
        if (i >= m_grouping_top) {
            numStr.insert(i * digitWidth, group);
            ++usedWidth;
            while ((i -= m_grouping_higher) > 0) {
                numStr.insert(i * digitWidth, group);
                ++usedWidth;
            }
        }
        // TODO: should we group any zero-padding we add later ?
    }

    const bool noPrecision = precision == -1;
    if (noPrecision)
        precision = 1;

    for (qsizetype i = numStr.size(); i < precision; ++i) {
        numStr.prepend(zero);
        usedWidth++;
    }

    // LeftAdjusted overrides ZeroPadded; and sprintf() only pads when
    // precision is not specified in the format string.
    if (noPrecision && flags & ZeroPadded && !(flags & LeftAdjusted)) {
        for (qsizetype i = usedWidth; i < width; ++i)
            numStr.prepend(zero);
    }

    QString result(flags & CapitalEorX ? std::move(numStr).toUpper() : std::move(numStr));
    if (prefix.size())
        result.prepend(prefix);
    return result;
}

inline QLocaleData::NumericData QLocaleData::numericData(QLocaleData::NumberMode mode) const
{
    NumericData result;
    if (this == c()) {
        result.isC = true;
        return result;
    }
    result.setZero(zero().viewData(single_character_data));
    result.group = groupDelim().viewData(single_character_data);
    // Note: minus, plus and exponent might not actually be single characters.
    result.minus = minus().viewData(single_character_data);
    result.plus = plus().viewData(single_character_data);
    if (mode != IntegerMode)
        result.decimal = decimalSeparator().viewData(single_character_data);
    if (mode == DoubleScientificMode) {
        result.exponent = exponential().viewData(single_character_data);
        // exponentCyrillic means "apply the Cyrrilic-specific exponent hack"
        result.exponentCyrillic = m_script_id == QLocale::CyrillicScript;
    }
#ifndef QT_NO_SYSTEMLOCALE
    if (this == &systemLocaleData) {
        const auto getString = [sys = systemLocale()](QSystemLocale::QueryType query) {
            return sys->query(query).toString();
        };
        if (mode != IntegerMode) {
            result.sysDecimal = getString(QSystemLocale::DecimalPoint);
            if (result.sysDecimal.size())
                result.decimal = QStringView{result.sysDecimal};
        }
        result.sysGroup = getString(QSystemLocale::GroupSeparator);
        if (result.sysGroup.size())
            result.group = QStringView{result.sysGroup};
        result.sysMinus = getString(QSystemLocale::NegativeSign);
        if (result.sysMinus.size())
            result.minus = QStringView{result.sysMinus};
        result.sysPlus = getString(QSystemLocale::PositiveSign);
        if (result.sysPlus.size())
            result.plus = QStringView{result.sysPlus};
        result.setZero(getString(QSystemLocale::ZeroDigit));
    }
#endif

    return result;
}

namespace {
// A bit like QStringIterator but rather specialized ... and some of the tokens
// it recognizes aren't single Unicode code-points (but it does map each to a
// single character).
class NumericTokenizer
{
    // TODO: use deterministic finite-state-automata.
    // TODO QTBUG-95460: CLDR has Inf/NaN representations per locale.
    static constexpr char lettersInfNaN[] = "afin"; // Letters of Inf, NaN
    static constexpr auto matchInfNaN = QtPrivate::makeCharacterSetMatch<lettersInfNaN>();
    const QStringView m_text;
    const QLocaleData::NumericData m_guide;
    qsizetype m_index = 0;
    const QLocaleData::NumberMode m_mode;
    static_assert('+' + 1 == ',' && ',' + 1 == '-' && '-' + 1 == '.');
    char lastMark; // C locale accepts '+' through lastMark.
public:
    NumericTokenizer(QStringView text, QLocaleData::NumericData &&guide,
                     QLocaleData::NumberMode mode)
        : m_text(text), m_guide(guide), m_mode(mode),
          lastMark(mode == QLocaleData::IntegerMode ? '-' : '.')
    {
        Q_ASSERT(m_guide.isValid(mode));
    }
    bool done() const { return !(m_index < m_text.size()); }
    qsizetype index() const { return m_index; }
    inline int asBmpDigit(char16_t digit) const;
    char nextToken();
};

int NumericTokenizer::asBmpDigit(char16_t digit) const
{
    // If digit *is* a digit, result will be in range 0 through 9; otherwise not.
    // Must match qlocale_tools.h's unicodeForDigit()
    if (m_guide.zeroUcs != u'\u3007' || digit == m_guide.zeroUcs)
        return digit - m_guide.zeroUcs;

    // QTBUG-85409: Suzhou's digits aren't contiguous !
    if (digit == u'\u3020') // U+3020 POSTAL MARK FACE is not a digit.
        return -1;
    // ... but is followed by digits 1 through 9.
    return digit - u'\u3020';
}

char NumericTokenizer::nextToken()
{
    // As long as caller stops iterating on a zero return, those don't need to
    // keep m_index correctly updated.
    Q_ASSERT(!done());
    // Mauls non-letters above 'Z' but we don't care:
    const auto asciiLower = [](unsigned char c) { return c >= 'A' ? c | 0x20 : c; };
    const QStringView tail = m_text.sliced(m_index);
    const QChar ch = tail.front();
    if (ch == u'\u2212') {
        // Special case: match the "proper" minus sign, for all locales.
        ++m_index;
        return '-';
    }
    if (m_guide.isC) {
        // "Conversion" to C locale is just a filter:
        ++m_index;
        if (Q_LIKELY(ch.unicode() < 256)) {
            unsigned char ascii = asciiLower(ch.toLatin1());
            if (Q_LIKELY(isAsciiDigit(ascii) || ('+' <= ascii && ascii <= lastMark)
                         // No caller presently (6.5) passes DoubleStandardMode,
                         // so !IntegerMode implies scientific, for now.
                         || (m_mode != QLocaleData::IntegerMode
                             && matchInfNaN.matches(ascii))
                         || (m_mode == QLocaleData::DoubleScientificMode
                             && ascii == 'e'))) {
                return ascii;
            }
        }
        return 0;
    }
    if (ch.unicode() < 256) {
        // Accept the C locale's digits and signs in all locales:
        char ascii = asciiLower(ch.toLatin1());
        if (isAsciiDigit(ascii) || ascii == '-' || ascii == '+'
            // Also its Inf and NaN letters:
            || (m_mode != QLocaleData::IntegerMode && matchInfNaN.matches(ascii))) {
            ++m_index;
            return ascii;
        }
    }

    // Other locales may be trickier:
    if (tail.startsWith(m_guide.minus)) {
        m_index += m_guide.minus.size();
        return '-';
    }
    if (tail.startsWith(m_guide.plus)) {
        m_index += m_guide.plus.size();
        return '+';
    }
    if (!m_guide.group.isEmpty() && tail.startsWith(m_guide.group)) {
        m_index += m_guide.group.size();
        return ',';
    }
    if (m_mode != QLocaleData::IntegerMode && tail.startsWith(m_guide.decimal)) {
        m_index += m_guide.decimal.size();
        return '.';
    }
    if (m_mode == QLocaleData::DoubleScientificMode
        && tail.startsWith(m_guide.exponent, Qt::CaseInsensitive)) {
        m_index += m_guide.exponent.size();
        return 'e';
    }

    // Must match qlocale_tools.h's unicodeForDigit()
    if (m_guide.zeroLen == 1) {
        if (!ch.isSurrogate()) {
            const uint gap = asBmpDigit(ch.unicode());
            if (gap < 10u) {
                ++m_index;
                return '0' + gap;
            }
        } else if (ch.isHighSurrogate() && tail.size() > 1 && tail.at(1).isLowSurrogate()) {
            return 0;
        }
    } else if (ch.isHighSurrogate()) {
        // None of the corner cases below matches a surrogate, so (update
        // already and) return early if we don't have a digit.
        if (tail.size() > 1) {
            QChar low = tail.at(1);
            if (low.isLowSurrogate()) {
                m_index += 2;
                const uint gap = QChar::surrogateToUcs4(ch, low) - m_guide.zeroUcs;
                return gap < 10u ? '0' + gap : 0;
            }
        }
        return 0;
    }

    // All cases where tail starts with properly-matched surrogate pair
    // have been handled by this point.
    Q_ASSERT(!(ch.isHighSurrogate() && tail.size() > 1 && tail.at(1).isLowSurrogate()));

    // Weird corner cases follow (code above assumes these match no surrogates).

    // Some locales use a non-breaking space (U+00A0) or its thin version
    // (U+202f) for grouping. These look like spaces, so people (and thus some
    // of our tests) use a regular space instead and complain if it doesn't
    // work.
    // Should this be extended generally to any case where group is a space ?
    if ((m_guide.group == u"\u00a0" || m_guide.group == u"\u202f") && tail.startsWith(u' ')) {
        ++m_index;
        return ',';
    }

    // Cyrillic has its own E, used by Ukrainian as exponent; but others
    // writing Cyrillic may well use that; and Ukrainians might well use E.
    // All other Cyrillic locales (officially) use plain ASCII E.
    if (m_guide.exponentCyrillic // Only true in scientific float mode.
        && (tail.startsWith(u"\u0415", Qt::CaseInsensitive)
            || tail.startsWith(u"E", Qt::CaseInsensitive))) {
        ++m_index;
        return 'e';
    }

    return 0;
}
} // namespace with no name

/*
    Converts a number in locale representation to the C locale equivalent.

    Only has to guarantee that a string that is a correct representation of a
    number will be converted. Checks signs, separators and digits appear in all
    the places they should, and nowhere else.

    Returns true precisely if the number appears to be well-formed, modulo
    things a parser for C Locale strings (without digit-grouping separators;
    they're stripped) will catch. When it returns true, it records (and
    '\0'-terminates) the C locale representation in *result.

    Note: only QString integer-parsing methods have a base parameter (hence need
    to cope with letters as possible digits); but these are now all routed via
    byteArrayToU?LongLong(), so no longer come via here. The QLocale
    number-parsers only work in decimal, so don't have to cope with any digits
    other than 0 through 9.
*/
bool QLocaleData::numberToCLocale(QStringView s, QLocale::NumberOptions number_options,
                                  NumberMode mode, CharBuff *result) const
{
    s = s.trimmed();
    if (s.size() < 1)
        return false;
    NumericTokenizer tokens(s, numericData(mode), mode);

    // Digit-grouping details (all modes):
    qsizetype digitsInGroup = 0;
    qsizetype last_separator_idx = -1;
    qsizetype start_of_digits_idx = -1;

    // Floating-point details (non-integer modes):
    qsizetype decpt_idx = -1;
    qsizetype exponent_idx = -1;

    char last = '\0';
    while (!tokens.done()) {
        qsizetype idx = tokens.index(); // before nextToken() advances
        char out = tokens.nextToken();
        if (out == 0)
            return false;
        Q_ASSERT(tokens.index() > idx); // it always *should* advance (except on zero return)

        if (out == '.') {
            // Fail if more than one decimal point or point after e
            if (decpt_idx != -1 || exponent_idx != -1)
                return false;
            decpt_idx = idx;
        } else if (out == 'e') {
            exponent_idx = idx;
        }

        if (number_options.testFlag(QLocale::RejectLeadingZeroInExponent)
                && exponent_idx != -1 && out == '0') {
            // After the exponent there can only be '+', '-' or digits.
            // If we find a '0' directly after some non-digit, then that is a
            // leading zero, acceptable only if it is the whole exponent.
            if (!tokens.done() && !isAsciiDigit(last))
                return false;
        }

        if (number_options.testFlag(QLocale::RejectTrailingZeroesAfterDot) && decpt_idx >= 0) {
            // In a fractional part, a 0 just before the exponent is trailing:
            if (idx == exponent_idx && last == '0')
                return false;
        }

        if (!number_options.testFlag(QLocale::RejectGroupSeparator)) {
            if (isAsciiDigit(out)) {
                if (start_of_digits_idx == -1)
                    start_of_digits_idx = idx;
                ++digitsInGroup;
            } else if (out == ',') {
                // Don't allow group chars after the decimal point or exponent
                if (decpt_idx != -1 || exponent_idx != -1)
                    return false;

                if (last_separator_idx == -1) {
                    // Check distance from the beginning of the digits:
                    if (start_of_digits_idx == -1 || m_grouping_top > digitsInGroup
                        || digitsInGroup >= m_grouping_least + m_grouping_top) {
                        return false;
                    }
                } else {
                    // Check distance from the last separator:
                    if (digitsInGroup != m_grouping_higher)
                        return false;
                }

                last_separator_idx = idx;
                digitsInGroup = 0;
            } else if (mode != IntegerMode && (out == '.' || idx == exponent_idx)
                       && last_separator_idx != -1) {
                // Were there enough digits since the last group separator?
                if (digitsInGroup != m_grouping_least)
                    return false;

                // stop processing separators
                last_separator_idx = -1;
            }
        } else if (out == ',') {
            return false;
        }

        last = out;
        if (out != ',') // Leave group separators out of the result.
            result->append(out);
    }

    if (!number_options.testFlag(QLocale::RejectGroupSeparator) && last_separator_idx != -1) {
        // Were there enough digits since the last group separator?
        if (digitsInGroup != m_grouping_least)
            return false;
    }

    if (number_options.testFlag(QLocale::RejectTrailingZeroesAfterDot)
            && decpt_idx != -1 && exponent_idx == -1) {
        // In the fractional part, a final zero is trailing:
        if (last == '0')
            return false;
    }

    result->append('\0');
    return true;
}

ParsingResult
QLocaleData::validateChars(QStringView str, NumberMode numMode, int decDigits,
                           QLocale::NumberOptions number_options) const
{
    ParsingResult result;
    result.buff.reserve(str.size());

    enum { Whole, Fractional, Exponent } state = Whole;
    const bool scientific = numMode == DoubleScientificMode;
    NumericTokenizer tokens(str, numericData(numMode), numMode);
    char last = '\0';

    while (!tokens.done()) {
        char c = tokens.nextToken();

        if (isAsciiDigit(c)) {
            switch (state) {
            case Whole:
                // Nothing special to do (unless we want to check grouping sizes).
                break;
            case Fractional:
                // If a double has too many digits in its fractional part it is Invalid.
                if (decDigits-- == 0)
                    return {};
                break;
            case Exponent:
                if (!isAsciiDigit(last)) {
                    // This is the first digit in the exponent (there may have beena '+'
                    // or '-' in before). If it's a zero, the exponent is zero-padded.
                    if (c == '0' && (number_options & QLocale::RejectLeadingZeroInExponent))
                        return {};
                }
                break;
            }

        } else {
            switch (c) {
            case '.':
                // If an integer has a decimal point, it is Invalid.
                // A double can only have one, at the end of its whole-number part.
                if (numMode == IntegerMode || state != Whole)
                    return {};
                // Even when decDigits is 0, we do allow the decimal point to be
                // present - just as long as no digits follow it.

                state = Fractional;
                break;

            case '+':
            case '-':
                // A sign can only appear at the start or after the e of scientific:
                if (last != '\0' && !(scientific && last == 'e'))
                    return {};
                break;

            case ',':
                // Grouping is only allowed after a digit in the whole-number portion:
                if ((number_options & QLocale::RejectGroupSeparator) || state != Whole
                        || !isAsciiDigit(last)) {
                    return {};
                }
                // We could check grouping sizes are correct, but fixup()s are
                // probably better off correcting any misplacement instead.
                break;

            case 'e':
                // Only one e is allowed and only in scientific:
                if (!scientific || state == Exponent)
                    return {};
                state = Exponent;
                break;

            default:
                // Nothing else can validly appear in a number.
                // NumericTokenizer allows letters of "inf" and "nan", but
                // validators don't accept those values.
                // For anything else, tokens.nextToken() must have returned 0.
                Q_ASSERT(!c || c == 'a' || c == 'f' || c == 'i' || c == 'n');
                return {};
            }
        }

        last = c;
        if (c != ',') // Skip grouping
            result.buff.append(c);
    }

    result.state = ParsingResult::Acceptable;

    // Intermediate if it ends with any character that requires a digit after
    // it to be valid e.g. group separator, sign, or exponent
    if (last == ',' || last == '-' || last == '+' || last == 'e')
        result.state = ParsingResult::Intermediate;

    return result;
}

double QLocaleData::stringToDouble(QStringView str, bool *ok,
                                   QLocale::NumberOptions number_options) const
{
    CharBuff buff;
    if (!numberToCLocale(str, number_options, DoubleScientificMode, &buff)) {
        if (ok != nullptr)
            *ok = false;
        return 0.0;
    }
    auto r = qt_asciiToDouble(buff.constData(), buff.size() - 1);
    if (ok != nullptr)
        *ok = r.ok();
    return r.result;
}

QSimpleParsedNumber<qint64>
QLocaleData::stringToLongLong(QStringView str, int base,
                              QLocale::NumberOptions number_options) const
{
    CharBuff buff;
    if (!numberToCLocale(str, number_options, IntegerMode, &buff))
        return {};

    return bytearrayToLongLong(QByteArrayView(buff), base);
}

QSimpleParsedNumber<quint64>
QLocaleData::stringToUnsLongLong(QStringView str, int base,
                                 QLocale::NumberOptions number_options) const
{
    CharBuff buff;
    if (!numberToCLocale(str, number_options, IntegerMode, &buff))
        return {};

    return bytearrayToUnsLongLong(QByteArrayView(buff), base);
}

static bool checkParsed(QByteArrayView num, qsizetype used)
{
    if (used <= 0)
        return false;

    const qsizetype len = num.size();
    if (used < len && num[used] != '\0') {
        while (used < len && ascii_isspace(num[used]))
            ++used;
    }

    if (used < len && num[used] != '\0')
        // we stopped at a non-digit character after converting some digits
        return false;

    return true;
}

QSimpleParsedNumber<qint64> QLocaleData::bytearrayToLongLong(QByteArrayView num, int base)
{
    auto r = qstrntoll(num.data(), num.size(), base);
    if (!checkParsed(num, r.used))
        return {};
    return r;
}

QSimpleParsedNumber<quint64> QLocaleData::bytearrayToUnsLongLong(QByteArrayView num, int base)
{
    auto r = qstrntoull(num.data(), num.size(), base);
    if (!checkParsed(num, r.used))
        return {};
    return r;
}

/*!
    \since 4.8

    \enum QLocale::CurrencySymbolFormat

    Specifies the format of the currency symbol.

    \value CurrencyIsoCode a ISO-4217 code of the currency.
    \value CurrencySymbol a currency symbol.
    \value CurrencyDisplayName a user readable name of the currency.
*/

/*!
    \since 4.8
    Returns a currency symbol according to the \a format.
*/
QString QLocale::currencySymbol(CurrencySymbolFormat format) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        auto res = systemLocale()->query(QSystemLocale::CurrencySymbol, format).toString();
        if (!res.isEmpty())
            return res;
    }
#endif
    switch (format) {
    case CurrencySymbol:
        return d->m_data->currencySymbol().getData(currency_symbol_data);
    case CurrencyDisplayName:
        return d->m_data->currencyDisplayName().getData(currency_display_name_data);
    case CurrencyIsoCode: {
        const char *code = d->m_data->m_currency_iso_code;
        if (auto len = qstrnlen(code, 3))
            return QString::fromLatin1(code, qsizetype(len));
        break;
    }
    }
    return QString();
}

/*!
    \since 4.8

    Returns a localized string representation of \a value as a currency.
    If the \a symbol is provided it is used instead of the default currency symbol.

    \sa currencySymbol()
*/
QString QLocale::toCurrencyString(qlonglong value, const QString &symbol) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QSystemLocale::CurrencyToStringArgument arg(value, symbol);
        auto res = systemLocale()->query(QSystemLocale::CurrencyToString,
                                         QVariant::fromValue(arg)).toString();
        if (!res.isEmpty())
            return res;
    }
#endif
    QLocaleData::DataRange range = d->m_data->currencyFormatNegative();
    if (!range.size || value >= 0)
        range = d->m_data->currencyFormat();
    else
        value = -value;
    QString str = toString(value);
    QString sym = symbol.isNull() ? currencySymbol() : symbol;
    if (sym.isEmpty())
        sym = currencySymbol(CurrencyIsoCode);
    return range.viewData(currency_format_data).arg(str, sym);
}

/*!
    \since 4.8
    \overload
*/
QString QLocale::toCurrencyString(qulonglong value, const QString &symbol) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QSystemLocale::CurrencyToStringArgument arg(value, symbol);
        auto res = systemLocale()->query(QSystemLocale::CurrencyToString,
                                         QVariant::fromValue(arg)).toString();
        if (!res.isEmpty())
            return res;
    }
#endif
    QString str = toString(value);
    QString sym = symbol.isNull() ? currencySymbol() : symbol;
    if (sym.isEmpty())
        sym = currencySymbol(CurrencyIsoCode);
    return d->m_data->currencyFormat().getData(currency_format_data).arg(str, sym);
}

/*!
    \since 5.7
    \overload toCurrencyString()

    Returns a localized string representation of \a value as a currency.
    If the \a symbol is provided it is used instead of the default currency symbol.
    If the \a precision is provided it is used to set the precision of the currency value.

    \sa currencySymbol()
 */
QString QLocale::toCurrencyString(double value, const QString &symbol, int precision) const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        QSystemLocale::CurrencyToStringArgument arg(value, symbol);
        auto res = systemLocale()->query(QSystemLocale::CurrencyToString,
                                         QVariant::fromValue(arg)).toString();
        if (!res.isEmpty())
            return res;
    }
#endif
    QLocaleData::DataRange range = d->m_data->currencyFormatNegative();
    if (!range.size || value >= 0)
        range = d->m_data->currencyFormat();
    else
        value = -value;
    QString str = toString(value, 'f', precision == -1 ? d->m_data->m_currency_digits : precision);
    QString sym = symbol.isNull() ? currencySymbol() : symbol;
    if (sym.isEmpty())
        sym = currencySymbol(CurrencyIsoCode);
    return range.viewData(currency_format_data).arg(str, sym);
}

/*!
  \fn QString QLocale::toCurrencyString(float i, const QString &symbol, int precision) const
  \overload toCurrencyString()
*/

/*!
    \since 5.10

    \enum QLocale::DataSizeFormat

    Specifies the format for representation of data quantities.

    \omitvalue DataSizeBase1000
    \omitvalue DataSizeSIQuantifiers
    \value DataSizeIecFormat            format using base 1024 and IEC prefixes: KiB, MiB, GiB, ...
    \value DataSizeTraditionalFormat    format using base 1024 and SI prefixes: kB, MB, GB, ...
    \value DataSizeSIFormat             format using base 1000 and SI prefixes: kB, MB, GB, ...

    \sa formattedDataSize()
*/

/*!
    \since 5.10

    Converts a size in bytes to a human-readable localized string, comprising a
    number and a quantified unit. The quantifier is chosen such that the number
    is at least one, and as small as possible. For example if \a bytes is
    16384, \a precision is 2, and \a format is \l DataSizeIecFormat (the
    default), this function returns "16.00 KiB"; for 1330409069609 bytes it
    returns "1.21 GiB"; and so on. If \a format is \l DataSizeIecFormat or
    \l DataSizeTraditionalFormat, the given number of bytes is divided by a
    power of 1024, with result less than 1024; for \l DataSizeSIFormat, it is
    divided by a power of 1000, with result less than 1000.
    \c DataSizeIecFormat uses the new IEC standard quantifiers Ki, Mi and so on,
    whereas \c DataSizeSIFormat uses the older SI quantifiers k, M, etc., and
    \c DataSizeTraditionalFormat abuses them.
*/
QString QLocale::formattedDataSize(qint64 bytes, int precision, DataSizeFormats format) const
{
    int power, base = 1000;
    if (!bytes) {
        power = 0;
    } else if (format & DataSizeBase1000) {
        power = int(std::log10(qAbs(bytes)) / 3);
    } else { // Compute log2(bytes) / 10:
        power = int((63 - qCountLeadingZeroBits(quint64(qAbs(bytes)))) / 10);
        base = 1024;
    }
    // Only go to doubles if we'll be using a quantifier:
    const QString number = power
        ? toString(bytes / std::pow(double(base), power), 'f', qMin(precision, 3 * power))
        : toString(bytes);

    // We don't support sizes in units larger than exbibytes because
    // the number of bytes would not fit into qint64.
    Q_ASSERT(power <= 6 && power >= 0);
    QStringView unit;
    if (power > 0) {
        QLocaleData::DataRange range = (format & DataSizeSIQuantifiers)
            ? d->m_data->byteAmountSI() : d->m_data->byteAmountIEC();
        unit = range.viewListEntry(byte_unit_data, power - 1);
    } else {
        unit = d->m_data->byteCount().viewData(byte_unit_data);
    }

    return number + u' ' + unit;
}

/*!
    \since 4.8
    \brief List of locale names for use in selecting translations

    Each entry in the returned list is the name of a locale suitable to the
    user's preferences for what to translate the UI into. Where a name in the
    list is composed of several tags, they are joined as indicated by \a
    separator. Prior to Qt 6.7 a dash was used as separator.

    For example, using the default separator QLocale::TagSeparator::Dash, if the
    user has configured their system to use English as used in the USA, the list
    would be "en-Latn-US", "en-US", "en". The order of entries is the order in
    which to check for translations; earlier items in the list are to be
    preferred over later ones. If your translation files use underscores, rather
    than dashes, to separate locale tags, pass QLocale::TagSeparator::Underscore
    as \a separator.

    Most likely you do not need to use this function directly, but just pass the
    QLocale object to the QTranslator::load() function.

    \sa QTranslator, bcp47Name()
*/
QStringList QLocale::uiLanguages(TagSeparator separator) const
{
    const char sep = char(separator);
    QStringList uiLanguages;
    if (uchar(sep) > 0x7f) {
        badSeparatorWarning("uiLanguages", sep);
        return uiLanguages;
    }
    QList<QLocaleId> localeIds;
#ifdef QT_NO_SYSTEMLOCALE
    constexpr bool isSystem = false;
#else
    const bool isSystem = d->m_data == &systemLocaleData;
    if (isSystem) {
        uiLanguages = systemLocale()->query(QSystemLocale::UILanguages).toStringList();
        // ... but we need to include likely-adjusted forms of each of those, too.
        // For now, collect up locale Ids representing the entries, for later processing:
        for (const auto &entry : std::as_const(uiLanguages))
            localeIds.append(QLocaleId::fromName(entry));
        if (localeIds.isEmpty())
            localeIds.append(systemLocale()->fallbackLocale().d->m_data->id());
        // If the system locale (isn't C and) didn't include itself in the list,
        // or as fallback, presume to know better than it and put its name
        // first. (Known issue, QTBUG-104930, on some macOS versions when in
        // locale en_DE.) Our translation system might have a translation for a
        // locale the platform doesn't believe in.
        const QString name = bcp47Name(separator);
        if (!name.isEmpty() && language() != C && !uiLanguages.contains(name)) {
            // That uses contains(name) as a cheap pre-test, but there may be an
            // entry that matches this on purging likely subtags.
            const QLocaleId mine = d->m_data->id().withLikelySubtagsRemoved();
            const auto isMine = [mine](const QString &entry) {
                return QLocaleId::fromName(entry).withLikelySubtagsRemoved() == mine;
            };
            if (std::none_of(uiLanguages.constBegin(), uiLanguages.constEnd(), isMine)) {
                localeIds.prepend(d->m_data->id());
                uiLanguages.prepend(name);
            }
        }
    } else
#endif
    {
        localeIds.append(d->m_data->id());
    }
    for (qsizetype i = localeIds.size(); i-- > 0; ) {
        QLocaleId id = localeIds.at(i);
        qsizetype j;
        QByteArray prior;
        if (isSystem && i < uiLanguages.size()) {
            // Adding likely-adjusted forms to system locale's list.
            // Name the locale is derived from:
            prior = uiLanguages.at(i).toLatin1();
            // Insert just after the entry we're supplementing:
            j = i + 1;
        } else if (id.language_id == C) {
            // Attempt no likely sub-tag amendments to C:
            uiLanguages.append(QString::fromLatin1(id.name(sep)));
            continue;
        } else {
            // Plain locale or empty system uiLanguages; just append.
            prior = id.name(sep);
            uiLanguages.append(QString::fromLatin1(prior));
            j = uiLanguages.size();
        }

        const QLocaleId max = id.withLikelySubtagsAdded();
        const QLocaleId min = max.withLikelySubtagsRemoved();

        // Include minimal version (last) unless it's what our locale is derived from:
        if (auto name = min.name(sep); name != prior)
            uiLanguages.insert(j, QString::fromLatin1(name));
        else if (!isSystem)
            --j; // bcp47Name() matches min(): put more specific forms *before* it.

        if (id.script_id) {
            // Include scriptless version if likely-equivalent and distinct:
            id.script_id = 0;
            if (id != min && id.withLikelySubtagsAdded() == max) {
                if (auto name = id.name(sep); name != prior)
                    uiLanguages.insert(j, QString::fromLatin1(name));
            }
        }

        if (!id.territory_id) {
            Q_ASSERT(!min.territory_id);
            Q_ASSERT(!id.script_id); // because we just cleared it.
            // Include version with territory if it likely-equivalent and distinct:
            id.territory_id = max.territory_id;
            if (id != max && id.withLikelySubtagsAdded() == max) {
                if (auto name = id.name(sep); name != prior)
                    uiLanguages.insert(j, QString::fromLatin1(name));
            }
        }

        // Include version with all likely sub-tags (first) if distinct from the rest:
        if (max != min && max != id) {
            if (auto name = max.name(sep); name != prior)
                uiLanguages.insert(j, QString::fromLatin1(name));
        }
    }
    return uiLanguages;
}

/*!
  \since 5.13

  Returns the locale to use for collation.

  The result is usually this locale; however, the system locale (which is
  commonly the default locale) will return the system collation locale.
  The result is suitable for passing to QCollator's constructor.

  \sa QCollator
*/
QLocale QLocale::collation() const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        const auto res = systemLocale()->query(QSystemLocale::Collation).toString();
        if (!res.isEmpty())
            return QLocale(res);
    }
#endif
    return *this;
}

/*!
    \since 4.8

    Returns a native name of the language for the locale. For example
    "Schweizer Hochdeutsch" for the Swiss-German locale.

    \sa nativeTerritoryName(), languageToString()
*/
QString QLocale::nativeLanguageName() const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        auto res = systemLocale()->query(QSystemLocale::NativeLanguageName).toString();
        if (!res.isEmpty())
            return res;
    }
#endif
    return d->m_data->endonymLanguage().getData(endonyms_data);
}

/*!
    \since 6.2

    Returns a native name of the territory for the locale. For example
    "España" for Spanish/Spain locale.

    \sa nativeLanguageName(), territoryToString()
*/
QString QLocale::nativeTerritoryName() const
{
#ifndef QT_NO_SYSTEMLOCALE
    if (d->m_data == &systemLocaleData) {
        auto res = systemLocale()->query(QSystemLocale::NativeTerritoryName).toString();
        if (!res.isEmpty())
            return res;
    }
#endif
    return d->m_data->endonymTerritory().getData(endonyms_data);
}

#if QT_DEPRECATED_SINCE(6, 6)
/*!
    \deprecated [6.6] Use \l nativeTerritoryName() instead.
    \since 4.8

    Returns a native name of the territory for the locale. For example
    "España" for Spanish/Spain locale.

    \sa nativeLanguageName(), territoryToString()
*/
QString QLocale::nativeCountryName() const
{
    return nativeTerritoryName();
}
#endif

#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QLocale &l)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace().noquote()
        << "QLocale(" << QLocale::languageToString(l.language())
        << ", " << QLocale::scriptToString(l.script())
        << ", " << QLocale::territoryToString(l.territory()) << ')';
    return dbg;
}
#endif
QT_END_NAMESPACE

#ifndef QT_NO_QOBJECT
#include "moc_qlocale.cpp"
#endif