summaryrefslogtreecommitdiffstats
path: root/src/corelib/io/qurl.cpp
blob: 4882e3575f1b6829d99f0f08f0c72e4b652b1a45 (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
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Copyright (C) 2012 Intel Corporation.
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

/*!
    \class QUrl
    \inmodule QtCore

    \brief The QUrl class provides a convenient interface for working
    with URLs.

    \reentrant
    \ingroup io
    \ingroup network
    \ingroup shared


    It can parse and construct URLs in both encoded and unencoded
    form. QUrl also has support for internationalized domain names
    (IDNs).

    The most common way to use QUrl is to initialize it via the
    constructor by passing a QString. Otherwise, setUrl() can also
    be used.

    URLs can be represented in two forms: encoded or unencoded. The
    unencoded representation is suitable for showing to users, but
    the encoded representation is typically what you would send to
    a web server. For example, the unencoded URL
    "http://b\\uuml\c{}hler.example.com" would be sent to the server as
    "http://xn--bhler-kva.example.com/List%20of%20applicants.xml".

    A URL can also be constructed piece by piece by calling
    setScheme(), setUserName(), setPassword(), setHost(), setPort(),
    setPath(), setQuery() and setFragment(). Some convenience
    functions are also available: setAuthority() sets the user name,
    password, host and port. setUserInfo() sets the user name and
    password at once.

    Call isValid() to check if the URL is valid. This can be done at
    any point during the constructing of a URL.

    Constructing a query is particularly convenient through the use of the \l
    QUrlQuery class and its methods QUrlQuery::setQueryItems(),
    QUrlQuery::addQueryItem() and QUrlQuery::removeQueryItem(). Use
    QUrlQuery::setQueryDelimiters() to customize the delimiters used for
    generating the query string.

    For the convenience of generating encoded URL strings or query
    strings, there are two static functions called
    fromPercentEncoding() and toPercentEncoding() which deal with
    percent encoding and decoding of QStrings.

    Calling isRelative() will tell whether or not the URL is
    relative. A relative URL can be resolved by passing it as argument
    to resolved(), which returns an absolute URL. isParentOf() is used
    for determining whether one URL is a parent of another.

    fromLocalFile() constructs a QUrl by parsing a local
    file path. toLocalFile() converts a URL to a local file path.

    The human readable representation of the URL is fetched with
    toString(). This representation is appropriate for displaying a
    URL to a user in unencoded form. The encoded form however, as
    returned by toEncoded(), is for internal use, passing to web
    servers, mail clients and so on.

    QUrl conforms to the URI specification from
    \l{RFC 3986} (Uniform Resource Identifier: Generic Syntax), and includes
    scheme extensions from \l{RFC 1738} (Uniform Resource Locators). Case
    folding rules in QUrl conform to \l{RFC 3491} (Nameprep: A Stringprep
    Profile for Internationalized Domain Names (IDN)).

    \section2 Error checking

    QUrl is capable of detecting many errors in URLs while parsing it or when
    components of the URL are set with individual setter methods (like
    setScheme(), setHost() or setPath()). If the parsing or setter function is
    successful, any previously recorded error conditions will be discarded.

    By default, QUrl setter methods operate in QUrl::TolerantMode, which means
    they accept some common mistakes and mis-representation of data. An
    alternate method of parsing is QUrl::StrictMode, which applies further
    checks. See QUrl::ParsingMode for a description of the difference of the
    parsing modes.

    QUrl only checks for conformance with the URL specification. It does not
    try to verify that high-level protocol URLs are in the format they are
    expected to be by handlers elsewhere. For example, the following URIs are
    all considered valid by QUrl, even if they do not make sense when used:

    \list
      \li "http:/filename.html"
      \li "mailto://example.com"
    \endlist

    When the parser encounters an error, it signals the event by making
    isValid() return false and toString() / toEncoded() return an empty string.
    If it is necessary to show the user the reason why the URL failed to parse,
    the error condition can be obtained from QUrl by calling errorString().
    Note that this message is highly technical and may not make sense to
    end-users.

    QUrl is capable of recording only one error condition. If more than one
    error is found, it is undefined which error is reported.

    \section2 Character Conversions

    Follow these rules to avoid erroneous character conversion when
    dealing with URLs and strings:

    \list
    \li When creating an QString to contain a URL from a QByteArray or a
       char*, always use QString::fromUtf8().
    \endlist
*/

/*!
    \enum QUrl::ParsingMode

    The parsing mode controls the way QUrl parses strings.

    \value TolerantMode QUrl will try to correct some common errors in URLs.
                        This mode is useful for parsing URLs coming from sources
                        not known to be strictly standards-conforming.

    \value StrictMode Only valid URLs are accepted. This mode is useful for
                      general URL validation.

    \value DecodedMode QUrl will interpret the URL component in the fully-decoded form,
                       where percent characters stand for themselves, not as the beginning
                       of a percent-encoded sequence. This mode is only valid for the
                       setters setting components of a URL; it is not permitted in
                       the QUrl constructor, in fromEncoded() or in setUrl().

    In TolerantMode, the parser has the following behaviour:

    \list

    \li Spaces and "%20": unencoded space characters will be accepted and will
    be treated as equivalent to "%20".

    \li Single "%" characters: Any occurrences of a percent character "%" not
    followed by exactly two hexadecimal characters (e.g., "13% coverage.html")
    will be replaced by "%25". Note that one lone "%" character will trigger
    the correction mode for all percent characters.

    \li Reserved and unreserved characters: An encoded URL should only
    contain a few characters as literals; all other characters should
    be percent-encoded. In TolerantMode, these characters will be
    automatically percent-encoded where they are not allowed:
            space / double-quote / "<" / ">" / "\" /
            "^" / "`" / "{" / "|" / "}"
    Those same characters can be decoded again by passing QUrl::DecodeReserved
    to toString() or toEncoded().

    \endlist

    When in StrictMode, if a parsing error is found, isValid() will return \c
    false and errorString() will return a message describing the error.
    If more than one error is detected, it is undefined which error gets
    reported.

    Note that TolerantMode is not usually enough for parsing user input, which
    often contains more errors and expectations than the parser can deal with.
    When dealing with data coming directly from the user -- as opposed to data
    coming from data-transfer sources, such as other programs -- it is
    recommended to use fromUserInput().

    \sa fromUserInput(), setUrl(), toString(), toEncoded(), QUrl::FormattingOptions
*/

/*!
    \enum QUrl::UrlFormattingOption

    The formatting options define how the URL is formatted when written out
    as text.

    \value None The format of the URL is unchanged.
    \value RemoveScheme  The scheme is removed from the URL.
    \value RemovePassword  Any password in the URL is removed.
    \value RemoveUserInfo  Any user information in the URL is removed.
    \value RemovePort      Any specified port is removed from the URL.
    \value RemoveAuthority
    \value RemovePath   The URL's path is removed, leaving only the scheme,
                        host address, and port (if present).
    \value RemoveQuery  The query part of the URL (following a '?' character)
                        is removed.
    \value RemoveFragment
    \value PreferLocalFile If the URL is a local file according to isLocalFile()
     and contains no query or fragment, a local file path is returned.
    \value StripTrailingSlash  The trailing slash is removed if one is present.

    Note that the case folding rules in \l{RFC 3491}{Nameprep}, which QUrl
    conforms to, require host names to always be converted to lower case,
    regardless of the Qt::FormattingOptions used.

    The options from QUrl::ComponentFormattingOptions are also possible.

    \sa QUrl::ComponentFormattingOptions
*/

/*!
    \enum QUrl::ComponentFormattingOption
    \since 5.0

    The component formatting options define how the components of an URL will
    be formatted when written out as text. They can be combined with the
    options from QUrl::FormattingOptions when used in toString() and
    toEncoded().

    \value PrettyDecoded   The component is returned in a "pretty form", with
                           most percent-encoded characters decoded. The exact
                           behavior of PrettyDecoded varies from component to
                           component and may also change from Qt release to Qt
                           release. This is the default.

    \value EncodeSpaces    Leave space characters in their encoded form ("%20").

    \value EncodeUnicode   Leave non-US-ASCII characters encoded in their UTF-8
                           percent-encoded form (e.g., "%C3%A9" for the U+00E9
                           codepoint, LATIN SMALL LETTER E WITH ACUTE).

    \value EncodeDelimiters Leave certain delimiters in their encoded form, as
                            would appear in the URL when the full URL is
                            represented as text. The delimiters are affected
                            by this option change from component to component.

    \value EncodeReserved  Leave the US-ASCII reserved characters in their encoded
                           forms.

    \value DecodeReserved   Decode the US-ASCII reserved characters.

    \value FullyEncoded    Leave all characters in their properly-encoded form,
                           as this component would appear as part of a URL. When
                           used with toString(), this produces a fully-compliant
                           URL in QString form, exactly equal to the result of
                           toEncoded()

    \value FullyDecoded    Attempt to decode as much as possible. For individual
                           components of the URL, this decodes every percent
                           encoding sequence, including control characters (U+0000
                           to U+001F) and UTF-8 sequences found in percent-encoded form.
                           Note: if the component contains non-US-ASCII sequences
                           that aren't valid UTF-8 sequences, the behaviour is
                           undefined since QString cannot represent those values
                           (data will be lost!)
                           This mode is should not be used in functions where more
                           than one URL component is returned (userInfo() and authority())
                           and it is not allowed in url() and toString().

    The values of EncodeReserved and DecodeReserved should not be used together
    in one call. The behaviour is undefined if that happens. They are provided
    as separate values because the behaviour of the "pretty mode" with regards
    to reserved characters is different on certain components and specially on
    the full URL.

    The FullyDecoded mode is similar to the behaviour of the functions
    returning QString in Qt 4.x, including the fact that they will most likely
    cause data loss if the component in question contains a non-UTF-8
    percent-encoded sequence. Fortunately, those cases aren't common, so this
    mode should be used when the component in question is used in a non-URL
    context. For example, in an FTP client application, the path to the remote
    file could be stored in a QUrl object, and the string to be transmitted to
    the FTP server should be obtained using this flag.

    \sa QUrl::FormattingOptions
*/

#include "qurl.h"
#include "qurl_p.h"
#include "qplatformdefs.h"
#include "qstring.h"
#include "qstringlist.h"
#include "qdebug.h"
#include "qhash.h"
#include "qdir.h"         // for QDir::fromNativeSeparators
#include "qtldurl_p.h"
#include "private/qipaddress_p.h"
#include "qurlquery.h"
#if defined(Q_OS_WINCE_WM)
#pragma optimize("g", off)
#endif

QT_BEGIN_NAMESPACE

inline static bool isHex(char c)
{
    c |= 0x20;
    return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
}

static inline QString ftpScheme()
{
    return QStringLiteral("ftp");
}

static inline QString httpScheme()
{
    return QStringLiteral("http");
}

static inline QString fileScheme()
{
    return QStringLiteral("file");
}

class QUrlPrivate
{
public:
    enum Section {
        Scheme = 0x01,
        UserName = 0x02,
        Password = 0x04,
        UserInfo = UserName | Password,
        Host = 0x08,
        Port = 0x10,
        Authority = UserInfo | Host | Port,
        Path = 0x20,
        Hierarchy = Authority | Path,
        Query = 0x40,
        Fragment = 0x80,
        FullUrl = 0xff
    };

    enum ErrorCode {
        // the high byte of the error code matches the Section
        // the first item in each value must be the generic "Invalid xxx Error"
        InvalidSchemeError = Scheme << 8,

        InvalidUserNameError = UserName << 8,

        InvalidPasswordError = Password << 8,

        InvalidRegNameError = Host << 8,
        InvalidIPv4AddressError,
        InvalidIPv6AddressError,
        InvalidIPvFutureError,
        HostMissingEndBracket,

        InvalidPortError = Port << 8,
        PortEmptyError,

        InvalidPathError = Path << 8,

        InvalidQueryError = Query << 8,

        InvalidFragmentError = Fragment << 8,

        // the following two cases are only possible in combination
        // with presence/absence of the authority and scheme. See validityError().
        AuthorityPresentAndPathIsRelative = Authority << 8 | Path << 8 | 0x10000,
        RelativeUrlPathContainsColonBeforeSlash = Scheme << 8 | Authority << 8 | Path << 8 | 0x10000,

        NoError = 0
    };

    struct Error {
        QString source;
        ErrorCode code;
        int position;
    };

    QUrlPrivate();
    QUrlPrivate(const QUrlPrivate &copy);
    ~QUrlPrivate();

    void parse(const QString &url, QUrl::ParsingMode parsingMode);
    bool isEmpty() const
    { return sectionIsPresent == 0 && port == -1 && path.isEmpty(); }

    Error *cloneError() const;
    void clearError();
    void setError(ErrorCode errorCode, const QString &source, int supplement = -1);
    ErrorCode validityError(QString *source = 0, int *position = 0) const;
    bool validateComponent(Section section, const QString &input, int begin, int end);
    bool validateComponent(Section section, const QString &input)
    { return validateComponent(section, input, 0, uint(input.length())); }

    // no QString scheme() const;
    void appendAuthority(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const;
    void appendUserInfo(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const;
    void appendUserName(QString &appendTo, QUrl::FormattingOptions options) const;
    void appendPassword(QString &appendTo, QUrl::FormattingOptions options) const;
    void appendHost(QString &appendTo, QUrl::FormattingOptions options) const;
    void appendPath(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const;
    void appendQuery(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const;
    void appendFragment(QString &appendTo, QUrl::FormattingOptions options) const;

    // the "end" parameters are like STL iterators: they point to one past the last valid element
    bool setScheme(const QString &value, int len, bool doSetError);
    void setAuthority(const QString &auth, int from, int end, QUrl::ParsingMode mode);
    void setUserInfo(const QString &userInfo, int from, int end);
    void setUserName(const QString &value, int from, int end);
    void setPassword(const QString &value, int from, int end);
    bool setHost(const QString &value, int from, int end, QUrl::ParsingMode mode);
    void setPath(const QString &value, int from, int end);
    void setQuery(const QString &value, int from, int end);
    void setFragment(const QString &value, int from, int end);

    inline bool hasScheme() const { return sectionIsPresent & Scheme; }
    inline bool hasAuthority() const { return sectionIsPresent & Authority; }
    inline bool hasUserInfo() const { return sectionIsPresent & UserInfo; }
    inline bool hasUserName() const { return sectionIsPresent & UserName; }
    inline bool hasPassword() const { return sectionIsPresent & Password; }
    inline bool hasHost() const { return sectionIsPresent & Host; }
    inline bool hasPort() const { return port != -1; }
    inline bool hasPath() const { return !path.isEmpty(); }
    inline bool hasQuery() const { return sectionIsPresent & Query; }
    inline bool hasFragment() const { return sectionIsPresent & Fragment; }

    QString mergePaths(const QString &relativePath) const;

    QAtomicInt ref;
    int port;

    QString scheme;
    QString userName;
    QString password;
    QString host;
    QString path;
    QString query;
    QString fragment;

    Error *error;

    // not used for:
    //  - Port (port == -1 means absence)
    //  - Path (there's no path delimiter, so we optimize its use out of existence)
    // Schemes are never supposed to be empty, but we keep the flag anyway
    uchar sectionIsPresent;
};

inline QUrlPrivate::QUrlPrivate()
    : ref(1), port(-1),
      error(0),
      sectionIsPresent(0)
{
}

inline QUrlPrivate::QUrlPrivate(const QUrlPrivate &copy)
    : ref(1), port(copy.port),
      scheme(copy.scheme),
      userName(copy.userName),
      password(copy.password),
      host(copy.host),
      path(copy.path),
      query(copy.query),
      fragment(copy.fragment),
      error(copy.cloneError()),
      sectionIsPresent(copy.sectionIsPresent)
{
}

inline QUrlPrivate::~QUrlPrivate()
{
    delete error;
}

inline QUrlPrivate::Error *QUrlPrivate::cloneError() const
{
    return error ? new Error(*error) : 0;
}

inline void QUrlPrivate::clearError()
{
    delete error;
    error = 0;
}

inline void QUrlPrivate::setError(ErrorCode errorCode, const QString &source, int supplement)
{
    if (error) {
        // don't overwrite an error set in a previous section during parsing
        return;
    }
    error = new Error;
    error->code = errorCode;
    error->source = source;
    error->position = supplement;
}

// From RFC 3896, Appendix A Collected ABNF for URI
//    URI           = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
//[...]
//    scheme        = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
//
//    authority     = [ userinfo "@" ] host [ ":" port ]
//    userinfo      = *( unreserved / pct-encoded / sub-delims / ":" )
//    host          = IP-literal / IPv4address / reg-name
//    port          = *DIGIT
//[...]
//    reg-name      = *( unreserved / pct-encoded / sub-delims )
//[..]
//    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
//
//    query         = *( pchar / "/" / "?" )
//
//    fragment      = *( pchar / "/" / "?" )
//
//    pct-encoded   = "%" HEXDIG HEXDIG
//
//    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
//    reserved      = gen-delims / sub-delims
//    gen-delims    = ":" / "/" / "?" / "#" / "[" / "]" / "@"
//    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
//                  / "*" / "+" / "," / ";" / "="
// the path component has a complex ABNF that basically boils down to
// slash-separated segments of "pchar"

// The above is the strict definition of the URL components and it is what we
// return encoded as FullyEncoded. However, we store the equivalent to
// PrettyDecoded internally, as that is the default formatting mode and most
// likely to be used. PrettyDecoded decodes spaces, unicode sequences and
// unambiguous delimiters.
//
// An ambiguous delimiter is a delimiter that, if appeared decoded, would be
// interpreted as the beginning of a new component. The exact delimiters that
// match that definition change according to the use. When each field is
// considered in isolation from the rest, there are no ambiguities. In other
// words, we always store the most decoded form (except for the query, see
// below).
//
// The ambiguities arise when components are put together. From last to first
// component of a full URL, the ambiguities are:
//  - fragment: none, since it's the last.
//  - query: the "#" character is ambiguous, as it starts the fragment. In
//    addition, the "+" character is treated specially, as should be both
//    intra-query delimiters. Since we don't know which ones they are, we
//    keep all reserved characters untouched.
//  - path: the "#" and "?" characters are ambigous. In addition to them,
//    the slash itself is considered special.
//  - host: completely special but never ambiguous, see setHost() below.
//  - password: the "#", "?", "/", "[", "]" and "@" characters are ambiguous
//  - username: the "#", "?", "/", "[", "]", "@", and ":" characters are ambiguous
//  - scheme: doesn't accept any delimiter, see setScheme() below.
//
// When the authority component is considered in isolation, the ambiguities of
// its components are:
//  - host: special, never ambiguous
//  - password: "[", "]", "@" are ambiguous
//  - username: "[", "]", "@", ":" are ambiguous
//
// Finally, when the userinfo is considered in isolation, the ambiguities of its
// components are:
//  - password: none, since it's the last
//  - username: ":" is ambiguous

// list the recoding table modifications to be used with the recodeFromUser and
// appendToUser functions, according to the rules above.
// the encodedXXX tables are run with the delimiters set to "leave" by default;
// the decodedXXX tables are run with the delimiters set to "decode" by default
// (except for the query, which doesn't use these functions)

#define decode(x) ushort(x)
#define leave(x)  ushort(0x100 | (x))
#define encode(x) ushort(0x200 | (x))

static const ushort encodedUserNameActions[] = {
    // first field, everything must be encoded, including the ":"
    //    userinfo      = *( unreserved / pct-encoded / sub-delims / ":" )
    encode('/'), // 0
    encode('?'), // 1
    encode('#'), // 2
    encode('['), // 3
    encode(']'), // 4
    encode('@'), // 5
    encode(':'), // 6
    0
};
static const ushort * const decodedUserNameInAuthorityActions = encodedUserNameActions + 3;
static const ushort * const decodedUserNameInUserInfoActions = encodedUserNameActions + 6;
static const ushort * const decodedUserNameInUrlActions = encodedUserNameActions;
static const ushort * const decodedUserNameInIsolationActions = 0;

static const ushort encodedPasswordActions[] = {
    // same as encodedUserNameActions, but decode ":"
    //    userinfo      = *( unreserved / pct-encoded / sub-delims / ":" )
    encode('/'), // 0
    encode('?'), // 1
    encode('#'), // 2
    encode('['), // 3
    encode(']'), // 4
    encode('@'), // 5
    0
};
static const ushort * const decodedPasswordInAuthorityActions = encodedPasswordActions + 3;
static const ushort * const decodedPasswordInUserInfoActions = 0;
static const ushort * const decodedPasswordInUrlActions = encodedPasswordActions;
static const ushort * const decodedPasswordInIsolationActions = 0;

static const ushort encodedPathActions[] = {
    //    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
    encode('['), // 0
    encode(']'), // 1
    encode('?'), // 2
    encode('#'), // 3
    leave('/'),  // 4
    0
};
static const ushort decodedPathInUrlActions[] = {
    decode('{'), // 0
    decode('}'), // 1
    encode('?'), // 2
    encode('#'), // 3
    leave('/'),  // 4
    0
};
static const ushort * const decodedPathInIsolationActions = encodedPathActions + 4; // leave('/')

static const ushort encodedFragmentActions[] = {
    //    fragment      = *( pchar / "/" / "?" )
    // gen-delims permitted: ":" / "@" / "/" / "?"
    //   ->   must encode: "[" / "]" / "#"
    // HOWEVER: we allow "#" to remain decoded
    decode('#'), // 0
    decode(':'), // 1
    decode('@'), // 2
    decode('/'), // 3
    decode('?'), // 4
    encode('['), // 5
    encode(']'), // 6
    0
};
static const ushort * const decodedFragmentInUrlActions = 0;
static const ushort * const decodedFragmentInIsolationActions = 0;

// the query is handled specially: the decodedQueryXXX tables are run with
// the delimiters set to "leave" by default and the others set to "encode"
static const ushort encodedQueryActions[] = {
    //    query         = *( pchar / "/" / "?" )
    // gen-delims permitted: ":" / "@" / "/" / "?"
    // HOWEVER: we leave alone them alone, plus "[" and "]"
    //   ->   must encode: "#"
    encode('#'), // 0
    0
};
static const ushort decodedQueryInIsolationActions[] = {
    decode('"'), // 0
    decode('<'), // 1
    decode('>'), // 2
    decode('^'), // 3
    decode('\\'),// 4
    decode('|'), // 5
    decode('{'), // 6
    decode('}'), // 7
    decode('#'), // 8
    0
};
static const ushort decodedQueryInUrlActions[] = {
    decode('{'), // 6
    decode('}'), // 7
    encode('#'), // 8
    0
};

static inline void parseDecodedComponent(QString &data)
{
    data.replace(QLatin1Char('%'), QStringLiteral("%25"));
}

static inline QString
recodeFromUser(const QString &input, const ushort *actions, int from, int to)
{
    QString output;
    const QChar *begin = input.constData() + from;
    const QChar *end = input.constData() + to;
    if (qt_urlRecode(output, begin, end,
                     QUrl::DecodeReserved, actions))
        return output;

    return input.mid(from, to - from);
}

// appendXXXX functions:
// the internal value is stored in its most decoded form, so that case is easy.
// DecodeUnicode and DecodeSpaces are handled by qt_urlRecode.
// That leaves these functions to handle two cases related to delimiters:
//  1) encoded                           encodedXXXX tables
//  2) decoded                           decodedXXXX tables
static inline void appendToUser(QString &appendTo, const QString &value, QUrl::FormattingOptions options,
                                const ushort *encodedActions, const ushort *decodedActions)
{
    if (options == QUrl::PrettyDecoded) {
        appendTo += value;
        return;
    }

    const ushort *actions = 0;
    if (options & QUrl::EncodeDelimiters)
        actions = encodedActions;
    else
        actions = decodedActions;

    if (!qt_urlRecode(appendTo, value.constData(), value.constEnd(), options, actions))
        appendTo += value;
}

inline void QUrlPrivate::appendAuthority(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const
{
    if ((options & QUrl::RemoveUserInfo) != QUrl::RemoveUserInfo) {
        appendUserInfo(appendTo, options, appendingTo);

        // add '@' only if we added anything
        if (hasUserName() || (hasPassword() && (options & QUrl::RemovePassword) == 0))
            appendTo += QLatin1Char('@');
    }
    appendHost(appendTo, options);
    if (!(options & QUrl::RemovePort) && port != -1)
        appendTo += QLatin1Char(':') + QString::number(port);
}

inline void QUrlPrivate::appendUserInfo(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const
{
    if (Q_LIKELY(!hasUserInfo()))
        return;

    const ushort *userNameActions;
    const ushort *passwordActions;
    if (options & QUrl::EncodeDelimiters) {
        userNameActions = encodedUserNameActions;
        passwordActions = encodedPasswordActions;
    } else {
        switch (appendingTo) {
        case UserInfo:
            userNameActions = decodedUserNameInUserInfoActions;
            passwordActions = decodedPasswordInUserInfoActions;
            break;

        case Authority:
            userNameActions = decodedUserNameInAuthorityActions;
            passwordActions = decodedPasswordInAuthorityActions;
            break;

        case FullUrl:
        default:
            userNameActions = decodedUserNameInUrlActions;
            passwordActions = decodedPasswordInUrlActions;
            break;
        }
    }

    if ((options & QUrl::EncodeReserved) == 0)
        options |= QUrl::DecodeReserved;

    if (!qt_urlRecode(appendTo, userName.constData(), userName.constEnd(), options, userNameActions))
        appendTo += userName;
    if (options & QUrl::RemovePassword || !hasPassword()) {
        return;
    } else {
        appendTo += QLatin1Char(':');
        if (!qt_urlRecode(appendTo, password.constData(), password.constEnd(), options, passwordActions))
            appendTo += password;
    }
}

inline void QUrlPrivate::appendUserName(QString &appendTo, QUrl::FormattingOptions options) const
{
    appendToUser(appendTo, userName, options, encodedUserNameActions, decodedUserNameInIsolationActions);
}

inline void QUrlPrivate::appendPassword(QString &appendTo, QUrl::FormattingOptions options) const
{
    appendToUser(appendTo, password, options, encodedPasswordActions, decodedPasswordInIsolationActions);
}

inline void QUrlPrivate::appendPath(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const
{
    if (appendingTo != Path && !(options & QUrl::EncodeDelimiters)) {
        if (!qt_urlRecode(appendTo, path.constData(), path.constEnd(), options, decodedPathInUrlActions))
            appendTo += path;

    } else {
        appendToUser(appendTo, path, options, encodedPathActions, decodedPathInIsolationActions);
    }
}

inline void QUrlPrivate::appendFragment(QString &appendTo, QUrl::FormattingOptions options) const
{
    appendToUser(appendTo, fragment, options, encodedFragmentActions, decodedFragmentInIsolationActions);
}

inline void QUrlPrivate::appendQuery(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const
{
    // almost the same code as the previous functions
    // except we prefer not to touch the delimiters
    if (options == QUrl::PrettyDecoded && appendingTo == Query) {
        appendTo += query;
        return;
    }

    const ushort *actions = 0;
    if (options & QUrl::EncodeDelimiters) {
        actions = encodedQueryActions;
    } else {
        // reset to default qt_urlRecode behaviour (leave delimiters alone)
        options |= QUrl::EncodeDelimiters;
        actions = appendingTo == Query ? decodedQueryInIsolationActions : decodedQueryInUrlActions;
    }

    if (!qt_urlRecode(appendTo, query.constData(), query.constData() + query.length(),
                      options, actions))
        appendTo += query;
}

// setXXX functions

inline bool QUrlPrivate::setScheme(const QString &value, int len, bool doSetError)
{
    // schemes are strictly RFC-compliant:
    //    scheme        = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
    // we also lowercase the scheme

    // schemes in URLs are not allowed to be empty, but they can be in
    // "Relative URIs" which QUrl also supports. QUrl::setScheme does
    // not call us with len == 0, so this can only be from parse()
    scheme.clear();
    if (len == 0)
        return false;

    sectionIsPresent |= Scheme;

    // validate it:
    int needsLowercasing = -1;
    const ushort *p = reinterpret_cast<const ushort *>(value.constData());
    for (int i = 0; i < len; ++i) {
        if (p[i] >= 'a' && p[i] <= 'z')
            continue;
        if (p[i] >= 'A' && p[i] <= 'Z') {
            needsLowercasing = i;
            continue;
        }
        if (p[i] >= '0' && p[i] <= '9' && i > 0)
            continue;
        if (p[i] == '+' || p[i] == '-' || p[i] == '.')
            continue;

        // found something else
        // don't call setError needlessly:
        // if we've been called from parse(), it will try to recover
        if (doSetError)
            setError(InvalidSchemeError, value, i);
        return false;
    }

    scheme = value.left(len);

    if (needsLowercasing != -1) {
        // schemes are ASCII only, so we don't need the full Unicode toLower
        QChar *schemeData = scheme.data(); // force detaching here
        for (int i = needsLowercasing; i >= 0; --i) {
            register ushort c = schemeData[i].unicode();
            if (c >= 'A' && c <= 'Z')
                schemeData[i] = c + 0x20;
        }
    }
    return true;
}

inline void QUrlPrivate::setAuthority(const QString &auth, int from, int end, QUrl::ParsingMode mode)
{
    sectionIsPresent &= ~Authority;
    sectionIsPresent |= Host;

    // we never actually _loop_
    while (from != end) {
        int userInfoIndex = auth.indexOf(QLatin1Char('@'), from);
        if (uint(userInfoIndex) < uint(end)) {
            setUserInfo(auth, from, userInfoIndex);
            if (mode == QUrl::StrictMode && !validateComponent(UserInfo, auth, from, userInfoIndex))
                break;
            from = userInfoIndex + 1;
        }

        int colonIndex = auth.lastIndexOf(QLatin1Char(':'), end - 1);
        if (colonIndex < from)
            colonIndex = -1;

        if (uint(colonIndex) < uint(end)) {
            if (auth.at(from).unicode() == '[') {
                // check if colonIndex isn't inside the "[...]" part
                int closingBracket = auth.indexOf(QLatin1Char(']'), from);
                if (uint(closingBracket) > uint(colonIndex))
                    colonIndex = -1;
            }
        }

        if (colonIndex == end - 1) {
            // found a colon but no digits after it
            setError(PortEmptyError, auth, colonIndex + 1);
        } else if (uint(colonIndex) < uint(end)) {
            unsigned long x = 0;
            for (int i = colonIndex + 1; i < end; ++i) {
                ushort c = auth.at(i).unicode();
                if (c >= '0' && c <= '9') {
                    x *= 10;
                    x += c - '0';
                } else {
                    x = ulong(-1); // x != ushort(x)
                    break;
                }
            }
            if (x == ushort(x)) {
                port = ushort(x);
            } else {
                setError(InvalidPortError, auth, colonIndex + 1);
                if (mode == QUrl::StrictMode)
                    break;
            }
        } else {
            port = -1;
        }

        setHost(auth, from, qMin<uint>(end, colonIndex), mode);
        if (mode == QUrl::StrictMode && !validateComponent(Host, auth, from, qMin<uint>(end, colonIndex))) {
            // clear host too
            sectionIsPresent &= ~Authority;
            break;
        }

        // success
        return;
    }
    // clear all sections but host
    sectionIsPresent &= ~Authority | Host;
    userName.clear();
    password.clear();
    host.clear();
    port = -1;
}

inline void QUrlPrivate::setUserInfo(const QString &userInfo, int from, int end)
{
    int delimIndex = userInfo.indexOf(QLatin1Char(':'), from);
    setUserName(userInfo, from, qMin<uint>(delimIndex, end));

    if (uint(delimIndex) >= uint(end)) {
        password.clear();
        sectionIsPresent &= ~Password;
    } else {
        setPassword(userInfo, delimIndex + 1, end);
    }
}

inline void QUrlPrivate::setUserName(const QString &value, int from, int end)
{
    sectionIsPresent |= UserName;
    userName = recodeFromUser(value, decodedUserNameInIsolationActions, from, end);
}

inline void QUrlPrivate::setPassword(const QString &value, int from, int end)
{
    sectionIsPresent |= Password;
    password = recodeFromUser(value, decodedPasswordInIsolationActions, from, end);
}

inline void QUrlPrivate::setPath(const QString &value, int from, int end)
{
    // sectionIsPresent |= Path; // not used, save some cycles
    path = recodeFromUser(value, decodedPathInIsolationActions, from, end);
}

inline void QUrlPrivate::setFragment(const QString &value, int from, int end)
{
    sectionIsPresent |= Fragment;
    fragment = recodeFromUser(value, decodedFragmentInIsolationActions, from, end);
}

inline void QUrlPrivate::setQuery(const QString &value, int from, int iend)
{
    sectionIsPresent |= Query;

    // use the default actions for the query (don't set QUrl::DecodeAllDelimiters)
    QString output;
    const QChar *begin = value.constData() + from;
    const QChar *end = value.constData() + iend;

    // leave delimiters alone but decode the rest
    if (qt_urlRecode(output, begin, end, QUrl::EncodeDelimiters,
                     decodedQueryInIsolationActions))
        query = output;
    else
        query = value.mid(from, iend - from);
}

// Host handling
// The RFC says the host is:
//    host          = IP-literal / IPv4address / reg-name
//    IP-literal    = "[" ( IPv6address / IPvFuture  ) "]"
//    IPvFuture     = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
//  [a strict definition of IPv6Address and IPv4Address]
//     reg-name      = *( unreserved / pct-encoded / sub-delims )
//
// We deviate from the standard in all but IPvFuture. For IPvFuture we accept
// and store only exactly what the RFC says we should. No percent-encoding is
// permitted in this field, so Unicode characters and space aren't either.
//
// For IPv4 addresses, we accept broken addresses like inet_aton does (that is,
// less than three dots). However, we correct the address to the proper form
// and store the corrected address. After correction, we comply to the RFC and
// it's exclusively composed of unreserved characters.
//
// For IPv6 addresses, we accept addresses including trailing (embedded) IPv4
// addresses, the so-called v4-compat and v4-mapped addresses. We also store
// those addresses like that in the hostname field, which violates the spec.
// IPv6 hosts are stored with the square brackets in the QString. It also
// requires no transformation in any way.
//
// As for registered names, it's the other way around: we accept only valid
// hostnames as specified by STD 3 and IDNA. That means everything we accept is
// valid in the RFC definition above, but there are many valid reg-names
// according to the RFC that we do not accept in the name of security. Since we
// do accept IDNA, reg-names are subject to ACE encoding and decoding, which is
// specified by the DecodeUnicode flag. The hostname is stored in its Unicode form.

inline void QUrlPrivate::appendHost(QString &appendTo, QUrl::FormattingOptions options) const
{
    // this is the only flag that matters
    options &= QUrl::EncodeUnicode;
    if (host.isEmpty())
        return;
    if (host.at(0).unicode() == '[') {
        // IPv6Address and IPvFuture address never require any transformation
        appendTo += host;
    } else {
        // this is either an IPv4Address or a reg-name
        // if it is a reg-name, it is already stored in Unicode form
        if (options == QUrl::EncodeUnicode)
            appendTo += qt_ACE_do(host, ToAceOnly);
        else
            appendTo += host;
    }
}

// the whole IPvFuture is passed and parsed here, including brackets;
// returns null if the parsing was successful, or the QChar of the first failure
static const QChar *parseIpFuture(QString &host, const QChar *begin, const QChar *end)
{
    //    IPvFuture     = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
    static const char acceptable[] =
            "!$&'()*+,;=" // sub-delims
            ":"           // ":"
            "-._~";       // unreserved

    // the brackets and the "v" have been checked
    if (begin[3].unicode() != '.')
        return &begin[3];
    if ((begin[2].unicode() >= 'A' && begin[2].unicode() >= 'F') ||
            (begin[2].unicode() >= 'a' && begin[2].unicode() <= 'f') ||
            (begin[2].unicode() >= '0' && begin[2].unicode() <= '9')) {
        // this is so unlikely that we'll just go down the slow path
        // decode the whole string, skipping the "[vH." and "]" which we already know to be there
        host += QString::fromRawData(begin, 4);
        begin += 4;
        --end;

        QString decoded;
        if (qt_urlRecode(decoded, begin, end, QUrl::FullyEncoded, 0)) {
            begin = decoded.constBegin();
            end = decoded.constEnd();
        }

        for ( ; begin != end; ++begin) {
            if (begin->unicode() >= 'A' && begin->unicode() <= 'Z')
                host += *begin;
            else if (begin->unicode() >= 'a' && begin->unicode() <= 'z')
                host += *begin;
            else if (begin->unicode() >= '0' && begin->unicode() <= '9')
                host += *begin;
            else if (begin->unicode() < 0x80 && strchr(acceptable, begin->unicode()) != 0)
                host += *begin;
            else
                return begin;
        }
        host += QLatin1Char(']');
        return 0;
    }
    return &begin[2];
}

// ONLY the IPv6 address is parsed here, WITHOUT the brackets
static bool parseIp6(QString &host, const QChar *begin, const QChar *end)
{
    QIPAddressUtils::IPv6Address address;
    if (!QIPAddressUtils::parseIp6(address, begin, end)) {
        // IPv6 failed parsing, check if it was a percent-encoded character in
        // the middle and try again
        QString decoded;
        if (!qt_urlRecode(decoded, begin, end, QUrl::FullyEncoded, 0)) {
            // no transformation, nothing to re-parse
            return false;
        }

        // recurse
        // if the parsing fails again, the qt_urlRecode above will return 0
        return parseIp6(host, decoded.constBegin(), decoded.constEnd());
    }

    host.reserve(host.size() + (end - begin));
    host += QLatin1Char('[');
    QIPAddressUtils::toString(host, address);
    host += QLatin1Char(']');
    return true;
}

inline bool QUrlPrivate::setHost(const QString &value, int from, int iend, QUrl::ParsingMode mode)
{
    const QChar *begin = value.constData() + from;
    const QChar *end = value.constData() + iend;

    const int len = end - begin;
    host.clear();
    sectionIsPresent |= Host;
    if (len == 0)
        return true;

    if (begin[0].unicode() == '[') {
        // IPv6Address or IPvFuture
        // smallest IPv6 address is      "[::]"   (len = 4)
        // smallest IPvFuture address is "[v7.X]" (len = 6)
        if (end[-1].unicode() != ']') {
            setError(HostMissingEndBracket, value);
            return false;
        }

        if (len > 5 && begin[1].unicode() == 'v') {
            const QChar *c = parseIpFuture(host, begin, end);
            if (c)
                setError(InvalidIPvFutureError, value, c - value.constData());
            return !c;
        }

        if (parseIp6(host, begin + 1, end - 1))
            return true;

        setError(begin[1].unicode() == 'v' ? InvalidIPvFutureError : InvalidIPv6AddressError,
                 value, from);
        return false;
    }

    // check if it's an IPv4 address
    QIPAddressUtils::IPv4Address ip4;
    if (QIPAddressUtils::parseIp4(ip4, begin, end)) {
        // yes, it was
        QIPAddressUtils::toString(host, ip4);
        return true;
    }

    // This is probably a reg-name.
    // But it can also be an encoded string that, when decoded becomes one
    // of the types above.
    //
    // Two types of encoding are possible:
    //  percent encoding (e.g., "%31%30%2E%30%2E%30%2E%31" -> "10.0.0.1")
    //  Unicode encoding (some non-ASCII characters case-fold to digits
    //                    when nameprepping is done)
    //
    // The qt_ACE_do function below applies nameprepping and the STD3 check.
    // That means a Unicode string may become an IPv4 address, but it cannot
    // produce a '[' or a '%'.

    // check for percent-encoding first
    QString s;
    if (mode == QUrl::TolerantMode && qt_urlRecode(s, begin, end, QUrl::DecodeReserved, 0)) {
        // something was decoded
        // anything encoded left?
        int pos = s.indexOf(QChar(0x25)); // '%'
        if (pos != -1) {
            setError(InvalidRegNameError, s, pos);
            return false;
        }

        // recurse
        return setHost(s, 0, s.length(), QUrl::StrictMode);
    }

    s = qt_ACE_do(QString::fromRawData(begin, len), NormalizeAce);
    if (s.isEmpty()) {
        setError(InvalidRegNameError, value);
        return false;
    }

    // check IPv4 again
    if (QIPAddressUtils::parseIp4(ip4, s.constBegin(), s.constEnd())) {
        QIPAddressUtils::toString(host, ip4);
    } else {
        host = s;
    }
    return true;
}

inline void QUrlPrivate::parse(const QString &url, QUrl::ParsingMode parsingMode)
{
    //   URI-reference = URI / relative-ref
    //   URI           = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
    //   relative-ref  = relative-part [ "?" query ] [ "#" fragment ]
    //   hier-part     = "//" authority path-abempty
    //                 / other path types
    //   relative-part = "//" authority path-abempty
    //                 /  other path types here

    sectionIsPresent = 0;
    clearError();

    // find the important delimiters
    int colon = -1;
    int question = -1;
    int hash = -1;
    const int len = url.length();
    const QChar *const begin = url.constData();
    const ushort *const data = reinterpret_cast<const ushort *>(begin);

    for (int i = 0; i < len; ++i) {
        register uint uc = data[i];
        if (uc == '#' && hash == -1) {
            hash = i;

            // nothing more to be found
            break;
        }

        if (question == -1) {
            if (uc == ':' && colon == -1)
                colon = i;
            else if (uc == '?')
                question = i;
        }
    }

    // check if we have a scheme
    int hierStart;
    if (colon != -1 && setScheme(url, colon, /* don't set error */ false)) {
        hierStart = colon + 1;
    } else {
        // recover from a failed scheme: it might not have been a scheme at all
        scheme.clear();
        sectionIsPresent = 0;
        hierStart = 0;
    }

    int pathStart;
    int hierEnd = qMin<uint>(qMin<uint>(question, hash), len);
    if (hierEnd - hierStart >= 2 && data[hierStart] == '/' && data[hierStart + 1] == '/') {
        // we have an authority, it ends at the first slash after these
        int authorityEnd = hierEnd;
        for (int i = hierStart + 2; i < authorityEnd ; ++i) {
            if (data[i] == '/') {
                authorityEnd = i;
                break;
            }
        }

        setAuthority(url, hierStart + 2, authorityEnd, parsingMode);

        // even if we failed to set the authority properly, let's try to recover
        pathStart = authorityEnd;
        setPath(url, pathStart, hierEnd);
    } else {
        userName.clear();
        password.clear();
        host.clear();
        port = -1;
        pathStart = hierStart;

        if (hierStart < hierEnd)
            setPath(url, hierStart, hierEnd);
        else
            path.clear();
    }

    if (uint(question) < uint(hash))
        setQuery(url, question + 1, qMin<uint>(hash, len));

    if (hash != -1)
        setFragment(url, hash + 1, len);

    if (error || parsingMode == QUrl::TolerantMode)
        return;

    // The parsing so far was partially tolerant of errors, except for the
    // scheme parser (which is always strict) and the authority (which was
    // executed in strict mode).
    // If we haven't found any errors so far, continue the strict-mode parsing
    // from the path component onwards.

    if (!validateComponent(Path, url, pathStart, hierEnd))
        return;
    if (uint(question) < uint(hash) && !validateComponent(Query, url, question + 1, qMin<uint>(hash, len)))
        return;
    if (hash != -1)
        validateComponent(Fragment, url, hash + 1, len);
}

/*
    From http://www.ietf.org/rfc/rfc3986.txt, 5.2.3: Merge paths

    Returns a merge of the current path with the relative path passed
    as argument.

    Note: \a relativePath is relative (does not start with '/').
*/
inline QString QUrlPrivate::mergePaths(const QString &relativePath) const
{
    // If the base URI has a defined authority component and an empty
    // path, then return a string consisting of "/" concatenated with
    // the reference's path; otherwise,
    if (!host.isEmpty() && path.isEmpty())
        return QLatin1Char('/') + relativePath;

    // Return a string consisting of the reference's path component
    // appended to all but the last segment of the base URI's path
    // (i.e., excluding any characters after the right-most "/" in the
    // base URI path, or excluding the entire base URI path if it does
    // not contain any "/" characters).
    QString newPath;
    if (!path.contains(QLatin1Char('/')))
        newPath = relativePath;
    else
        newPath = path.leftRef(path.lastIndexOf(QLatin1Char('/')) + 1) + relativePath;

    return newPath;
}

/*
    From http://www.ietf.org/rfc/rfc3986.txt, 5.2.4: Remove dot segments

    Removes unnecessary ../ and ./ from the path. Used for normalizing
    the URL.
*/
static void removeDotsFromPath(QString *path)
{
    // The input buffer is initialized with the now-appended path
    // components and the output buffer is initialized to the empty
    // string.
    QChar *out = path->data();
    const QChar *in = out;
    const QChar *end = out + path->size();

    // If the input buffer consists only of
    // "." or "..", then remove that from the input
    // buffer;
    if (path->size() == 1 && in[0].unicode() == '.')
        ++in;
    else if (path->size() == 2 && in[0].unicode() == '.' && in[1].unicode() == '.')
        in += 2;
    // While the input buffer is not empty, loop:
    while (in < end) {

        // otherwise, if the input buffer begins with a prefix of "../" or "./",
        // then remove that prefix from the input buffer;
        if (path->size() >= 2 && in[0].unicode() == '.' && in[1].unicode() == '/')
            in += 2;
        else if (path->size() >= 3 && in[0].unicode() == '.'
                 && in[1].unicode() == '.' && in[2].unicode() == '/')
            in += 3;

        // otherwise, if the input buffer begins with a prefix of
        // "/./" or "/.", where "." is a complete path segment,
        // then replace that prefix with "/" in the input buffer;
        if (in <= end - 3 && in[0].unicode() == '/' && in[1].unicode() == '.'
                && in[2].unicode() == '/') {
            in += 2;
            continue;
        } else if (in == end - 2 && in[0].unicode() == '/' && in[1].unicode() == '.') {
            *out++ = QLatin1Char('/');
            in += 2;
            break;
        }

        // otherwise, if the input buffer begins with a prefix
        // of "/../" or "/..", where ".." is a complete path
        // segment, then replace that prefix with "/" in the
        // input buffer and remove the last //segment and its
        // preceding "/" (if any) from the output buffer;
        if (in <= end - 4 && in[0].unicode() == '/' && in[1].unicode() == '.'
                && in[2].unicode() == '.' && in[3].unicode() == '/') {
            while (out > path->constData() && (--out)->unicode() != '/')
                ;
            if (out == path->constData() && out->unicode() != '/')
                ++in;
            in += 3;
            continue;
        } else if (in == end - 3 && in[0].unicode() == '/' && in[1].unicode() == '.'
                   && in[2].unicode() == '.') {
            while (out > path->constData() && (--out)->unicode() != '/')
                ;
            if (out->unicode() == '/')
                ++out;
            in += 3;
            break;
        }

        // otherwise move the first path segment in
        // the input buffer to the end of the output
        // buffer, including the initial "/" character
        // (if any) and any subsequent characters up
        // to, but not including, the next "/"
        // character or the end of the input buffer.
        *out++ = *in++;
        while (in < end && in->unicode() != '/')
            *out++ = *in++;
    }
    path->truncate(out - path->constData());
}

inline QUrlPrivate::ErrorCode QUrlPrivate::validityError(QString *source, int *position) const
{
    Q_ASSERT(!source == !position);
    if (error) {
        if (source) {
            *source = error->source;
            *position = error->position;
        }
        return error->code;
    }

    // There are two more cases of invalid URLs that QUrl recognizes and they
    // are only possible with constructed URLs (setXXX methods), not with
    // parsing. Therefore, they are tested here.
    //
    // The two cases are a non-empty path that doesn't start with a slash and:
    //  - with an authority
    //  - without an authority, without scheme but the path with a colon before
    //    the first slash
    // Those cases are considered invalid because toString() would produce a URL
    // that wouldn't be parsed back to the same QUrl.

    if (path.isEmpty() || path.at(0) == QLatin1Char('/'))
        return NoError;
    if (sectionIsPresent & QUrlPrivate::Host) {
        if (source) {
            *source = path;
            *position = 0;
        }
        return AuthorityPresentAndPathIsRelative;
    }
    if (sectionIsPresent & QUrlPrivate::Scheme)
        return NoError;

    // check for a path of "text:text/"
    for (int i = 0; i < path.length(); ++i) {
        register ushort c = path.at(i).unicode();
        if (c == '/') {
            // found the slash before the colon
            return NoError;
        }
        if (c == ':') {
            // found the colon before the slash, it's invalid
            if (source) {
                *source = path;
                *position = i;
            }
            return RelativeUrlPathContainsColonBeforeSlash;
        }
    }
    return NoError;
}

bool QUrlPrivate::validateComponent(QUrlPrivate::Section section, const QString &input,
                                    int begin, int end)
{
    // What we need to look out for, that the regular parser tolerates:
    //  - percent signs not followed by two hex digits
    //  - forbidden characters, which should always appear encoded
    //    '"' / '<' / '>' / '\' / '^' / '`' / '{' / '|' / '}' / BKSP
    //    control characters
    //  - delimiters not allowed in certain positions
    //    . scheme: parser is already strict
    //    . user info: gen-delims except ":" disallowed ("/" / "?" / "#" / "[" / "]" / "@")
    //    . host: parser is stricter than the standard
    //    . port: parser is stricter than the standard
    //    . path: all delimiters allowed
    //    . fragment: all delimiters allowed
    //    . query: all delimiters allowed
    static const char forbidden[] = "\"<>\\^`{|}\x7F";
    static const char forbiddenUserInfo[] = ":/?#[]@";

    Q_ASSERT(section != Authority && section != Hierarchy && section != FullUrl);

    const ushort *const data = reinterpret_cast<const ushort *>(input.constData());
    for (uint i = uint(begin); i < uint(end); ++i) {
        register uint uc = data[i];
        if (uc >= 0x80)
            continue;

        bool error = false;
        if ((uc == '%' && (uint(end) < i + 2 || !isHex(data[i + 1]) || !isHex(data[i + 2])))
                || uc <= 0x20 || strchr(forbidden, uc)) {
            // found an error
            error = true;
        } else if (section & UserInfo) {
            if (section == UserInfo && strchr(forbiddenUserInfo + 1, uc))
                error = true;
            else if (section != UserInfo && strchr(forbiddenUserInfo, uc))
                error = true;
        }

        if (!error)
            continue;

        ErrorCode errorCode = ErrorCode(int(section) << 8);
        if (section == UserInfo) {
            // is it the user name or the password?
            errorCode = InvalidUserNameError;
            for (uint j = uint(begin); j < i; ++j)
                if (data[j] == ':') {
                    errorCode = InvalidPasswordError;
                    break;
                }
        }

        setError(errorCode, input, i);
        return false;
    }

    // no errors
    return true;
}

#if 0
inline void QUrlPrivate::validate() const
{
    QUrlPrivate *that = (QUrlPrivate *)this;
    that->encodedOriginal = that->toEncoded(); // may detach
    parse(ParseOnly);

    QURL_SETFLAG(that->stateFlags, Validated);

    if (!isValid)
        return;

    QString auth = authority(); // causes the non-encoded forms to be valid

    // authority() calls canonicalHost() which sets this
    if (!isHostValid)
        return;

    if (scheme == QLatin1String("mailto")) {
        if (!host.isEmpty() || port != -1 || !userName.isEmpty() || !password.isEmpty()) {
            that->isValid = false;
            that->errorInfo.setParams(0, QT_TRANSLATE_NOOP(QUrl, "expected empty host, username,"
                                                           "port and password"),
                                      0, 0);
        }
    } else if (scheme == ftpScheme() || scheme == httpScheme()) {
        if (host.isEmpty() && !(path.isEmpty() && encodedPath.isEmpty())) {
            that->isValid = false;
            that->errorInfo.setParams(0, QT_TRANSLATE_NOOP(QUrl, "the host is empty, but not the path"),
                                      0, 0);
        }
    }
}

inline const QByteArray &QUrlPrivate::normalized() const
{
    if (QURL_HASFLAG(stateFlags, QUrlPrivate::Normalized))
        return encodedNormalized;

    QUrlPrivate *that = const_cast<QUrlPrivate *>(this);
    QURL_SETFLAG(that->stateFlags, QUrlPrivate::Normalized);

    QUrlPrivate tmp = *this;
    tmp.scheme = tmp.scheme.toLower();
    tmp.host = tmp.canonicalHost();

    // ensure the encoded and normalized parts of the URL
    tmp.ensureEncodedParts();
    if (tmp.encodedUserName.contains('%'))
        q_normalizePercentEncoding(&tmp.encodedUserName, userNameExcludeChars);
    if (tmp.encodedPassword.contains('%'))
        q_normalizePercentEncoding(&tmp.encodedPassword, passwordExcludeChars);
    if (tmp.encodedFragment.contains('%'))
        q_normalizePercentEncoding(&tmp.encodedFragment, fragmentExcludeChars);

    if (tmp.encodedPath.contains('%')) {
        // the path is a bit special:
        // the slashes shouldn't be encoded or decoded.
        // They should remain exactly like they are right now
        //
        // treat the path as a slash-separated sequence of pchar
        QByteArray result;
        result.reserve(tmp.encodedPath.length());
        if (tmp.encodedPath.startsWith('/'))
            result.append('/');

        const char *data = tmp.encodedPath.constData();
        int lastSlash = 0;
        int nextSlash;
        do {
            ++lastSlash;
            nextSlash = tmp.encodedPath.indexOf('/', lastSlash);
            int len;
            if (nextSlash == -1)
                len = tmp.encodedPath.length() - lastSlash;
            else
                len = nextSlash - lastSlash;

            if (memchr(data + lastSlash, '%', len)) {
                // there's at least one percent before the next slash
                QByteArray block = QByteArray(data + lastSlash, len);
                q_normalizePercentEncoding(&block, pathExcludeChars);
                result.append(block);
            } else {
                // no percents in this path segment, append wholesale
                result.append(data + lastSlash, len);
            }

            // append the slash too, if it's there
            if (nextSlash != -1)
                result.append('/');

            lastSlash = nextSlash;
        } while (lastSlash != -1);

        tmp.encodedPath = result;
    }

    if (!tmp.scheme.isEmpty()) // relative test
        removeDotsFromPath(&tmp.encodedPath);

    int qLen = tmp.query.length();
    for (int i = 0; i < qLen; i++) {
        if (qLen - i > 2 && tmp.query.at(i) == '%') {
            ++i;
            tmp.query[i] = qToLower(tmp.query.at(i));
            ++i;
            tmp.query[i] = qToLower(tmp.query.at(i));
        }
    }
    encodedNormalized = tmp.toEncoded();

    return encodedNormalized;
}
#endif

/*!
    \macro QT_NO_URL_CAST_FROM_STRING
    \relates QUrl

    Disables automatic conversions from QString (or char *) to QUrl.

    Compiling your code with this define is useful when you have a lot of
    code that uses QString for file names and you wish to convert it to
    use QUrl for network transparency. In any code that uses QUrl, it can
    help avoid missing QUrl::resolved() calls, and other misuses of
    QString to QUrl conversions.

    \oldcode
        url = filename; // probably not what you want
    \newcode
        url = QUrl::fromLocalFile(filename);
        url = baseurl.resolved(QUrl(filename));
    \endcode

    \sa QT_NO_CAST_FROM_ASCII
*/


/*!
    Constructs a URL by parsing \a url. QUrl will automatically percent encode
    all characters that are not allowed in a URL and decode the percent-encoded
    sequences that represent a character that is allowed in a URL.

    Parses the \a url using the parser mode \a parsingMode. In TolerantMode
    (the default), QUrl will correct certain mistakes, notably the presence of
    a percent character ('%') not followed by two hexadecimal digits, and it
    will accept any character in any position. In StrictMode, encoding mistakes
    will not be tolerated and QUrl will also check that certain forbidden
    characters are not present in unencoded form. If an error is detected in
    StrictMode, isValid() will return false. The parsing mode DecodedMode is not
    permitted in this context.

    Example:

    \snippet code/src_corelib_io_qurl.cpp 0

    To construct a URL from an encoded string, you can also use fromEncoded():

    \snippet code/src_corelib_io_qurl.cpp 1

    Both functions are equivalent and, in Qt 5, both functions accept encoded
    data. Usually, the choice of the QUrl constructor or setUrl() versus
    fromEncoded() will depend on the source data: the constructor and setUrl()
    take a QString, whereas fromEncoded takes a QByteArray.

    \sa setUrl(), fromEncoded(), TolerantMode
*/
QUrl::QUrl(const QString &url, ParsingMode parsingMode) : d(0)
{
    setUrl(url, parsingMode);
}

/*!
    Constructs an empty QUrl object.
*/
QUrl::QUrl() : d(0)
{
}

/*!
    Constructs a copy of \a other.
*/
QUrl::QUrl(const QUrl &other) : d(other.d)
{
    if (d)
        d->ref.ref();
}

/*!
    Destructor; called immediately before the object is deleted.
*/
QUrl::~QUrl()
{
    if (d && !d->ref.deref())
        delete d;
}

/*!
    Returns true if the URL is non-empty and valid; otherwise returns false.

    The URL is run through a conformance test. Every part of the URL
    must conform to the standard encoding rules of the URI standard
    for the URL to be reported as valid.

    \snippet code/src_corelib_io_qurl.cpp 2
*/
bool QUrl::isValid() const
{
    if (isEmpty()) {
        // also catches d == 0
        return false;
    }
    return d->validityError() == QUrlPrivate::NoError;
}

/*!
    Returns true if the URL has no data; otherwise returns false.

    \sa clear()
*/
bool QUrl::isEmpty() const
{
    if (!d) return true;
    return d->isEmpty();
}

/*!
    Resets the content of the QUrl. After calling this function, the
    QUrl is equal to one that has been constructed with the default
    empty constructor.

    \sa isEmpty()
*/
void QUrl::clear()
{
    if (d && !d->ref.deref())
        delete d;
    d = 0;
}

/*!
    Parses \a url and sets this object to that value. QUrl will automatically
    percent encode all characters that are not allowed in a URL and decode the
    percent-encoded sequences that represent a character that is allowed in a
    URL.

    Parses the \a url using the parser mode \a parsingMode. In TolerantMode
    (the default), QUrl will correct certain mistakes, notably the presence of
    a percent character ('%') not followed by two hexadecimal digits, and it
    will accept any character in any position. In StrictMode, encoding mistakes
    will not be tolerated and QUrl will also check that certain forbidden
    characters are not present in unencoded form. If an error is detected in
    StrictMode, isValid() will return false. The parsing mode DecodedMode is
    not permitted in this context and will produce a run-time warning.

    \sa url(), toString()
*/
void QUrl::setUrl(const QString &url, ParsingMode parsingMode)
{
    if (parsingMode == DecodedMode) {
        qWarning("QUrl: QUrl::DecodedMode is not permitted when parsing a full URL");
    } else {
        detach();
        d->parse(url, parsingMode);
    }
}

/*!
    \fn void QUrl::setEncodedUrl(const QByteArray &encodedUrl, ParsingMode parsingMode)
    \deprecated
    Constructs a URL by parsing the contents of \a encodedUrl.

    \a encodedUrl is assumed to be a URL string in percent encoded
    form, containing only ASCII characters.

    The parsing mode \a parsingMode is used for parsing \a encodedUrl.

    \obsolete Use setUrl(QString::fromUtf8(encodedUrl), parsingMode)

    \sa setUrl()
*/

/*!
    Sets the scheme of the URL to \a scheme. As a scheme can only
    contain ASCII characters, no conversion or decoding is done on the
    input. It must also start with an ASCII letter.

    The scheme describes the type (or protocol) of the URL. It's
    represented by one or more ASCII characters at the start the URL,
    and is followed by a ':'. The following example shows a URL where
    the scheme is "ftp":

    \image qurl-authority2.png

    The scheme can also be empty, in which case the URL is interpreted
    as relative.

    \sa scheme(), isRelative()
*/
void QUrl::setScheme(const QString &scheme)
{
    detach();
    d->clearError();
    if (scheme.isEmpty()) {
        // schemes are not allowed to be empty
        d->sectionIsPresent &= ~QUrlPrivate::Scheme;
        d->scheme.clear();
    } else {
        d->setScheme(scheme, scheme.length(), /* do set error */ true);
    }
}

/*!
    Returns the scheme of the URL. If an empty string is returned,
    this means the scheme is undefined and the URL is then relative.

    The scheme can only contain US-ASCII letters or digits, which means it
    cannot contain any character that would otherwise require encoding.

    \sa setScheme(), isRelative()
*/
QString QUrl::scheme() const
{
    if (!d) return QString();

    return d->scheme;
}

/*!
    Sets the authority of the URL to \a authority.

    The authority of a URL is the combination of user info, a host
    name and a port. All of these elements are optional; an empty
    authority is therefore valid.

    The user info and host are separated by a '@', and the host and
    port are separated by a ':'. If the user info is empty, the '@'
    must be omitted; although a stray ':' is permitted if the port is
    empty.

    The following example shows a valid authority string:

    \image qurl-authority.png

    The \a authority data is interpreted according to \a mode: in StrictMode,
    any '%' characters must be followed by exactly two hexadecimal characters
    and some characters (including space) are not allowed in undecoded form. In
    TolerantMode (the default), all characters are accepted in undecoded form
    and the tolerant parser will correct stray '%' not followed by two hex
    characters. In DecodedMode, '%' stand for themselves and encoded characters
    are not possible. Because of that, in DecodedMode, it is not possible to
    use the delimiter characters as non-delimiters (e.g., a password containing
    a '@').

    \sa setUserInfo(), setHost(), setPort()
*/
void QUrl::setAuthority(const QString &authority, ParsingMode mode)
{
    detach();
    d->clearError();
    QString data = authority;
    if (mode == DecodedMode) {
        parseDecodedComponent(data);
        mode = TolerantMode;
    }

    d->setAuthority(data, 0, data.length(), mode);
    if (authority.isNull()) {
        // QUrlPrivate::setAuthority cleared almost everything
        // but it leaves the Host bit set
        d->sectionIsPresent &= ~QUrlPrivate::Authority;
    }
}

/*!
    Returns the authority of the URL if it is defined; otherwise
    an empty string is returned.

    The \a options argument controls how to format the authority portion of the
    URL. The value of QUrl::FullyDecoded should be avoided, since it may
    produce an ambiguous return value (for example, if the username contains a
    colon ':' or either the username or password contain an at-sign '@'). In
    all other cases, this function returns an unambiguous value, which may
    contain those characters still percent-encoded, plus some control
    sequences not representable in decoded form in QString.

    \sa setAuthority(), userInfo(), userName(), password(), host(), port()
*/
QString QUrl::authority(ComponentFormattingOptions options) const
{
    if (!d) return QString();

    QString result;
    d->appendAuthority(result, options, QUrlPrivate::Authority);
    return result;
}

/*!
    Sets the user info of the URL to \a userInfo. The user info is an
    optional part of the authority of the URL, as described in
    setAuthority().

    The user info consists of a user name and optionally a password,
    separated by a ':'. If the password is empty, the colon must be
    omitted. The following example shows a valid user info string:

    \image qurl-authority3.png

    The \a userInfo data is interpreted according to \a mode: in StrictMode,
    any '%' characters must be followed by exactly two hexadecimal characters
    and some characters (including space) are not allowed in undecoded form. In
    TolerantMode (the default), all characters are accepted in undecoded form
    and the tolerant parser will correct stray '%' not followed by two hex
    characters. In DecodedMode, '%' stand for themselves and encoded characters
    are not possible. Because of that, in DecodedMode, it is not possible to
    use the ':' delimiter characters as non-delimiter in the user name.

    \sa userInfo(), setUserName(), setPassword(), setAuthority()
*/
void QUrl::setUserInfo(const QString &userInfo, ParsingMode mode)
{
    detach();
    d->clearError();
    QString trimmed = userInfo.trimmed();
    if (mode == DecodedMode) {
        parseDecodedComponent(trimmed);
        mode = TolerantMode;
    }

    d->setUserInfo(trimmed, 0, trimmed.length());
    if (userInfo.isNull()) {
        // QUrlPrivate::setUserInfo cleared almost everything
        // but it leaves the UserName bit set
        d->sectionIsPresent &= ~QUrlPrivate::UserInfo;
    } else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::UserInfo, userInfo)) {
        d->sectionIsPresent &= ~QUrlPrivate::UserInfo;
        d->userName.clear();
        d->password.clear();
    }
}

/*!
    Returns the user info of the URL, or an empty string if the user
    info is undefined.

    The \a options argument controls how to format the user info component. The
    value of QUrl::FullyDecoded should be avoided, since it may produce an
    ambiguous return value (for example, if the username contains a colon ':').
    In all other cases, this function returns an unambiguous value, which may
    contain that characters still percent-encoded, plus some control sequences
    not representable in decoded form in QString.

    \sa setUserInfo(), userName(), password(), authority()
*/
QString QUrl::userInfo(ComponentFormattingOptions options) const
{
    if (!d) return QString();

    QString result;
    d->appendUserInfo(result, options, QUrlPrivate::UserInfo);
    return result;
}

/*!
    Sets the URL's user name to \a userName. The \a userName is part
    of the user info element in the authority of the URL, as described
    in setUserInfo().

    The \a userName data is interpreted according to \a mode: in StrictMode,
    any '%' characters must be followed by exactly two hexadecimal characters
    and some characters (including space) are not allowed in undecoded form. In
    TolerantMode (the default), all characters are accepted in undecoded form
    and the tolerant parser will correct stray '%' not followed by two hex
    characters. In DecodedMode, '%' stand for themselves and encoded characters
    are not possible.

    QUrl::DecodedMode should be used when setting the user name from a data
    source which is not a URL, such as a password dialog shown to the user or
    with a user name obtained by calling userName() with the QUrl::FullyDecoded
    formatting option.

    \sa userName(), setUserInfo()
*/
void QUrl::setUserName(const QString &userName, ParsingMode mode)
{
    detach();
    d->clearError();

    QString data = userName;
    if (mode == DecodedMode) {
        parseDecodedComponent(data);
        mode = TolerantMode;
    }

    d->setUserName(data, 0, data.length());
    if (userName.isNull())
        d->sectionIsPresent &= ~QUrlPrivate::UserName;
    else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::UserName, userName))
        d->userName.clear();
}

/*!
    Returns the user name of the URL if it is defined; otherwise
    an empty string is returned.

    The \a options argument controls how to format the user name component. All
    values produce an unambiguous result. With QUrl::FullyDecoded, all
    percent-encoded sequences are decoded; otherwise, the returned value may
    contain some percent-encoded sequences for some control sequences not
    representable in decoded form in QString.

    Note that QUrl::FullyDecoded may cause data loss if those non-representable
    sequences are present. It is recommended to use that value when the result
    will be used in a non-URL context, such as setting in QAuthenticator or
    negotiating a login.

    \sa setUserName(), userInfo()
*/
QString QUrl::userName(ComponentFormattingOptions options) const
{
    if (!d) return QString();

    QString result;
    d->appendUserName(result, options);
    return result;
}

/*!
    \fn void QUrl::setEncodedUserName(const QByteArray &userName)
    \deprecated
    \since 4.4

    Sets the URL's user name to the percent-encoded \a userName. The \a
    userName is part of the user info element in the authority of the
    URL, as described in setUserInfo().

    \obsolete Use setUserName(QString::fromUtf8(userName))

    \sa setUserName(), encodedUserName(), setUserInfo()
*/

/*!
    \fn QByteArray QUrl::encodedUserName() const
    \deprecated
    \since 4.4

    Returns the user name of the URL if it is defined; otherwise
    an empty string is returned. The returned value will have its
    non-ASCII and other control characters percent-encoded, as in
    toEncoded().

    \obsolete Use userName(QUrl::FullyEncoded).toLatin1()

    \sa setEncodedUserName()
*/

/*!
    Sets the URL's password to \a password. The \a password is part of
    the user info element in the authority of the URL, as described in
    setUserInfo().

    The \a password data is interpreted according to \a mode: in StrictMode,
    any '%' characters must be followed by exactly two hexadecimal characters
    and some characters (including space) are not allowed in undecoded form. In
    TolerantMode, all characters are accepted in undecoded form and the
    tolerant parser will correct stray '%' not followed by two hex characters.
    In DecodedMode, '%' stand for themselves and encoded characters are not
    possible.

    QUrl::DecodedMode should be used when setting the password from a data
    source which is not a URL, such as a password dialog shown to the user or
    with a password obtained by calling password() with the QUrl::FullyDecoded
    formatting option.

    \sa password(), setUserInfo()
*/
void QUrl::setPassword(const QString &password, ParsingMode mode)
{
    detach();
    d->clearError();

    QString data = password;
    if (mode == DecodedMode) {
        parseDecodedComponent(data);
        mode = TolerantMode;
    }

    d->setPassword(data, 0, data.length());
    if (password.isNull())
        d->sectionIsPresent &= ~QUrlPrivate::Password;
    else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::Password, password))
        d->password.clear();
}

/*!
    Returns the password of the URL if it is defined; otherwise
    an empty string is returned.

    The \a options argument controls how to format the user name component. All
    values produce an unambiguous result. With QUrl::FullyDecoded, all
    percent-encoded sequences are decoded; otherwise, the returned value may
    contain some percent-encoded sequences for some control sequences not
    representable in decoded form in QString.

    Note that QUrl::FullyDecoded may cause data loss if those non-representable
    sequences are present. It is recommended to use that value when the result
    will be used in a non-URL context, such as setting in QAuthenticator or
    negotiating a login.

    \sa setPassword()
*/
QString QUrl::password(ComponentFormattingOptions options) const
{
    if (!d) return QString();

    QString result;
    d->appendPassword(result, options);
    return result;
}

/*!
    \fn void QUrl::setEncodedPassword(const QByteArray &password)
    \deprecated
    \since 4.4

    Sets the URL's password to the percent-encoded \a password. The \a
    password is part of the user info element in the authority of the
    URL, as described in setUserInfo().

    \obsolete Use setPassword(QString::fromUtf8(password));

    \sa setPassword(), encodedPassword(), setUserInfo()
*/

/*!
    \fn QByteArray QUrl::encodedPassword() const
    \deprecated
    \since 4.4

    Returns the password of the URL if it is defined; otherwise an
    empty string is returned. The returned value will have its
    non-ASCII and other control characters percent-encoded, as in
    toEncoded().

    \obsolete Use password(QUrl::FullyEncoded).toLatin1()

    \sa setEncodedPassword(), toEncoded()
*/

/*!
    Sets the host of the URL to \a host. The host is part of the
    authority.

    The \a host data is interpreted according to \a mode: in StrictMode,
    any '%' characters must be followed by exactly two hexadecimal characters
    and some characters (including space) are not allowed in undecoded form. In
    TolerantMode, all characters are accepted in undecoded form and the
    tolerant parser will correct stray '%' not followed by two hex characters.
    In DecodedMode, '%' stand for themselves and encoded characters are not
    possible.

    Note that, in all cases, the result of the parsing must be a valid hostname
    according to STD 3 rules, as modified by the Internationalized Resource
    Identifiers specification (RFC 3987). Invalid hostnames are not permitted
    and will cause isValid() to become false.

    \sa host(), setAuthority()
*/
void QUrl::setHost(const QString &host, ParsingMode mode)
{
    detach();
    d->clearError();

    QString data = host;
    if (mode == DecodedMode) {
        parseDecodedComponent(data);
        mode = TolerantMode;
    }

    if (d->setHost(data, 0, data.length(), mode)) {
        if (host.isNull())
            d->sectionIsPresent &= ~QUrlPrivate::Host;
    } else if (!data.startsWith(QLatin1Char('['))) {
        // setHost failed, it might be IPv6 or IPvFuture in need of bracketing
        Q_ASSERT(d->error);

        data.prepend(QLatin1Char('['));
        data.append(QLatin1Char(']'));
        if (!d->setHost(data, 0, data.length(), mode)) {
            // failed again
            if (data.contains(QLatin1Char(':'))) {
                // source data contains ':', so it's an IPv6 error
                d->error->code = QUrlPrivate::InvalidIPv6AddressError;
            }
        } else {
            // succeeded
            d->clearError();
        }
    }
}

/*!
    Returns the host of the URL if it is defined; otherwise
    an empty string is returned.

    The \a options argument controls how the hostname will be formatted. The
    QUrl::EncodeUnicode option will cause this function to return the hostname
    in the ASCII-Compatible Encoding (ACE) form, which is suitable for use in
    channels that are not 8-bit clean or that require the legacy hostname (such
    as DNS requests or in HTTP request headers). If that flag is not present,
    this function returns the International Domain Name (IDN) in Unicode form,
    according to the list of permissible top-level domains (see
    idnWhiteList()).

    All other flags are ignored. Host names cannot contain control or percent
    characters, so the returned value can be considered fully decoded.

    \sa setHost(), idnWhitelist(), setIdnWhitelist(), authority()
*/
QString QUrl::host(ComponentFormattingOptions options) const
{
    if (!d) return QString();

    QString result;
    d->appendHost(result, options);
    if (result.startsWith(QLatin1Char('[')))
        return result.mid(1, result.length() - 2);
    return result;
}

/*!
    \fn void QUrl::setEncodedHost(const QByteArray &host)
    \deprecated
    \since 4.4

    Sets the URL's host to the ACE- or percent-encoded \a host. The \a
    host is part of the user info element in the authority of the
    URL, as described in setAuthority().

    \obsolete Use setHost(QString::fromUtf8(host)).

    \sa setHost(), encodedHost(), setAuthority(), fromAce()
*/

/*!
    \fn QByteArray QUrl::encodedHost() const
    \deprecated
    \since 4.4

    Returns the host part of the URL if it is defined; otherwise
    an empty string is returned.

    Note: encodedHost() does not return percent-encoded hostnames. Instead,
    the ACE-encoded (bare ASCII in Punycode encoding) form will be
    returned for any non-ASCII hostname.

    This function is equivalent to calling QUrl::toAce() on the return
    value of host().

    \obsolete Use host(QUrl::FullyEncoded).toLatin1() or toAce(host()).

    \sa setEncodedHost()
*/

/*!
    Sets the port of the URL to \a port. The port is part of the
    authority of the URL, as described in setAuthority().

    \a port must be between 0 and 65535 inclusive. Setting the
    port to -1 indicates that the port is unspecified.
*/
void QUrl::setPort(int port)
{
    detach();
    d->clearError();

    if (port < -1 || port > 65535) {
        port = -1;
        d->setError(QUrlPrivate::InvalidPortError, QString::number(port), 0);
    }

    d->port = port;
}

/*!
    \since 4.1

    Returns the port of the URL, or \a defaultPort if the port is
    unspecified.

    Example:

    \snippet code/src_corelib_io_qurl.cpp 3
*/
int QUrl::port(int defaultPort) const
{
    if (!d) return defaultPort;
    return d->port == -1 ? defaultPort : d->port;
}

/*!
    Sets the path of the URL to \a path. The path is the part of the
    URL that comes after the authority but before the query string.

    \image qurl-ftppath.png

    For non-hierarchical schemes, the path will be everything
    following the scheme declaration, as in the following example:

    \image qurl-mailtopath.png

    The \a path data is interpreted according to \a mode: in StrictMode,
    any '%' characters must be followed by exactly two hexadecimal characters
    and some characters (including space) are not allowed in undecoded form. In
    TolerantMode (the default), all characters are accepted in undecoded form and the
    tolerant parser will correct stray '%' not followed by two hex characters.
    In DecodedMode, '%' stand for themselves and encoded characters are not
    possible.

    QUrl::DecodedMode should be used when setting the path from a data source
    which is not a URL, such as a dialog shown to the user or with a path
    obtained by calling path() with the QUrl::FullyDecoded formatting option.

    \sa path()
*/
void QUrl::setPath(const QString &path, ParsingMode mode)
{
    detach();
    d->clearError();

    QString data = path;
    if (mode == DecodedMode) {
        parseDecodedComponent(data);
        mode = TolerantMode;
    }

    d->setPath(data, 0, data.length());

    // optimized out, since there is no path delimiter
//    if (path.isNull())
//        d->sectionIsPresent &= ~QUrlPrivate::Path;
//    else
    if (mode == StrictMode && !d->validateComponent(QUrlPrivate::Path, path))
        d->path.clear();
}

/*!
    Returns the path of the URL.

    The \a options argument controls how to format the path component. All
    values produce an unambiguous result. With QUrl::FullyDecoded, all
    percent-encoded sequences are decoded; otherwise, the returned value may
    contain some percent-encoded sequences for some control sequences not
    representable in decoded form in QString.

    Note that QUrl::FullyDecoded may cause data loss if those non-representable
    sequences are present. It is recommended to use that value when the result
    will be used in a non-URL context, such as sending to an FTP server.

    \sa setPath()
*/
QString QUrl::path(ComponentFormattingOptions options) const
{
    if (!d) return QString();

    QString result;
    d->appendPath(result, options, QUrlPrivate::Path);
    return result;
}

/*!
    \fn void QUrl::setEncodedPath(const QByteArray &path)
    \deprecated
    \since 4.4

    Sets the URL's path to the percent-encoded \a path.  The path is
    the part of the URL that comes after the authority but before the
    query string.

    \image qurl-ftppath.png

    For non-hierarchical schemes, the path will be everything
    following the scheme declaration, as in the following example:

    \image qurl-mailtopath.png

    \obsolete Use setPath(QString::fromUtf8(path)).

    \sa setPath(), encodedPath(), setUserInfo()
*/

/*!
    \fn QByteArray QUrl::encodedPath() const
    \deprecated
    \since 4.4

    Returns the path of the URL if it is defined; otherwise an
    empty string is returned. The returned value will have its
    non-ASCII and other control characters percent-encoded, as in
    toEncoded().

    \obsolete Use path(QUrl::FullyEncoded).toLatin1().

    \sa setEncodedPath(), toEncoded()
*/

/*!
    \since 4.2

    Returns true if this URL contains a Query (i.e., if ? was seen on it).

    \sa setQuery(), query(), hasFragment()
*/
bool QUrl::hasQuery() const
{
    if (!d) return false;
    return d->hasQuery();
}

/*!
    Sets the query string of the URL to \a query.

    This function is useful if you need to pass a query string that
    does not fit into the key-value pattern, or that uses a different
    scheme for encoding special characters than what is suggested by
    QUrl.

    Passing a value of QString() to \a query (a null QString) unsets
    the query completely. However, passing a value of QString("")
    will set the query to an empty value, as if the original URL
    had a lone "?".

    The \a query data is interpreted according to \a mode: in StrictMode,
    any '%' characters must be followed by exactly two hexadecimal characters
    and some characters (including space) are not allowed in undecoded form. In
    TolerantMode, all characters are accepted in undecoded form and the
    tolerant parser will correct stray '%' not followed by two hex characters.
    In DecodedMode, '%' stand for themselves and encoded characters are not
    possible.

    Query strings often contain percent-encoded sequences, so use of
    DecodedMode is discouraged. One special sequence to be aware of is that of
    the plus character ('+'). QUrl does not convert spaces to plus characters,
    even though HTML forms posted by web browsers do. In order to represent an
    actual plus character in a query, the sequence "%2B" is usually used. This
    function will leave "%2B" sequences untouched in TolerantMode or
    StrictMode.

    \sa query(), hasQuery()
*/
void QUrl::setQuery(const QString &query, ParsingMode mode)
{
    detach();
    d->clearError();

    QString data = query;
    if (mode == DecodedMode) {
        parseDecodedComponent(data);
        mode = TolerantMode;
    }

    d->setQuery(data, 0, data.length());
    if (query.isNull())
        d->sectionIsPresent &= ~QUrlPrivate::Query;
    else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::Query, query))
        d->query.clear();
}

/*!
    \fn void QUrl::setEncodedQuery(const QByteArray &query)
    \deprecated

    Sets the query string of the URL to \a query. The string is
    inserted as-is, and no further encoding is performed when calling
    toEncoded().

    This function is useful if you need to pass a query string that
    does not fit into the key-value pattern, or that uses a different
    scheme for encoding special characters than what is suggested by
    QUrl.

    Passing a value of QByteArray() to \a query (a null QByteArray) unsets
    the query completely. However, passing a value of QByteArray("")
    will set the query to an empty value, as if the original URL
    had a lone "?".

    \obsolete Use setQuery, which has the same null / empty behavior.

    \sa encodedQuery(), hasQuery()
*/

/*!
    \overload
    \since 5.0
    Sets the query string of the URL to \a query.

    This function reconstructs the query string from the QUrlQuery object and
    sets on this QUrl object. This function does not have parsing parameters
    because the QUrlQuery contains data that is already parsed.

    \sa query(), hasQuery()
*/
void QUrl::setQuery(const QUrlQuery &query)
{
    detach();
    d->clearError();

    // we know the data is in the right format
    d->query = query.toString();
    if (query.isEmpty())
        d->sectionIsPresent &= ~QUrlPrivate::Query;
    else
        d->sectionIsPresent |= QUrlPrivate::Query;
}

/*!
    \fn void QUrl::setQueryItems(const QList<QPair<QString, QString> > &query)
    \deprecated

    Sets the query string of the URL to an encoded version of \a
    query. The contents of \a query are converted to a string
    internally, each pair delimited by the character returned by
    pairDelimiter(), and the key and value are delimited by
    valueDelimiter().

    \note This method does not encode spaces (ASCII 0x20) as plus (+) signs,
    like HTML forms do. If you need that kind of encoding, you must encode
    the value yourself and use QUrl::setEncodedQueryItems.

    \obsolete Use QUrlQuery and setQuery().

    \sa queryItems(), setEncodedQueryItems()
*/

/*!
    \fn void QUrl::setEncodedQueryItems(const QList<QPair<QByteArray, QByteArray> > &query)
    \deprecated
    \since 4.4

    Sets the query string of the URL to the encoded version of \a
    query. The contents of \a query are converted to a string
    internally, each pair delimited by the character returned by
    pairDelimiter(), and the key and value are delimited by
    valueDelimiter().

    \obsolete Use QUrlQuery and setQuery().

    \sa encodedQueryItems(), setQueryItems()
*/

/*!
    \fn void QUrl::addQueryItem(const QString &key, const QString &value)
    \deprecated

    Inserts the pair \a key = \a value into the query string of the
    URL.

    The key/value pair is encoded before it is added to the query. The
    pair is converted into separate strings internally. The \a key and
    \a value is first encoded into UTF-8 and then delimited by the
    character returned by valueDelimiter(). Each key/value pair is
    delimited by the character returned by pairDelimiter().

    \note This method does not encode spaces (ASCII 0x20) as plus (+) signs,
    like HTML forms do. If you need that kind of encoding, you must encode
    the value yourself and use QUrl::addEncodedQueryItem.

    \obsolete Use QUrlQuery and setQuery().

    \sa addEncodedQueryItem()
*/

/*!
    \fn void QUrl::addEncodedQueryItem(const QByteArray &key, const QByteArray &value)
    \deprecated
    \since 4.4

    Inserts the pair \a key = \a value into the query string of the
    URL.

    \obsolete Use QUrlQuery and setQuery().

    \sa addQueryItem()
*/

/*!
    \fn QList<QPair<QString, QString> > QUrl::queryItems() const
    \deprecated

    Returns the query string of the URL, as a map of keys and values.

    \note This method does not decode spaces plus (+) signs as spaces (ASCII
    0x20), like HTML forms do. If you need that kind of decoding, you must
    use QUrl::encodedQueryItems and decode the data yourself.

    \obsolete Use QUrlQuery.

    \sa setQueryItems(), setEncodedQuery()
*/

/*!
    \fn QList<QPair<QByteArray, QByteArray> > QUrl::encodedQueryItems() const
    \deprecated
    \since 4.4

    Returns the query string of the URL, as a map of encoded keys and values.

    \obsolete Use QUrlQuery.

    \sa setEncodedQueryItems(), setQueryItems(), setEncodedQuery()
*/

/*!
    \fn bool QUrl::hasQueryItem(const QString &key) const
    \deprecated

    Returns true if there is a query string pair whose key is equal
    to \a key from the URL.

    \obsolete Use QUrlQuery.

    \sa hasEncodedQueryItem()
*/

/*!
    \fn bool QUrl::hasEncodedQueryItem(const QByteArray &key) const
    \deprecated
    \since 4.4

    Returns true if there is a query string pair whose key is equal
    to \a key from the URL.

    \obsolete Use QUrlQuery.

    \sa hasQueryItem()
*/

/*!
    \fn QString QUrl::queryItemValue(const QString &key) const
    \deprecated

    Returns the first query string value whose key is equal to \a key
    from the URL.

    \note This method does not decode spaces plus (+) signs as spaces (ASCII
    0x20), like HTML forms do. If you need that kind of decoding, you must
    use QUrl::encodedQueryItemValue and decode the data yourself.

    \obsolete Use QUrlQuery.

    \sa allQueryItemValues()
*/

/*!
    \fn QByteArray QUrl::encodedQueryItemValue(const QByteArray &key) const
    \deprecated
    \since 4.4

    Returns the first query string value whose key is equal to \a key
    from the URL.

    \obsolete Use QUrlQuery.

    \sa queryItemValue(), allQueryItemValues()
*/

/*!
    \fn QStringList QUrl::allQueryItemValues(const QString &key) const
    \deprecated

    Returns the a list of query string values whose key is equal to
    \a key from the URL.

    \note This method does not decode spaces plus (+) signs as spaces (ASCII
    0x20), like HTML forms do. If you need that kind of decoding, you must
    use QUrl::allEncodedQueryItemValues and decode the data yourself.

    \obsolete Use QUrlQuery.

    \sa queryItemValue()
*/

/*!
    \fn QList<QByteArray> QUrl::allEncodedQueryItemValues(const QByteArray &key) const
    \deprecated
    \since 4.4

    Returns the a list of query string values whose key is equal to
    \a key from the URL.

    \obsolete Use QUrlQuery.

    \sa allQueryItemValues(), queryItemValue(), encodedQueryItemValue()
*/

/*!
    \fn void QUrl::removeQueryItem(const QString &key)
    \deprecated

    Removes the first query string pair whose key is equal to \a key
    from the URL.

    \obsolete Use QUrlQuery.

    \sa removeAllQueryItems()
*/

/*!
    \fn void QUrl::removeEncodedQueryItem(const QByteArray &key)
    \deprecated
    \since 4.4

    Removes the first query string pair whose key is equal to \a key
    from the URL.

    \obsolete Use QUrlQuery.

    \sa removeQueryItem(), removeAllQueryItems()
*/

/*!
    \fn void QUrl::removeAllQueryItems(const QString &key)
    \deprecated

    Removes all the query string pairs whose key is equal to \a key
    from the URL.

    \obsolete Use QUrlQuery.

   \sa removeQueryItem()
*/

/*!
    \fn void QUrl::removeAllEncodedQueryItems(const QByteArray &key)
    \deprecated
    \since 4.4

    Removes all the query string pairs whose key is equal to \a key
    from the URL.

    \obsolete Use QUrlQuery.

   \sa removeQueryItem()
*/

/*!
    \fn QByteArray QUrl::encodedQuery() const
    \deprecated

    Returns the query string of the URL in percent encoded form.

    \obsolete Use query(QUrl::FullyEncoded).toLatin1()

    \sa setEncodedQuery(), query()
*/

/*!
    Returns the query string of the URL if there's a query string, or an empty
    result if not. To determine if the parsed URL contained a query string, use
    hasQuery().

    The \a options argument controls how to format the query component. All
    values produce an unambiguous result. With QUrl::FullyDecoded, all
    percent-encoded sequences are decoded; otherwise, the returned value may
    contain some percent-encoded sequences for some control sequences not
    representable in decoded form in QString.

    Note that use of QUrl::FullyDecoded in queries is discouraged, as queries
    often contain data that is supposed to remain percent-encoded, including
    the use of the "%2B" sequence to represent a plus character ('+').

    \sa setQuery(), hasQuery()
*/
QString QUrl::query(ComponentFormattingOptions options) const
{
    if (!d) return QString();

    QString result;
    d->appendQuery(result, options, QUrlPrivate::Query);
    if (d->hasQuery() && result.isNull())
        result.detach();
    return result;
}

/*!
    Sets the fragment of the URL to \a fragment. The fragment is the
    last part of the URL, represented by a '#' followed by a string of
    characters. It is typically used in HTTP for referring to a
    certain link or point on a page:

    \image qurl-fragment.png

    The fragment is sometimes also referred to as the URL "reference".

    Passing an argument of QString() (a null QString) will unset the fragment.
    Passing an argument of QString("") (an empty but not null QString)
    will set the fragment to an empty string (as if the original URL
    had a lone "#").

    The \a fragment data is interpreted according to \a mode: in StrictMode,
    any '%' characters must be followed by exactly two hexadecimal characters
    and some characters (including space) are not allowed in undecoded form. In
    TolerantMode, all characters are accepted in undecoded form and the
    tolerant parser will correct stray '%' not followed by two hex characters.
    In DecodedMode, '%' stand for themselves and encoded characters are not
    possible.

    QUrl::DecodedMode should be used when setting the fragment from a data
    source which is not a URL or with a fragment obtained by calling
    fragment() with the QUrl::FullyDecoded formatting option.

    \sa fragment(), hasFragment()
*/
void QUrl::setFragment(const QString &fragment, ParsingMode mode)
{
    detach();
    d->clearError();

    QString data = fragment;
    if (mode == DecodedMode) {
        parseDecodedComponent(data);
        mode = TolerantMode;
    }

    d->setFragment(data, 0, data.length());
    if (fragment.isNull())
        d->sectionIsPresent &= ~QUrlPrivate::Fragment;
    else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::Fragment, fragment))
        d->fragment.clear();
}

/*!
    Returns the fragment of the URL. To determine if the parsed URL contained a
    fragment, use hasFragment().

    The \a options argument controls how to format the fragment component. All
    values produce an unambiguous result. With QUrl::FullyDecoded, all
    percent-encoded sequences are decoded; otherwise, the returned value may
    contain some percent-encoded sequences for some control sequences not
    representable in decoded form in QString.

    Note that QUrl::FullyDecoded may cause data loss if those non-representable
    sequences are present. It is recommended to use that value when the result
    will be used in a non-URL context.

    \sa setFragment(), hasFragment()
*/
QString QUrl::fragment(ComponentFormattingOptions options) const
{
    if (!d) return QString();

    QString result;
    d->appendFragment(result, options);
    if (d->hasFragment() && result.isNull())
        result.detach();
    return result;
}

/*!
    \fn void QUrl::setEncodedFragment(const QByteArray &fragment)
    \deprecated
    \since 4.4

    Sets the URL's fragment to the percent-encoded \a fragment. The fragment is the
    last part of the URL, represented by a '#' followed by a string of
    characters. It is typically used in HTTP for referring to a
    certain link or point on a page:

    \image qurl-fragment.png

    The fragment is sometimes also referred to as the URL "reference".

    Passing an argument of QByteArray() (a null QByteArray) will unset
    the fragment.  Passing an argument of QByteArray("") (an empty but
    not null QByteArray) will set the fragment to an empty string (as
    if the original URL had a lone "#").

    \obsolete Use setFragment(), which has the same behavior of null / empty.

    \sa setFragment(), encodedFragment()
*/

/*!
    \fn QByteArray QUrl::encodedFragment() const
    \deprecated
    \since 4.4

    Returns the fragment of the URL if it is defined; otherwise an
    empty string is returned. The returned value will have its
    non-ASCII and other control characters percent-encoded, as in
    toEncoded().

    \obsolete Use query(QUrl::FullyEncoded).toLatin1().

    \sa setEncodedFragment(), toEncoded()
*/

/*!
    \since 4.2

    Returns true if this URL contains a fragment (i.e., if # was seen on it).

    \sa fragment(), setFragment()
*/
bool QUrl::hasFragment() const
{
    if (!d) return false;
    return d->hasFragment();
}

/*!
    \since 4.8

    Returns the TLD (Top-Level Domain) of the URL, (e.g. .co.uk, .net).
    Note that the return value is prefixed with a '.' unless the
    URL does not contain a valid TLD, in which case the function returns
    an empty string.

    If \a options includes EncodeUnicode, the returned string will be in
    ASCII Compatible Encoding.
*/
QString QUrl::topLevelDomain(ComponentFormattingOptions options) const
{
    QString tld = qTopLevelDomain(host());
    if (options & EncodeUnicode) {
        return qt_ACE_do(tld, ToAceOnly);
    }
    return tld;
}

/*!
    Returns the result of the merge of this URL with \a relative. This
    URL is used as a base to convert \a relative to an absolute URL.

    If \a relative is not a relative URL, this function will return \a
    relative directly. Otherwise, the paths of the two URLs are
    merged, and the new URL returned has the scheme and authority of
    the base URL, but with the merged path, as in the following
    example:

    \snippet code/src_corelib_io_qurl.cpp 5

    Calling resolved() with ".." returns a QUrl whose directory is
    one level higher than the original. Similarly, calling resolved()
    with "../.." removes two levels from the path. If \a relative is
    "/", the path becomes "/".

    \sa isRelative()
*/
QUrl QUrl::resolved(const QUrl &relative) const
{
    if (!d) return relative;
    if (!relative.d) return *this;

    QUrl t;
    // be non strict and allow scheme in relative url
    if (!relative.d->scheme.isEmpty() && relative.d->scheme != d->scheme) {
        t = relative;
        t.detach();
    } else {
        if (relative.d->hasAuthority()) {
            t = relative;
            t.detach();
        } else {
            t.d = new QUrlPrivate;

            // copy the authority
            t.d->userName = d->userName;
            t.d->password = d->password;
            t.d->host = d->host;
            t.d->port = d->port;
            t.d->sectionIsPresent = d->sectionIsPresent & QUrlPrivate::Authority;

            if (relative.d->path.isEmpty()) {
                t.d->path = d->path;
                if (relative.d->hasQuery()) {
                    t.d->query = relative.d->query;
                    t.d->sectionIsPresent |= QUrlPrivate::Query;
                } else if (d->hasQuery()) {
                    t.d->query = d->query;
                    t.d->sectionIsPresent |= QUrlPrivate::Query;
                }
            } else {
                t.d->path = relative.d->path.startsWith(QLatin1Char('/'))
                            ? relative.d->path
                            : d->mergePaths(relative.d->path);
                if (relative.d->hasQuery()) {
                    t.d->query = relative.d->query;
                    t.d->sectionIsPresent |= QUrlPrivate::Query;
                }
            }
        }
        t.d->scheme = d->scheme;
        if (d->hasScheme())
            t.d->sectionIsPresent |= QUrlPrivate::Scheme;
        else
            t.d->sectionIsPresent &= ~QUrlPrivate::Scheme;
    }
    t.d->fragment = relative.d->fragment;
    if (relative.d->hasFragment())
        t.d->sectionIsPresent |= QUrlPrivate::Fragment;
    else
        t.d->sectionIsPresent &= ~QUrlPrivate::Fragment;

    removeDotsFromPath(&t.d->path);

#if defined(QURL_DEBUG)
    qDebug("QUrl(\"%s\").resolved(\"%s\") = \"%s\"",
           qPrintable(url()),
           qPrintable(relative.url()),
           qPrintable(t.url()));
#endif
    return t;
}

/*!
    Returns true if the URL is relative; otherwise returns false. A URL is
    relative reference if its scheme is undefined; this function is therefore
    equivalent to calling scheme().isEmpty().

    Relative references are defined in RFC 3986 section 4.2.
*/
bool QUrl::isRelative() const
{
    if (!d) return true;
    return !d->hasScheme();
}

/*!
    Returns a string representation of the URL. The output can be customized by
    passing flags with \a options. The option QUrl::FullyDecoded is not
    permitted in this function since it would generate ambiguous data.

    The resulting QString can be passed back to a QUrl later on.

    Synonym for toString(options).

    \sa FormattingOptions, toEncoded(), toString()
*/
QString QUrl::url(FormattingOptions options) const
{
    return toString(options);
}

/*!
    Returns a string representation of the URL. The output can be customized by
    passing flags with \a options. The option QUrl::FullyDecoded is not
    permitted in this function since it would generate ambiguous data.

    The default formatting option is \l{QUrl::FormattingOptions}{PrettyDecoded}.

    \sa FormattingOptions, url(), setUrl()
*/
QString QUrl::toString(FormattingOptions options) const
{
    if (!isValid()) {
        // also catches isEmpty()
        return QString();
    }
    if (options == QUrl::FullyDecoded) {
        qWarning("QUrl: QUrl::FullyDecoded is not permitted when reconstructing the full URL");
        options = QUrl::PrettyDecoded;
    }

    // return just the path if:
    //  - QUrl::PreferLocalFile is passed
    //  - QUrl::RemovePath isn't passed (rather stupid if the user did...)
    //  - there's no query or fragment to return
    //    that is, either they aren't present, or we're removing them
    //  - it's a local file
    //    (test done last since it's the most expensive)
    if (options.testFlag(QUrl::PreferLocalFile) && !options.testFlag(QUrl::RemovePath)
            && (!d->hasQuery() || options.testFlag(QUrl::RemoveQuery))
            && (!d->hasFragment() || options.testFlag(QUrl::RemoveFragment))
            && isLocalFile()) {
        return path(options);
    }

    QString url;

    // for the full URL, we consider that the reserved characters are prettier if encoded
    if (options & DecodeReserved)
        options &= ~EncodeReserved;
    else
        options |= EncodeReserved;

    if (!(options & QUrl::RemoveScheme) && d->hasScheme())
        url += d->scheme + QLatin1Char(':');

    bool pathIsAbsolute = d->path.startsWith(QLatin1Char('/'));
    if (!((options & QUrl::RemoveAuthority) == QUrl::RemoveAuthority) && d->hasAuthority()) {
        url += QLatin1String("//");
        d->appendAuthority(url, options, QUrlPrivate::FullUrl);
    } else if (isLocalFile() && pathIsAbsolute) {
        url += QLatin1String("//");
    }

    if (!(options & QUrl::RemovePath)) {
        d->appendPath(url, options, QUrlPrivate::FullUrl);
        // check if we need to remove trailing slashes
        if ((options & StripTrailingSlash) && !d->path.isEmpty() && d->path != QLatin1String("/") && url.endsWith(QLatin1Char('/')))
            url.chop(1);
    }

    if (!(options & QUrl::RemoveQuery) && d->hasQuery()) {
        url += QLatin1Char('?');
        d->appendQuery(url, options, QUrlPrivate::FullUrl);
    }
    if (!(options & QUrl::RemoveFragment) && d->hasFragment()) {
        url += QLatin1Char('#');
        d->appendFragment(url, options);
    }

    return url;
}

/*!
    \since 5.0

    Returns a human-displayable string representation of the URL.
    The output can be customized by passing flags with \a options.
    The option RemovePassword is always enabled, since passwords
    should never be shown back to users.

    With the default options, the resulting QString can be passed back
    to a QUrl later on, but any password that was present initially will
    be lost.

    \sa FormattingOptions, toEncoded(), toString()
*/

QString QUrl::toDisplayString(FormattingOptions options) const
{
    return toString(options | RemovePassword);
}

/*!
    Returns the encoded representation of the URL if it's valid;
    otherwise an empty QByteArray is returned. The output can be
    customized by passing flags with \a options.

    The user info, path and fragment are all converted to UTF-8, and
    all non-ASCII characters are then percent encoded. The host name
    is encoded using Punycode.
*/
QByteArray QUrl::toEncoded(FormattingOptions options) const
{
    options &= ~(FullyDecoded | FullyEncoded);
    QString stringForm = toString(options | FullyEncoded);
    return stringForm.toLatin1();
}

/*!
    \fn QUrl QUrl::fromEncoded(const QByteArray &input, ParsingMode parsingMode)

    Parses \a input and returns the corresponding QUrl. \a input is
    assumed to be in encoded form, containing only ASCII characters.

    Parses the URL using \a parsingMode. See setUrl() for more information on
    this parameter. QUrl::DecodedMode is not permitted in this context.

    \sa toEncoded(), setUrl()
*/
QUrl QUrl::fromEncoded(const QByteArray &input, ParsingMode mode)
{
    return QUrl(QString::fromUtf8(input.constData(), input.size()), mode);
}

/*!
    Returns a decoded copy of \a input. \a input is first decoded from
    percent encoding, then converted from UTF-8 to unicode.
*/
QString QUrl::fromPercentEncoding(const QByteArray &input)
{
    QByteArray ba = QByteArray::fromPercentEncoding(input);
    return QString::fromUtf8(ba, ba.size());
}

/*!
    Returns an encoded copy of \a input. \a input is first converted
    to UTF-8, and all ASCII-characters that are not in the unreserved group
    are percent encoded. To prevent characters from being percent encoded
    pass them to \a exclude. To force characters to be percent encoded pass
    them to \a include.

    Unreserved is defined as:
       ALPHA / DIGIT / "-" / "." / "_" / "~"

    \snippet code/src_corelib_io_qurl.cpp 6
*/
QByteArray QUrl::toPercentEncoding(const QString &input, const QByteArray &exclude, const QByteArray &include)
{
    return input.toUtf8().toPercentEncoding(exclude, include);
}

/*!
    \internal
    \since 5.0
    Used in the setEncodedXXX compatibility functions. Converts \a ba to
    QString form.
*/
QString QUrl::fromEncodedComponent_helper(const QByteArray &ba)
{
    return qt_urlRecodeByteArray(ba);
}

/*!
    \fn QByteArray QUrl::toPunycode(const QString &uc)
    \obsolete
    Returns a \a uc in Punycode encoding.

    Punycode is a Unicode encoding used for internationalized domain
    names, as defined in RFC3492. If you want to convert a domain name from
    Unicode to its ASCII-compatible representation, use toAce().
*/

/*!
    \fn QString QUrl::fromPunycode(const QByteArray &pc)
    \obsolete
    Returns the Punycode decoded representation of \a pc.

    Punycode is a Unicode encoding used for internationalized domain
    names, as defined in RFC3492. If you want to convert a domain from
    its ASCII-compatible encoding to the Unicode representation, use
    fromAce().
*/

/*!
    \since 4.2

    Returns the Unicode form of the given domain name
    \a domain, which is encoded in the ASCII Compatible Encoding (ACE).
    The result of this function is considered equivalent to \a domain.

    If the value in \a domain cannot be encoded, it will be converted
    to QString and returned.

    The ASCII Compatible Encoding (ACE) is defined by RFC 3490, RFC 3491
    and RFC 3492. It is part of the Internationalizing Domain Names in
    Applications (IDNA) specification, which allows for domain names
    (like \c "example.com") to be written using international
    characters.
*/
QString QUrl::fromAce(const QByteArray &domain)
{
    return qt_ACE_do(QString::fromLatin1(domain), NormalizeAce);
}

/*!
    \since 4.2

    Returns the ASCII Compatible Encoding of the given domain name \a domain.
    The result of this function is considered equivalent to \a domain.

    The ASCII-Compatible Encoding (ACE) is defined by RFC 3490, RFC 3491
    and RFC 3492. It is part of the Internationalizing Domain Names in
    Applications (IDNA) specification, which allows for domain names
    (like \c "example.com") to be written using international
    characters.

    This function return an empty QByteArra if \a domain is not a valid
    hostname. Note, in particular, that IPv6 literals are not valid domain
    names.
*/
QByteArray QUrl::toAce(const QString &domain)
{
    QString result = qt_ACE_do(domain, ToAceOnly);
    return result.toLatin1();
}

/*!
    \internal

    Returns true if this URL is "less than" the given \a url. This
    provides a means of ordering URLs.
*/
bool QUrl::operator <(const QUrl &url) const
{
    if (!d || !url.d) {
        bool thisIsEmpty = !d || d->isEmpty();
        bool thatIsEmpty = !url.d || url.d->isEmpty();

        // sort an empty URL first
        return thisIsEmpty && !thatIsEmpty;
    }

    int cmp;
    cmp = d->scheme.compare(url.d->scheme);
    if (cmp != 0)
        return cmp < 0;

    cmp = d->userName.compare(url.d->userName);
    if (cmp != 0)
        return cmp < 0;

    cmp = d->password.compare(url.d->password);
    if (cmp != 0)
        return cmp < 0;

    cmp = d->host.compare(url.d->host);
    if (cmp != 0)
        return cmp < 0;

    if (d->port != url.d->port)
        return d->port < url.d->port;

    cmp = d->path.compare(url.d->path);
    if (cmp != 0)
        return cmp < 0;

    if (d->hasQuery() != url.d->hasQuery())
        return url.d->hasQuery();

    cmp = d->query.compare(url.d->query);
    if (cmp != 0)
        return cmp < 0;

    if (d->hasFragment() != url.d->hasFragment())
        return url.d->hasFragment();

    cmp = d->fragment.compare(url.d->fragment);
    return cmp < 0;
}

/*!
    Returns true if this URL and the given \a url are equal;
    otherwise returns false.
*/
bool QUrl::operator ==(const QUrl &url) const
{
    if (!d && !url.d)
        return true;
    if (!d)
        return url.d->isEmpty();
    if (!url.d)
        return d->isEmpty();

    // Compare which sections are present, but ignore Host
    // which is set by parsing but not by construction, when empty.
    const int mask = QUrlPrivate::FullUrl & ~QUrlPrivate::Host;
    return (d->sectionIsPresent & mask) == (url.d->sectionIsPresent & mask) &&
            d->scheme == url.d->scheme &&
            d->userName == url.d->userName &&
            d->password == url.d->password &&
            d->host == url.d->host &&
            d->port == url.d->port &&
            d->path == url.d->path &&
            d->query == url.d->query &&
            d->fragment == url.d->fragment;
}

/*!
    Returns true if this URL and the given \a url are not equal;
    otherwise returns false.
*/
bool QUrl::operator !=(const QUrl &url) const
{
    return !(*this == url);
}

/*!
    Assigns the specified \a url to this object.
*/
QUrl &QUrl::operator =(const QUrl &url)
{
    if (!d) {
        if (url.d) {
            url.d->ref.ref();
            d = url.d;
        }
    } else {
        if (url.d)
            qAtomicAssign(d, url.d);
        else
            clear();
    }
    return *this;
}

/*!
    Assigns the specified \a url to this object.
*/
QUrl &QUrl::operator =(const QString &url)
{
    if (url.isEmpty()) {
        clear();
    } else {
        detach();
        d->parse(url, TolerantMode);
    }
    return *this;
}

/*!
    \fn void QUrl::swap(QUrl &other)
    \since 4.8

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

/*!
    \internal

    Forces a detach.
*/
void QUrl::detach()
{
    if (!d)
        d = new QUrlPrivate;
    else
        qAtomicDetach(d);
}

/*!
    \internal
*/
bool QUrl::isDetached() const
{
    return !d || d->ref.load() == 1;
}


/*!
    Returns a QUrl representation of \a localFile, interpreted as a local
    file. This function accepts paths separated by slashes as well as the
    native separator for this platform.

    This function also accepts paths with a doubled leading slash (or
    backslash) to indicate a remote file, as in
    "//servername/path/to/file.txt". Note that only certain platforms can
    actually open this file using QFile::open().

    \sa toLocalFile(), isLocalFile(), QDir::toNativeSeparators()
*/
QUrl QUrl::fromLocalFile(const QString &localFile)
{
    QUrl url;
    url.setScheme(fileScheme());
    QString deslashified = QDir::fromNativeSeparators(localFile);

    // magic for drives on windows
    if (deslashified.length() > 1 && deslashified.at(1) == QLatin1Char(':') && deslashified.at(0) != QLatin1Char('/')) {
        deslashified.prepend(QLatin1Char('/'));
    } else if (deslashified.startsWith(QLatin1String("//"))) {
        // magic for shared drive on windows
        int indexOfPath = deslashified.indexOf(QLatin1Char('/'), 2);
        url.setHost(deslashified.mid(2, indexOfPath - 2));
        if (indexOfPath > 2)
            deslashified = deslashified.right(deslashified.length() - indexOfPath);
        else
            deslashified.clear();
    }

    url.setPath(deslashified, DecodedMode);
    return url;
}

/*!
    Returns the path of this URL formatted as a local file path. The path
    returned will use forward slashes, even if it was originally created
    from one with backslashes.

    If this URL contains a non-empty hostname, it will be encoded in the
    returned value in the form found on SMB networks (for example,
    "//servername/path/to/file.txt").

    Note: if the path component of this URL contains a non-UTF-8 binary
    sequence (such as %80), the behaviour of this function is undefined.

    \sa fromLocalFile(), isLocalFile()
*/
QString QUrl::toLocalFile() const
{
    // the call to isLocalFile() also ensures that we're parsed
    if (!isLocalFile())
        return QString();

    QString tmp;
    QString ourPath = path(QUrl::FullyDecoded);

    // magic for shared drive on windows
    if (!d->host.isEmpty()) {
        tmp = QStringLiteral("//") + host() + (ourPath.length() > 0 && ourPath.at(0) != QLatin1Char('/')
                                               ? QLatin1Char('/') + ourPath :  ourPath);
    } else {
        tmp = ourPath;
#ifdef Q_OS_WIN
        // magic for drives on windows
        if (ourPath.length() > 2 && ourPath.at(0) == QLatin1Char('/') && ourPath.at(2) == QLatin1Char(':'))
            tmp.remove(0, 1);
#endif
    }
    return tmp;
}

/*!
    \since 4.8
    Returns true if this URL is pointing to a local file path. A URL is a
    local file path if the scheme is "file".

    Note that this function considers URLs with hostnames to be local file
    paths, even if the eventual file path cannot be opened with
    QFile::open().

    \sa fromLocalFile(), toLocalFile()
*/
bool QUrl::isLocalFile() const
{
    if (!d) return false;

    if (d->scheme != fileScheme())
        return false;   // not file
    return true;
}

/*!
    Returns true if this URL is a parent of \a childUrl. \a childUrl is a child
    of this URL if the two URLs share the same scheme and authority,
    and this URL's path is a parent of the path of \a childUrl.
*/
bool QUrl::isParentOf(const QUrl &childUrl) const
{
    QString childPath = childUrl.path();

    if (!d)
        return ((childUrl.scheme().isEmpty())
            && (childUrl.authority().isEmpty())
            && childPath.length() > 0 && childPath.at(0) == QLatin1Char('/'));

    QString ourPath = path();

    return ((childUrl.scheme().isEmpty() || d->scheme == childUrl.scheme())
            && (childUrl.authority().isEmpty() || authority() == childUrl.authority())
            &&  childPath.startsWith(ourPath)
            && ((ourPath.endsWith(QLatin1Char('/')) && childPath.length() > ourPath.length())
                || (!ourPath.endsWith(QLatin1Char('/'))
                    && childPath.length() > ourPath.length() && childPath.at(ourPath.length()) == QLatin1Char('/'))));
}


#ifndef QT_NO_DATASTREAM
/*! \relates QUrl

    Writes url \a url to the stream \a out and returns a reference
    to the stream.

    \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
*/
QDataStream &operator<<(QDataStream &out, const QUrl &url)
{
    QByteArray u;
    if (url.isValid())
        u = url.toEncoded();
    out << u;
    return out;
}

/*! \relates QUrl

    Reads a url into \a url from the stream \a in and returns a
    reference to the stream.

    \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
*/
QDataStream &operator>>(QDataStream &in, QUrl &url)
{
    QByteArray u;
    in >> u;
    url.setUrl(QString::fromLatin1(u));
    return in;
}
#endif // QT_NO_DATASTREAM

#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug d, const QUrl &url)
{
    d.maybeSpace() << "QUrl(" << url.toDisplayString() << ')';
    return d.space();
}
#endif

static QString errorMessage(QUrlPrivate::ErrorCode errorCode, const QString &errorSource, int errorPosition)
{
    QChar c = uint(errorPosition) < uint(errorSource.length()) ?
                errorSource.at(errorPosition) : QChar(QChar::Null);

    switch (errorCode) {
    case QUrlPrivate::NoError:
        Q_ASSERT_X(false, "QUrl::errorString",
                   "Impossible: QUrl::errorString should have treated this condition");
        Q_UNREACHABLE();
        return QString();

    case QUrlPrivate::InvalidSchemeError: {
        QString msg = QStringLiteral("Invalid scheme (character '%1' not permitted)");
        return msg.arg(c);
    }

    case QUrlPrivate::InvalidUserNameError:
        return QString(QStringLiteral("Invalid user name (character '%1' not permitted)"))
                .arg(c);

    case QUrlPrivate::InvalidPasswordError:
        return QString(QStringLiteral("Invalid password (character '%1' not permitted)"))
                .arg(c);

    case QUrlPrivate::InvalidRegNameError:
        if (errorPosition != -1)
            return QString(QStringLiteral("Invalid hostname (character '%1' not permitted)"))
                    .arg(c);
        else
            return QStringLiteral("Invalid hostname (contains invalid characters)");
    case QUrlPrivate::InvalidIPv4AddressError:
        return QString(); // doesn't happen yet
    case QUrlPrivate::InvalidIPv6AddressError:
        return QStringLiteral("Invalid IPv6 address");
    case QUrlPrivate::InvalidIPvFutureError:
        return QStringLiteral("Invalid IPvFuture address");
    case QUrlPrivate::HostMissingEndBracket:
        return QStringLiteral("Expected ']' to match '[' in hostname");

    case QUrlPrivate::InvalidPortError:
        return QStringLiteral("Invalid port or port number out of range");
    case QUrlPrivate::PortEmptyError:
        return QStringLiteral("Port field was empty");

    case QUrlPrivate::InvalidPathError:
        return QString(QStringLiteral("Invalid path (character '%1' not permitted)"))
                .arg(c);

    case QUrlPrivate::InvalidQueryError:
        return QString(QStringLiteral("Invalid query (character '%1' not permitted)"))
                .arg(c);

    case QUrlPrivate::InvalidFragmentError:
        return QString(QStringLiteral("Invalid fragment (character '%1' not permitted)"))
                .arg(c);

    case QUrlPrivate::AuthorityPresentAndPathIsRelative:
        return QStringLiteral("Path component is relative and authority is present");
    case QUrlPrivate::RelativeUrlPathContainsColonBeforeSlash:
        return QStringLiteral("Relative URL's path component contains ':' before any '/'");
    }

    Q_ASSERT_X(false, "QUrl::errorString", "Cannot happen, unknown error");
    Q_UNREACHABLE();
    return QString();
}

static inline void appendComponentIfPresent(QString &msg, bool present, const char *componentName,
                                            const QString &component)
{
    if (present) {
        msg += QLatin1String(componentName);
        msg += QLatin1Char('"');
        msg += component;
        msg += QLatin1String("\",");
    }
}

/*!
    \since 4.2

    Returns an error message if the last operation that modified this QUrl
    object ran into a parsing error. If no error was detected, this function
    returns an empty string and isValid() returns true.

    The error message returned by this function is technical in nature and may
    not be understood by end users. It is mostly useful to developers trying to
    understand why QUrl will not accept some input.

    \sa QUrl::ParsingMode
*/
QString QUrl::errorString() const
{
    if (!d)
        return QString();

    QString errorSource;
    int errorPosition;
    QUrlPrivate::ErrorCode errorCode = d->validityError(&errorSource, &errorPosition);
    if (errorCode == QUrlPrivate::NoError)
        return QString();

    QString msg = errorMessage(errorCode, errorSource, errorPosition);
    msg += QLatin1String("; source was \"");
    msg += errorSource;
    msg += QLatin1String("\";");
    appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::Scheme,
                             " scheme = ", d->scheme);
    appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::UserInfo,
                             " userinfo = ", userInfo());
    appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::Host,
                             " host = ", d->host);
    appendComponentIfPresent(msg, d->port != -1,
                             " port = ", QString::number(d->port));
    appendComponentIfPresent(msg, !d->path.isEmpty(),
                             " path = ", d->path);
    appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::Query,
                             " query = ", d->query);
    appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::Fragment,
                             " fragment = ", d->fragment);
    if (msg.endsWith(QLatin1Char(',')))
        msg.chop(1);
    return msg;
}

/*!
    \since 5.1

    Converts a list of \a urls into a list of QStrings, using toString(\a options).
*/
QStringList QUrl::toStringList(const QList<QUrl> &urls, FormattingOptions options)
{
    QStringList lst;
    lst.reserve(urls.size());
    foreach (const QUrl &url, urls)
        lst.append(url.toString(options));
    return lst;

}

/*!
    \since 5.1

    Converts a list of strings representing \a urls into a list of urls, using QUrl(str, \a mode).
    Note that this means all strings must be urls, not for instance local paths.
*/
QList<QUrl> QUrl::fromStringList(const QStringList &urls, ParsingMode mode)
{
    QList<QUrl> lst;
    lst.reserve(urls.size());
    foreach (const QString &str, urls) {
        lst.append(QUrl(str, mode));
    }
    return lst;
}

/*!
    \typedef QUrl::DataPtr
    \internal
*/

/*!
    \fn DataPtr &QUrl::data_ptr()
    \internal
*/

/*!
    Returns the hash value for the \a url. If specified, \a seed is used to
    initialize the hash.

    \relates QHash
    \since 5.0
*/
uint qHash(const QUrl &url, uint seed) Q_DECL_NOTHROW
{
    if (!url.d)
        return qHash(-1, seed); // the hash of an unset port (-1)

    return qHash(url.d->scheme) ^
            qHash(url.d->userName) ^
            qHash(url.d->password) ^
            qHash(url.d->host) ^
            qHash(url.d->port, seed) ^
            qHash(url.d->path) ^
            qHash(url.d->query) ^
            qHash(url.d->fragment);
}

static QUrl adjustFtpPath(QUrl url)
{
    if (url.scheme() == ftpScheme()) {
        QString path = url.path();
        if (path.startsWith(QLatin1String("//")))
            url.setPath(QLatin1String("/%2F") + path.midRef(2));
    }
    return url;
}


// The following code has the following copyright:
/*
   Copyright (C) Research In Motion Limited 2009. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Research In Motion Limited nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Research In Motion Limited ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Research In Motion Limited BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/


/*!
    Returns a valid URL from a user supplied \a userInput string if one can be
    deducted. In the case that is not possible, an invalid QUrl() is returned.

    \since 4.6

    Most applications that can browse the web, allow the user to input a URL
    in the form of a plain string. This string can be manually typed into
    a location bar, obtained from the clipboard, or passed in via command
    line arguments.

    When the string is not already a valid URL, a best guess is performed,
    making various web related assumptions.

    In the case the string corresponds to a valid file path on the system,
    a file:// URL is constructed, using QUrl::fromLocalFile().

    If that is not the case, an attempt is made to turn the string into a
    http:// or ftp:// URL. The latter in the case the string starts with
    'ftp'. The result is then passed through QUrl's tolerant parser, and
    in the case or success, a valid QUrl is returned, or else a QUrl().

    \section1 Examples:

    \list
    \li qt.nokia.com becomes http://qt.nokia.com
    \li ftp.qt-project.org becomes ftp://ftp.qt-project.org
    \li hostname becomes http://hostname
    \li /home/user/test.html becomes file:///home/user/test.html
    \endlist
*/
QUrl QUrl::fromUserInput(const QString &userInput)
{
    QString trimmedString = userInput.trimmed();

    // Check first for files, since on Windows drive letters can be interpretted as schemes
    if (QDir::isAbsolutePath(trimmedString))
        return QUrl::fromLocalFile(trimmedString);

    QUrl url = QUrl(trimmedString, QUrl::TolerantMode);
    QUrl urlPrepended = QUrl(QStringLiteral("http://") + trimmedString, QUrl::TolerantMode);

    // Check the most common case of a valid url with a scheme
    // We check if the port would be valid by adding the scheme to handle the case host:port
    // where the host would be interpretted as the scheme
    if (url.isValid()
        && !url.scheme().isEmpty()
        && urlPrepended.port() == -1)
        return adjustFtpPath(url);

    // Else, try the prepended one and adjust the scheme from the host name
    if (urlPrepended.isValid() && (!urlPrepended.host().isEmpty() || !urlPrepended.path().isEmpty()))
    {
        int dotIndex = trimmedString.indexOf(QLatin1Char('.'));
        const QString hostscheme = trimmedString.left(dotIndex).toLower();
        if (hostscheme == ftpScheme())
            urlPrepended.setScheme(ftpScheme());
        return adjustFtpPath(urlPrepended);
    }

    return QUrl();
}
// end of BSD code

QT_END_NAMESPACE