This file is indexed.

/usr/include/d2/4.6/std/path.d is in libphobos2-4.6-dev 0.29.1-4.6.3-1ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

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

/** This module is used to manipulate _path strings.

    All functions, with the exception of $(LREF expandTilde) (and in some
    cases $(LREF absolutePath) and $(LREF relativePath)), are pure
    string manipulation functions; they don't depend on any state outside
    the program, nor do they perform any actual file system actions.
    This has the consequence that the module does not make any distinction
    between a _path that points to a directory and a _path that points to a
    file, and it does not know whether or not the object pointed to by the
    _path actually exists in the file system.
    To differentiate between these cases, use $(XREF file,isDir) and
    $(XREF file,exists).

    Note that on Windows, both the backslash ($(D '\')) and the slash ($(D '/'))
    are in principle valid directory separators.  This module treats them
    both on equal footing, but in cases where a $(I new) separator is
    added, a backslash will be used.  Furthermore, the $(LREF buildNormalizedPath)
    function will replace all slashes with backslashes on that platform.

    In general, the functions in this module assume that the input paths
    are well-formed.  (That is, they should not contain invalid characters,
    they should follow the file system's _path format, etc.)  The result
    of calling a function on an ill-formed _path is undefined.  When there
    is a chance that a _path or a file name is invalid (for instance, when it
    has been input by the user), it may sometimes be desirable to use the
    $(LREF isValidFilename) and $(LREF isValidPath) functions to check
    this.

    Authors:
        Lars Tandle Kyllingstad,
        $(WEB digitalmars.com, Walter Bright),
        Grzegorz Adam Hankiewicz,
        Thomas Kühne,
        $(WEB erdani.org, Andrei Alexandrescu)
    Copyright:
        Copyright (c) 2000–2011, the authors. All rights reserved.
    License:
        $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0)
    Source:
        $(PHOBOSSRC std/_path.d)
    Macros:
        WIKI = Phobos/StdPath
*/
module std.path;


import std.algorithm;
import std.array;
import std.conv;
import std.file: getcwd;
import std.string;
import std.traits;

version(Posix)
{
    import core.exception;
    import core.stdc.errno;
    import core.sys.posix.pwd;
    import core.sys.posix.stdlib;
}




/** String used to separate directory names in a path.  Under
    POSIX this is a slash, under Windows a backslash.
*/
version(Posix)          enum string dirSeparator = "/";
else version(Windows)   enum string dirSeparator = "\\";
else static assert (0, "unsupported platform");




/** Path separator string.  A colon under POSIX, a semicolon
    under Windows.
*/
version(Posix)          enum string pathSeparator = ":";
else version(Windows)   enum string pathSeparator = ";";
else static assert (0, "unsupported platform");




/** Determine whether the given character is a directory separator.

    On Windows, this includes both $(D '\') and $(D '/').
    On POSIX, it's just $(D '/').
*/
bool isDirSeparator(dchar c)  @safe pure nothrow
{
    if (c == '/') return true;
    version(Windows) if (c == '\\') return true;
    return false;
}


/*  Determine whether the given character is a drive separator.

    On Windows, this is true if c is the ':' character that separates
    the drive letter from the rest of the path.  On POSIX, this always
    returns false.
*/
private bool isDriveSeparator(dchar c)  @safe pure nothrow
{
    version(Windows) return c == ':';
    else return false;
}


/*  Combines the isDirSeparator and isDriveSeparator tests. */
version(Windows) private bool isSeparator(dchar c)  @safe pure nothrow
{
    return isDirSeparator(c) || isDriveSeparator(c);
}
version(Posix) private alias isDirSeparator isSeparator;


/*  Helper function that determines the position of the last
    drive/directory separator in a string.  Returns -1 if none
    is found.
*/
private sizediff_t lastSeparator(C)(in C[] path)  @safe pure nothrow
    if (isSomeChar!C)
{
    auto i = (cast(sizediff_t) path.length) - 1;
    while (i >= 0 && !isSeparator(path[i])) --i;
    return i;
}


version (Windows)
{
    private bool isUNC(C)(in C[] path) @safe pure nothrow  if (isSomeChar!C)
    {
        return path.length >= 3 && isDirSeparator(path[0]) && isDirSeparator(path[1])
            && !isDirSeparator(path[2]);
    }

    private sizediff_t uncRootLength(C)(in C[] path) @safe pure nothrow  if (isSomeChar!C)
        in { assert (isUNC(path)); }
        body
    {
        sizediff_t i = 3;
        while (i < path.length && !isDirSeparator(path[i])) ++i;
        if (i < path.length)
        {
            auto j = i;
            do { ++j; } while (j < path.length && isDirSeparator(path[j]));
            if (j < path.length)
            {
                do { ++j; } while (j < path.length && !isDirSeparator(path[j]));
                i = j;
            }
        }
        return i;
    }

    private bool hasDrive(C)(in C[] path)  @safe pure nothrow  if (isSomeChar!C)
    {
        return path.length >= 2 && isDriveSeparator(path[1]);
    }

    private bool isDriveRoot(C)(in C[] path)  @safe pure nothrow  if (isSomeChar!C)
    {
        return path.length >= 3 && isDriveSeparator(path[1])
            && isDirSeparator(path[2]);
    }
}


/*  Helper functions that strip leading/trailing slashes and backslashes
    from a path.
*/
private C[] ltrimDirSeparators(C)(C[] path)  @safe pure nothrow
    if (isSomeChar!C)
{
    int i = 0;
    while (i < path.length && isDirSeparator(path[i])) ++i;
    return path[i .. $];
}

private C[] rtrimDirSeparators(C)(C[] path)  @safe pure nothrow
    if (isSomeChar!C)
{
    auto i = (cast(sizediff_t) path.length) - 1;
    while (i >= 0 && isDirSeparator(path[i])) --i;
    return path[0 .. i+1];
}

private C[] trimDirSeparators(C)(C[] path)  @safe pure nothrow
    if (isSomeChar!C)
{
    return ltrimDirSeparators(rtrimDirSeparators(path));
}




/** This $(D enum) is used as a template argument to functions which
    compare file names, and determines whether the comparison is
    case sensitive or not.
*/
enum CaseSensitive : bool
{
    /// File names are case insensitive
    no = false,

    /// File names are case sensitive
    yes = true,

    /** The default (or most common) setting for the current platform.
        That is, $(D no) on Windows and Mac OS X, and $(D yes) on all
        POSIX systems except OS X (Linux, *BSD, etc.).
    */
    osDefault = osDefaultCaseSensitivity
}
version (Windows)    private enum osDefaultCaseSensitivity = false;
else version (OSX)   private enum osDefaultCaseSensitivity = false;
else version (Posix) private enum osDefaultCaseSensitivity = true;
else static assert (0);




/** Returns the name of a file, without any leading directory
    and with an optional suffix chopped off.

    If $(D suffix) is specified, it will be compared to $(D path)
    using $(D filenameCmp!cs),
    where $(D cs) is an optional template parameter determining whether
    the comparison is case sensitive or not.  See the
    $(LREF filenameCmp) documentation for details.

    Examples:
    ---
    assert (baseName("dir/file.ext")         == "file.ext");
    assert (baseName("dir/file.ext", ".ext") == "file");
    assert (baseName("dir/file.ext", ".xyz") == "file.ext");
    assert (baseName("dir/filename", "name") == "file");
    assert (baseName("dir/subdir/")          == "subdir");

    version (Windows)
    {
        assert (baseName(`d:file.ext`)      == "file.ext");
        assert (baseName(`d:\dir\file.ext`) == "file.ext");
    }
    ---

    Note:
    This function only strips away the specified suffix.  If you want
    to remove the extension from a path, regardless of what the extension
    is, use $(LREF stripExtension).
    If you want the filename without leading directories and without
    an extension, combine the functions like this:
    ---
    assert (baseName(stripExtension("dir/file.ext")) == "file");
    ---

    Standards:
    This function complies with
    $(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html,
    the POSIX requirements for the 'basename' shell utility)
    (with suitable adaptations for Windows paths).
*/
C[] baseName(C)(C[] path)  //TODO: @safe pure nothrow (because of to())
    if (isSomeChar!C)
{
    auto p1 = stripDrive(path);
    if (p1.empty)
    {
        version (Windows)
        {
            if (isUNC(path)) return to!(typeof(return))(dirSeparator);
        }
        return null;
    }

    auto p2 = rtrimDirSeparators(p1);
    if (p2.empty) return p1[0 .. 1];

    return p2[lastSeparator(p2)+1 .. $];
}

/// ditto
C[] baseName(CaseSensitive cs = CaseSensitive.osDefault, C, C1)
    (C[] path, C1[] suffix)
    //TODO: @safe pure nothrow (because of the other baseName())
    if (isSomeChar!C && isSomeChar!C1)
{
    auto p = baseName(path);
    if (p.length > suffix.length
        && filenameCmp!cs(p[$-suffix.length .. $], suffix) == 0)
    {
        return p[0 .. $-suffix.length];
    }
    else return p;
}


unittest
{
    assert (baseName("").empty);
    assert (baseName("file.ext"w) == "file.ext");
    assert (baseName("file.ext"d, ".ext") == "file");
    assert (baseName("file", "file"w.dup) == "file");
    assert (baseName("dir/file.ext"d.dup) == "file.ext");
    assert (baseName("dir/file.ext", ".ext"d) == "file");
    assert (baseName("dir/file"w, "file"d) == "file");
    assert (baseName("dir///subdir////") == "subdir");
    assert (baseName("dir/subdir.ext/", ".ext") == "subdir");
    assert (baseName("dir/subdir/".dup, "subdir") == "subdir");
    assert (baseName("/"w.dup) == "/");
    assert (baseName("//"d.dup) == "/");
    assert (baseName("///") == "/");

    assert (baseName!(CaseSensitive.yes)("file.ext", ".EXT") == "file.ext");
    assert (baseName!(CaseSensitive.no)("file.ext", ".EXT") == "file");

    version (Windows)
    {
        assert (baseName(`dir\file.ext`) == `file.ext`);
        assert (baseName(`dir\file.ext`, `.ext`) == `file`);
        assert (baseName(`dir\file`, `file`) == `file`);
        assert (baseName(`d:file.ext`) == `file.ext`);
        assert (baseName(`d:file.ext`, `.ext`) == `file`);
        assert (baseName(`d:file`, `file`) == `file`);
        assert (baseName(`dir\\subdir\\\`) == `subdir`);
        assert (baseName(`dir\subdir.ext\`, `.ext`) == `subdir`);
        assert (baseName(`dir\subdir\`, `subdir`) == `subdir`);
        assert (baseName(`\`) == `\`);
        assert (baseName(`\\`) == `\`);
        assert (baseName(`\\\`) == `\`);
        assert (baseName(`d:\`) == `\`);
        assert (baseName(`d:`).empty);
        assert (baseName(`\\server\share\file`) == `file`);
        assert (baseName(`\\server\share\`) == `\`);
        assert (baseName(`\\server\share`) == `\`);
    }

    assert (baseName(stripExtension("dir/file.ext")) == "file");

    static assert (baseName("dir/file.ext") == "file.ext");
    static assert (baseName("dir/file.ext", ".ext") == "file");
}




/** Returns the directory part of a path.  On Windows, this
    includes the drive letter if present.

    Examples:
    ---
    assert (dirName("file")        == ".");
    assert (dirName("dir/file")    == "dir");
    assert (dirName("/file")       == "/");
    assert (dirName("dir/subdir/") == "dir");

    version (Windows)
    {
        assert (dirName("d:file")      == "d:");
        assert (dirName(`d:\dir\file`) == `d:\dir`);
        assert (dirName(`d:\file`)     == `d:\`);
        assert (dirName(`dir\subdir\`) == `dir`);
    }
    ---

    Standards:
    This function complies with
    $(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html,
    the POSIX requirements for the 'dirname' shell utility)
    (with suitable adaptations for Windows paths).
*/
C[] dirName(C)(C[] path)  //TODO: @safe pure nothrow (because of to())
    if (isSomeChar!C)
{
    enum currentDir = cast(C[]) ".";
    if (path.empty) return currentDir;

    auto p = rtrimDirSeparators(path);
    if (p.empty) return path[0 .. 1];

    version (Windows)
    {
        if (isUNC(p) && uncRootLength(p) == p.length)
            return p;
        if (p.length == 2 && isDriveSeparator(p[1]) && path.length > 2)
            return path[0 .. 3];
    }

    auto i = lastSeparator(p);
    if (i == -1) return to!(typeof(return))(".");
    if (i == 0) return p[0 .. 1];

    version (Windows)
    {
        // If the directory part is either d: or d:\, don't
        // chop off the last symbol.
        if (isDriveSeparator(p[i]) || isDriveSeparator(p[i-1]))
            return p[0 .. i+1];
    }

    // Remove any remaining trailing (back)slashes.
    return rtrimDirSeparators(p[0 .. i]);
}


unittest
{
    assert (dirName("") == ".");
    assert (dirName("file"w) == ".");
    assert (dirName("dir/"d) == ".");
    assert (dirName("dir///") == ".");
    assert (dirName("dir/file"w.dup) == "dir");
    assert (dirName("dir///file"d.dup) == "dir");
    assert (dirName("dir/subdir/") == "dir");
    assert (dirName("/dir/file"w) == "/dir");
    assert (dirName("/file"d) == "/");
    assert (dirName("/") == "/");
    assert (dirName("///") == "/");

    version (Windows)
    {
        assert (dirName(`dir\`) == `.`);
        assert (dirName(`dir\\\`) == `.`);
        assert (dirName(`dir\file`) == `dir`);
        assert (dirName(`dir\\\file`) == `dir`);
        assert (dirName(`dir\subdir\`) == `dir`);
        assert (dirName(`\dir\file`) == `\dir`);
        assert (dirName(`\file`) == `\`);
        assert (dirName(`\`) == `\`);
        assert (dirName(`\\\`) == `\`);
        assert (dirName(`d:`) == `d:`);
        assert (dirName(`d:file`) == `d:`);
        assert (dirName(`d:\`) == `d:\`);
        assert (dirName(`d:\file`) == `d:\`);
        assert (dirName(`d:\dir\file`) == `d:\dir`);
        assert (dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
        assert (dirName(`\\server\share\file`) == `\\server\share`);
        assert (dirName(`\\server\share\`) == `\\server\share`);
        assert (dirName(`\\server\share`) == `\\server\share`);
    }

    static assert (dirName("dir/file") == "dir");
}




/** Returns the root directory of the specified path, or $(D null) if the
    path is not rooted.

    Examples:
    ---
    assert (rootName("foo") is null);
    assert (rootName("/foo") == "/");

    version (Windows)
    {
        assert (rootName(`\foo`) == `\`);
        assert (rootName(`c:\foo`) == `c:\`);
        assert (rootName(`\\server\share\foo`) == `\\server\share`);
    }
    ---
*/
C[] rootName(C)(C[] path)  @safe pure nothrow  if (isSomeChar!C)
{
    if (path.empty) return null;

    version (Posix)
    {
        if (isDirSeparator(path[0])) return path[0 .. 1];
    }
    else version (Windows)
    {
        if (isDirSeparator(path[0]))
        {
            if (isUNC(path)) return path[0 .. uncRootLength(path)];
            else return path[0 .. 1];
        }
        else if (path.length >= 3 && isDriveSeparator(path[1]) &&
            isDirSeparator(path[2]))
        {
            return path[0 .. 3];
        }
    }
    else static assert (0, "unsupported platform");

    assert (!isRooted(path));
    return null;
}


unittest
{
    assert (rootName("") is null);
    assert (rootName("foo") is null);
    assert (rootName("/") == "/");
    assert (rootName("/foo/bar") == "/");

    version (Windows)
    {
        assert (rootName("d:foo") is null);
        assert (rootName(`d:\foo`) == `d:\`);
        assert (rootName(`\\server\share\foo`) == `\\server\share`);
        assert (rootName(`\\server\share`) == `\\server\share`);
    }
}




/** Returns the drive of a path, or $(D null) if the drive
    is not specified.  In the case of UNC paths, the network share
    is returned.

    Always returns $(D null) on POSIX.

    Examples:
    ---
    version (Windows)
    {
        assert (driveName(`d:\file`) == "d:");
        assert (driveName(`\\server\share\file`) == `\\server\share`);
        assert (driveName(`dir\file`).empty);
    }
    ---
*/
C[] driveName(C)(C[] path)  @safe pure //TODO: nothrow (because of stripLeft())
    if (isSomeChar!C)
{
    version (Windows)
    {
        if (hasDrive(path))
            return path[0 .. 2];
        else if (isUNC(path))
            return path[0 .. uncRootLength(path)];
    }
    return null;
}


unittest
{
    version (Posix)  assert (driveName("c:/foo").empty);
    version (Windows)
    {
        assert (driveName(`dir\file`).empty);
        assert (driveName(`d:file`) == "d:");
        assert (driveName(`d:\file`) == "d:");
        assert (driveName("d:") == "d:");
        assert (driveName(`\\server\share\file`) == `\\server\share`);
        assert (driveName(`\\server\share\`) == `\\server\share`);
        assert (driveName(`\\server\share`) == `\\server\share`);

        static assert (driveName(`d:\file`) == "d:");
    }
}




/** Strip the drive from a Windows path.  On POSIX, this is a noop.

    Example:
    ---
    version (Windows)
    {
        assert (stripDrive(`d:\dir\file`) == `\dir\file`);
        assert (stripDrive(`\\server\share\dir\file`) == `\dir\file`);
    }
    ---
*/
C[] stripDrive(C)(C[] path)  @safe pure nothrow  if (isSomeChar!C)
{
    version(Windows)
    {
        if (hasDrive(path))      return path[2 .. $];
        else if (isUNC(path))    return path[uncRootLength(path) .. $];
    }
    return path;
}


unittest
{
    version(Windows)
    {
        assert (stripDrive(`d:\dir\file`) == `\dir\file`);
        assert (stripDrive(`\\server\share\dir\file`) == `\dir\file`);
        static assert (stripDrive(`d:\dir\file`) == `\dir\file`);
    }
    version(Posix)
    {
        assert (stripDrive(`d:\dir\file`) == `d:\dir\file`);
    }
}




/*  Helper function that returns the position of the filename/extension
    separator dot in path.  If not found, returns -1.
*/
private sizediff_t extSeparatorPos(C)(in C[] path)  @safe pure nothrow
    if (isSomeChar!C)
{
    auto i = (cast(sizediff_t) path.length) - 1;
    while (i >= 0 && !isSeparator(path[i]))
    {
        if (path[i] == '.' && i > 0 && !isSeparator(path[i-1])) return i;
        --i;
    }
    return -1;
}




/** Get the _extension part of a file name, including the dot.

    If there is no _extension, $(D null) is returned.

    Examples:
    ---
    assert (extension("file").empty);
    assert (extension("file.ext")       == ".ext");
    assert (extension("file.ext1.ext2") == ".ext2");
    assert (extension("file.")          == ".");
    assert (extension(".file").empty);
    assert (extension(".file.ext")      == ".ext");
    ---
*/
C[] extension(C)(C[] path)  @safe pure nothrow  if (isSomeChar!C)
{
    auto i = extSeparatorPos(path);
    if (i == -1) return null;
    else return path[i .. $];
}


unittest
{
    assert (extension("file").empty);
    assert (extension("file.") == ".");
    assert (extension("file.ext"w) == ".ext");
    assert (extension("file.ext1.ext2"d) == ".ext2");
    assert (extension(".foo".dup).empty);
    assert (extension(".foo.ext"w.dup) == ".ext");

    assert (extension("dir/file"d.dup).empty);
    assert (extension("dir/file.") == ".");
    assert (extension("dir/file.ext") == ".ext");
    assert (extension("dir/file.ext1.ext2"w) == ".ext2");
    assert (extension("dir/.foo"d).empty);
    assert (extension("dir/.foo.ext".dup) == ".ext");

    version(Windows)
    {
        assert (extension(`dir\file`).empty);
        assert (extension(`dir\file.`) == ".");
        assert (extension(`dir\file.ext`) == `.ext`);
        assert (extension(`dir\file.ext1.ext2`) == `.ext2`);
        assert (extension(`dir\.foo`).empty);
        assert (extension(`dir\.foo.ext`) == `.ext`);

        assert (extension(`d:file`).empty);
        assert (extension(`d:file.`) == ".");
        assert (extension(`d:file.ext`) == `.ext`);
        assert (extension(`d:file.ext1.ext2`) == `.ext2`);
        assert (extension(`d:.foo`).empty);
        assert (extension(`d:.foo.ext`) == `.ext`);
    }

    static assert (extension("file").empty);
    static assert (extension("file.ext") == ".ext");
}




/** Return the path with the extension stripped off.

    Examples:
    ---
    assert (stripExtension("file")           == "file");
    assert (stripExtension("file.ext")       == "file");
    assert (stripExtension("file.ext1.ext2") == "file.ext1");
    assert (stripExtension("file.")          == "file");
    assert (stripExtension(".file")          == ".file");
    assert (stripExtension(".file.ext")      == ".file");
    assert (stripExtension("dir/file.ext")   == "dir/file");
    ---
*/
C[] stripExtension(C)(C[] path)  @safe pure nothrow  if (isSomeChar!C)
{
    auto i = extSeparatorPos(path);
    if (i == -1) return path;
    else return path[0 .. i];
}


unittest
{
    assert (stripExtension("file") == "file");
    assert (stripExtension("file.ext"w) == "file");
    assert (stripExtension("file.ext1.ext2"d) == "file.ext1");
    assert (stripExtension(".foo".dup) == ".foo");
    assert (stripExtension(".foo.ext"w.dup) == ".foo");

    assert (stripExtension("dir/file"d.dup) == "dir/file");
    assert (stripExtension("dir/file.ext") == "dir/file");
    assert (stripExtension("dir/file.ext1.ext2"w) == "dir/file.ext1");
    assert (stripExtension("dir/.foo"d) == "dir/.foo");
    assert (stripExtension("dir/.foo.ext".dup) == "dir/.foo");

    version(Windows)
    {
    assert (stripExtension("dir\\file") == "dir\\file");
    assert (stripExtension("dir\\file.ext") == "dir\\file");
    assert (stripExtension("dir\\file.ext1.ext2") == "dir\\file.ext1");
    assert (stripExtension("dir\\.foo") == "dir\\.foo");
    assert (stripExtension("dir\\.foo.ext") == "dir\\.foo");

    assert (stripExtension("d:file") == "d:file");
    assert (stripExtension("d:file.ext") == "d:file");
    assert (stripExtension("d:file.ext1.ext2") == "d:file.ext1");
    assert (stripExtension("d:.foo") == "d:.foo");
    assert (stripExtension("d:.foo.ext") == "d:.foo");
    }

    static assert (stripExtension("file") == "file");
    static assert (stripExtension("file.ext"w) == "file");
}




/** Set the extension of a filename.

    If the filename already has an extension, it is replaced.   If not, the
    extension is simply appended to the filename.  Including the dot in the
    extension is optional.

    This function normally allocates a new string (the possible exception
    being case when path is immutable and doesn't already have an extension).

    Examples:
    ---
    assert (setExtension("file", "ext")      == "file.ext");
    assert (setExtension("file", ".ext")     == "file.ext");
    assert (setExtension("file.old", "new")  == "file.new");
    assert (setExtension("file.old", ".new") == "file.new");
    ---
*/
immutable(Unqual!C1)[] setExtension(C1, C2)(in C1[] path, in C2[] ext)
    @trusted pure nothrow
    if (isSomeChar!C1 && !is(C1 == immutable) && is(Unqual!C1 == Unqual!C2))
{
    if (ext.length > 0 && ext[0] == '.')
        return cast(typeof(return))(stripExtension(path)~ext);
    else
        return cast(typeof(return))(stripExtension(path)~'.'~ext);
}

///ditto
immutable(C1)[] setExtension(C1, C2)(immutable(C1)[] path, const(C2)[] ext)
    @trusted pure nothrow
    if (isSomeChar!C1 && is(Unqual!C1 == Unqual!C2))
{
    // Optimised for the case where path is immutable and has no extension
    if (ext.length > 0 && ext[0] == '.') ext = ext[1 .. $];
    auto i = extSeparatorPos(path);
    if (i == -1)
    {
        path ~= '.';
        path ~= ext;
        return path;
    }
    else if (i == path.length - 1)
    {
        path ~= ext;
        return path;
    }
    else
    {
        return cast(typeof(return))(path[0 .. i+1] ~ ext);
    }
}


unittest
{
    assert (setExtension("file", "ext") == "file.ext");
    assert (setExtension("file"w, ".ext"w) == "file.ext");
    assert (setExtension("file."d, "ext"d) == "file.ext");
    assert (setExtension("file.", ".ext") == "file.ext");
    assert (setExtension("file.old"w, "new"w) == "file.new");
    assert (setExtension("file.old"d, ".new"d) == "file.new");

    assert (setExtension("file"w.dup, "ext"w) == "file.ext");
    assert (setExtension("file"w.dup, ".ext"w) == "file.ext");
    assert (setExtension("file."w, "ext"w.dup) == "file.ext");
    assert (setExtension("file."w, ".ext"w.dup) == "file.ext");
    assert (setExtension("file.old"d.dup, "new"d) == "file.new");
    assert (setExtension("file.old"d.dup, ".new"d) == "file.new");

    static assert (setExtension("file", "ext") == "file.ext");
    static assert (setExtension("file.old", "new") == "file.new");

    static assert (setExtension("file"w.dup, "ext"w) == "file.ext");
    static assert (setExtension("file.old"d.dup, "new"d) == "file.new");
}




/** Set the extension of a filename, but only if it doesn't
    already have one.

    Including the dot in the extension is optional.

    This function always allocates a new string, except in the case when
    path is immutable and already has an extension.

    Examples:
    ---
    assert (defaultExtension("file", "ext")      == "file.ext");
    assert (defaultExtension("file", ".ext")     == "file.ext");
    assert (defaultExtension("file.", "ext")     == "file.");
    assert (defaultExtension("file.old", "new")  == "file.old");
    assert (defaultExtension("file.old", ".new") == "file.old");
    ---
*/
immutable(Unqual!C1)[] defaultExtension(C1, C2)(in C1[] path, in C2[] ext)
    @trusted // (BUG 4850) pure (BUG 5700) nothrow
    if (isSomeChar!C1 && is(Unqual!C1 == Unqual!C2))
{
    auto i = extSeparatorPos(path);
    if (i == -1)
    {
        if (ext.length > 0 && ext[0] == '.')
            return cast(typeof(return))(path~ext);
        else
            return cast(typeof(return))(path~'.'~ext);
    }
    else return to!(typeof(return))(path);
}


unittest
{
    assert (defaultExtension("file", "ext") == "file.ext");
    assert (defaultExtension("file", ".ext") == "file.ext");
    assert (defaultExtension("file.", "ext")     == "file.");
    assert (defaultExtension("file.old", "new") == "file.old");
    assert (defaultExtension("file.old", ".new") == "file.old");

    assert (defaultExtension("file"w.dup, "ext"w) == "file.ext");
    assert (defaultExtension("file.old"d.dup, "new"d) == "file.old");

    static assert (defaultExtension("file", "ext") == "file.ext");
    static assert (defaultExtension("file.old", "new") == "file.old");

    static assert (defaultExtension("file"w.dup, "ext"w) == "file.ext");
    static assert (defaultExtension("file.old"d.dup, "new"d) == "file.old");
}




/** Joins one or more path components.

    The given path components are concatenated with each other,
    and if necessary, directory separators are inserted between
    them. If any of the path components are rooted (see
    $(LREF isRooted)) the preceding path components will be dropped.

    Examples:
    ---
    version (Posix)
    {
        assert (buildPath("foo", "bar", "baz") == "foo/bar/baz");
        assert (buildPath("/foo/", "bar")      == "/foo/bar");
        assert (buildPath("/foo", "/bar")      == "/bar");
    }

    version (Windows)
    {
        assert (buildPath("foo", "bar", "baz") == `foo\bar\baz`);
        assert (buildPath(`c:\foo`, "bar")    == `c:\foo\bar`);
        assert (buildPath("foo", `d:\bar`)    == `d:\bar`);
        assert (buildPath("foo", `\bar`)      == `\bar`);
    }
    ---
*/
immutable(C)[] buildPath(C)(const(C)[][] paths...)
    //TODO: @safe pure nothrow (because of reduce() and to())
    if (isSomeChar!C)
{
    static typeof(return) joinPaths(const(C)[] lhs, const(C)[] rhs)
        @trusted //TODO: pure nothrow (because of to())
    {
        if (rhs.empty) return to!(typeof(return))(lhs);
        if (lhs.empty || isRooted(rhs)) return to!(typeof(return))(rhs);
        if (isDirSeparator(lhs[$-1]) || isDirSeparator(rhs[0]))
            return cast(typeof(return))(lhs ~ rhs);
        else
            return cast(typeof(return))(lhs ~ dirSeparator ~ rhs);
    }

    return to!(typeof(return))(reduce!joinPaths(paths));
}


unittest
{
    version (Posix)
    {
        assert (buildPath("foo") == "foo");
        assert (buildPath("/foo/") == "/foo/");
        assert (buildPath("foo", "bar") == "foo/bar");
        assert (buildPath("foo", "bar", "baz") == "foo/bar/baz");
        assert (buildPath("foo/".dup, "bar") == "foo/bar");
        assert (buildPath("foo///", "bar".dup) == "foo///bar");
        assert (buildPath("/foo"w, "bar"w) == "/foo/bar");
        assert (buildPath("foo"w.dup, "/bar"w) == "/bar");
        assert (buildPath("foo"w, "bar/"w.dup) == "foo/bar/");
        assert (buildPath("/"d, "foo"d) == "/foo");
        assert (buildPath(""d.dup, "foo"d) == "foo");
        assert (buildPath("foo"d, ""d.dup) == "foo");
        assert (buildPath("foo", "bar".dup, "baz") == "foo/bar/baz");
        assert (buildPath("foo"w, "/bar"w, "baz"w.dup) == "/bar/baz");

        static assert (buildPath("foo", "bar", "baz") == "foo/bar/baz");
        static assert (buildPath("foo", "/bar", "baz") == "/bar/baz");
    }
    version (Windows)
    {
        assert (buildPath("foo") == "foo");
        assert (buildPath(`\foo/`) == `\foo/`);
        assert (buildPath("foo", "bar", "baz") == `foo\bar\baz`);
        assert (buildPath("foo", `\bar`) == `\bar`);
        assert (buildPath(`c:\foo`, "bar") == `c:\foo\bar`);
        assert (buildPath("foo"w, `d:\bar`w.dup) ==  `d:\bar`);

        static assert (buildPath("foo", "bar", "baz") == `foo\bar\baz`);
        static assert (buildPath("foo", `c:\bar`, "baz") == `c:\bar\baz`);
    }
}




/** Performs the same task as $(LREF buildPath),
    while at the same time resolving current/parent directory
    symbols ($(D ".") and $(D "..")) and removing superfluous
    directory separators.
    On Windows, slashes are replaced with backslashes.

    Note that this function does not resolve symbolic links.

    Examples:
    ---
    version (Posix)
    {
        assert (buildNormalizedPath("/foo/./bar/..//baz/") == "/foo/baz");
        assert (buildNormalizedPath("../foo/.") == "../foo");
        assert (buildNormalizedPath("/foo", "bar/baz/") == "/foo/bar/baz");
        assert (buildNormalizedPath("/foo", "/bar/..", "baz") == "/baz");
        assert (buildNormalizedPath("foo/./bar", "../../", "../baz") == "../baz");
        assert (buildNormalizedPath("/foo/./bar", "../../baz") == "/baz");
    }

    version (Windows)
    {
        assert (buildNormalizedPath(`c:\foo\.\bar/..\\baz\`) == `c:\foo\baz`);
        assert (buildNormalizedPath(`..\foo\.`) == `..\foo`);
        assert (buildNormalizedPath(`c:\foo`, `bar\baz\`) == `c:\foo\bar\baz`);
        assert (buildNormalizedPath(`c:\foo`, `bar/..`) == `c:\foo`);
        assert (buildNormalizedPath(`\\server\share\foo`, `..\bar`) == `\\server\share\bar`);
    }
    ---
*/
immutable(C)[] buildNormalizedPath(C)(const(C)[][] paths...)
    @trusted pure nothrow
    if (isSomeChar!C)
{
    // Check whether the resulting path will be absolute or rooted,
    // calculate its maximum length, and discard segments we won't use.
    typeof(paths[0]) rootElement;
    int numPaths = 0;
    bool seenAbsolute;
    size_t segmentLengthSum = 0;
    foreach (i; 0 .. paths.length)
    {
        auto p = paths[i];
        if (p.empty) continue;
        else if (isRooted(p))
        {
            immutable thisIsAbsolute = isAbsolute(p);
            if (thisIsAbsolute || !seenAbsolute)
            {
                if (thisIsAbsolute) seenAbsolute = true;
                rootElement = rootName(p);
                paths[0] = p[rootElement.length .. $];
                numPaths = 1;
                segmentLengthSum = paths[0].length;
            }
            else
            {
                paths[0] = p;
                numPaths = 1;
                segmentLengthSum = p.length;
            }
        }
        else
        {
            paths[numPaths++] = p;
            segmentLengthSum += p.length;
        }
    }
    if (rootElement.length + segmentLengthSum == 0) return null;
    paths = paths[0 .. numPaths];
    immutable rooted = !rootElement.empty;
    assert (rooted || !seenAbsolute); // absolute => rooted

    // Allocate memory for the resulting path, including room for
    // extra dir separators
    auto fullPath = new C[rootElement.length + segmentLengthSum + paths.length];

    // Copy the root element into fullPath, and let relPart be
    // the remaining slice.
    typeof(fullPath) relPart;
    if (rooted)
    {
        // For Windows, we also need to perform normalization on
        // the root element.
        version (Posix)
        {
            fullPath[0 .. rootElement.length] = rootElement[];
        }
        else version (Windows)
        {
            foreach (i, c; rootElement)
            {
                if (isDirSeparator(c))
                {
                    static assert (dirSeparator.length == 1);
                    fullPath[i] = dirSeparator[0];
                }
                else fullPath[i] = c;
            }
        }
        else static assert (0);

        // If the root element doesn't end with a dir separator,
        // we add one.
        if (!isDirSeparator(rootElement[$-1]))
        {
            static assert (dirSeparator.length == 1);
            fullPath[rootElement.length] = dirSeparator[0];
            relPart = fullPath[rootElement.length + 1 .. $];
        }
        else
        {
            relPart = fullPath[rootElement.length .. $];
        }
    }
    else relPart = fullPath;

    // Now, we have ensured that all segments in path are relative to the
    // root we found earlier.
    bool hasParents = rooted;
    sizediff_t i;
    foreach (path; paths)
    {
        path = trimDirSeparators(path);

        enum Prev { nonSpecial, dirSep, dot, doubleDot }
        Prev prev = Prev.dirSep;
        foreach (j; 0 .. path.length+1)
        {
            // Fake a dir separator between path segments
            immutable c = (j == path.length ? dirSeparator[0] : path[j]);

            if (isDirSeparator(c))
            {
                final switch (prev)
                {
                    case Prev.doubleDot:
                        if (hasParents)
                        {
                            while (i > 0 && !isDirSeparator(relPart[i-1])) --i;
                            if (i > 0) --i; // skip the dir separator
                            while (i > 0 && !isDirSeparator(relPart[i-1])) --i;
                            if (i == 0) hasParents = rooted;
                        }
                        else
                        {
                            relPart[i++] = '.';
                            relPart[i++] = '.';
                            static assert (dirSeparator.length == 1);
                            relPart[i++] = dirSeparator[0];
                        }
                        break;
                    case Prev.dot:
                        while (i > 0 && !isDirSeparator(relPart[i-1])) --i;
                        break;
                    case Prev.nonSpecial:
                        static assert (dirSeparator.length == 1);
                        relPart[i++] = dirSeparator[0];
                        hasParents = true;
                        break;
                    case Prev.dirSep:
                        break;
                }
                prev = Prev.dirSep;
            }
            else if (c == '.')
            {
                final switch (prev)
                {
                    case Prev.dirSep:
                        prev = Prev.dot;
                        break;
                    case Prev.dot:
                        prev = Prev.doubleDot;
                        break;
                    case Prev.doubleDot:
                        prev = Prev.nonSpecial;
                        relPart[i .. i+3] = "...";
                        i += 3;
                        break;
                    case Prev.nonSpecial:
                        relPart[i] = '.';
                        ++i;
                        break;
                }
            }
            else
            {
                final switch (prev)
                {
                    case Prev.doubleDot:
                        relPart[i] = '.';
                        ++i;
                        goto case;
                    case Prev.dot:
                        relPart[i] = '.';
                        ++i;
                        break;
                    case Prev.dirSep:       break;
                    case Prev.nonSpecial:   break;
                }
                relPart[i] = c;
                ++i;
                prev = Prev.nonSpecial;
            }
        }
    }

    // Return path, including root element and excluding the
    // final dir separator.
    immutable len = (relPart.ptr - fullPath.ptr) + (i > 0 ? i - 1 : 0);
    fullPath = fullPath[0 .. len];
    version (Windows)
    {
        // On Windows, if the path is on the form `\\server\share`,
        // with no further segments, normalization will have turned it
        // into `\\server\share\`.  If so, we need to remove the final
        // backslash.
        if (isUNC(fullPath) && uncRootLength(fullPath) == fullPath.length - 1)
            fullPath = fullPath[0 .. $-1];
    }
    return cast(typeof(return)) fullPath;
}

unittest
{
    assert (buildNormalizedPath("") is null);
    assert (buildNormalizedPath("foo") == "foo");

    version (Posix)
    {
        assert (buildNormalizedPath("/", "foo", "bar") == "/foo/bar");
        assert (buildNormalizedPath("foo", "bar", "baz") == "foo/bar/baz");
        assert (buildNormalizedPath("foo", "bar/baz") == "foo/bar/baz");
        assert (buildNormalizedPath("foo", "bar//baz///") == "foo/bar/baz");
        assert (buildNormalizedPath("/foo", "bar/baz") == "/foo/bar/baz");
        assert (buildNormalizedPath("/foo", "/bar/baz") == "/bar/baz");
        assert (buildNormalizedPath("/foo/..", "/bar/./baz") == "/bar/baz");
        assert (buildNormalizedPath("/foo/..", "bar/baz") == "/bar/baz");
        assert (buildNormalizedPath("/foo/../../", "bar/baz") == "/bar/baz");
        assert (buildNormalizedPath("/foo/bar", "../baz") == "/foo/baz");
        assert (buildNormalizedPath("/foo/bar", "../../baz") == "/baz");
        assert (buildNormalizedPath("/foo/bar", ".././/baz/..", "wee/") == "/foo/wee");
        assert (buildNormalizedPath("//foo/bar", "baz///wee") == "/foo/bar/baz/wee");
        static assert (buildNormalizedPath("/foo/..", "/bar/./baz") == "/bar/baz");
        // Examples in docs:
        assert (buildNormalizedPath("/foo", "bar/baz/") == "/foo/bar/baz");
        assert (buildNormalizedPath("/foo", "/bar/..", "baz") == "/baz");
        assert (buildNormalizedPath("foo/./bar", "../../", "../baz") == "../baz");
        assert (buildNormalizedPath("/foo/./bar", "../../baz") == "/baz");
    }
    else version (Windows)
    {
        assert (buildNormalizedPath(`\`, `foo`, `bar`) == `\foo\bar`);
        assert (buildNormalizedPath(`foo`, `bar`, `baz`) == `foo\bar\baz`);
        assert (buildNormalizedPath(`foo`, `bar\baz`) == `foo\bar\baz`);
        assert (buildNormalizedPath(`foo`, `bar\\baz\\\`) == `foo\bar\baz`);
        assert (buildNormalizedPath(`\foo`, `bar\baz`) == `\foo\bar\baz`);
        assert (buildNormalizedPath(`\foo`, `\bar\baz`) == `\bar\baz`);
        assert (buildNormalizedPath(`\foo\..`, `\bar\.\baz`) == `\bar\baz`);
        assert (buildNormalizedPath(`\foo\..`, `bar\baz`) == `\bar\baz`);
        assert (buildNormalizedPath(`\foo\..\..\`, `bar\baz`) == `\bar\baz`);
        assert (buildNormalizedPath(`\foo\bar`, `..\baz`) == `\foo\baz`);
        assert (buildNormalizedPath(`\foo\bar`, `../../baz`) == `\baz`);
        assert (buildNormalizedPath(`\foo\bar`, `..\.\/baz\..`, `wee\`) == `\foo\wee`);

        assert (buildNormalizedPath(`c:\`, `foo`, `bar`) == `c:\foo\bar`);
        assert (buildNormalizedPath(`c:foo`, `bar`, `baz`) == `c:foo\bar\baz`);
        assert (buildNormalizedPath(`c:foo`, `bar\baz`) == `c:foo\bar\baz`);
        assert (buildNormalizedPath(`c:foo`, `bar\\baz\\\`) == `c:foo\bar\baz`);
        assert (buildNormalizedPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
        assert (buildNormalizedPath(`c:\foo`, `\bar\baz`) == `c:\bar\baz`);
        assert (buildNormalizedPath(`c:\foo\..`, `\bar\.\baz`) == `c:\bar\baz`);
        assert (buildNormalizedPath(`c:\foo\..`, `bar\baz`) == `c:\bar\baz`);
        assert (buildNormalizedPath(`c:\foo\..\..\`, `bar\baz`) == `c:\bar\baz`);
        assert (buildNormalizedPath(`c:\foo\bar`, `..\baz`) == `c:\foo\baz`);
        assert (buildNormalizedPath(`c:\foo\bar`, `..\..\baz`) == `c:\baz`);
        assert (buildNormalizedPath(`c:\foo\bar`, `..\.\\baz\..`, `wee\`) == `c:\foo\wee`);

        assert (buildNormalizedPath(`\\server\share`, `foo`, `bar`) == `\\server\share\foo\bar`);
        assert (buildNormalizedPath(`\\server\share\`, `foo`, `bar`) == `\\server\share\foo\bar`);
        assert (buildNormalizedPath(`\\server\share\foo`, `bar\baz`) == `\\server\share\foo\bar\baz`);
        assert (buildNormalizedPath(`\\server\share\foo`, `\bar\baz`) == `\\server\share\bar\baz`);
        assert (buildNormalizedPath(`\\server\share\foo\..`, `\bar\.\baz`) == `\\server\share\bar\baz`);
        assert (buildNormalizedPath(`\\server\share\foo\..`, `bar\baz`) == `\\server\share\bar\baz`);
        assert (buildNormalizedPath(`\\server\share\foo\..\..\`, `bar\baz`) == `\\server\share\bar\baz`);
        assert (buildNormalizedPath(`\\server\share\foo\bar`, `..\baz`) == `\\server\share\foo\baz`);
        assert (buildNormalizedPath(`\\server\share\foo\bar`, `..\..\baz`) == `\\server\share\baz`);
        assert (buildNormalizedPath(`\\server\share\foo\bar`, `..\.\\baz\..`, `wee\`) == `\\server\share\foo\wee`);

        static assert (buildNormalizedPath(`\foo\..\..\`, `bar\baz`) == `\bar\baz`);

        // Examples in docs:
        assert (buildNormalizedPath(`c:\foo`, `bar\baz\`) == `c:\foo\bar\baz`);
        assert (buildNormalizedPath(`c:\foo`, `bar/..`) == `c:\foo`);
        assert (buildNormalizedPath(`\\server\share\foo`, `..\bar`) == `\\server\share\bar`);
    }
    else static assert (0);
}

unittest
{
    version (Posix)
    {
        // Trivial
        assert (buildNormalizedPath("").empty);
        assert (buildNormalizedPath("foo/bar") == "foo/bar");

        // Correct handling of leading slashes
        assert (buildNormalizedPath("/") == "/");
        assert (buildNormalizedPath("///") == "/");
        assert (buildNormalizedPath("////") == "/");
        assert (buildNormalizedPath("/foo/bar") == "/foo/bar");
        assert (buildNormalizedPath("//foo/bar") == "/foo/bar");
        assert (buildNormalizedPath("///foo/bar") == "/foo/bar");
        assert (buildNormalizedPath("////foo/bar") == "/foo/bar");

        // Correct handling of single-dot symbol (current directory)
        assert (buildNormalizedPath("/./foo") == "/foo");
        assert (buildNormalizedPath("/foo/./bar") == "/foo/bar");

        assert (buildNormalizedPath("./foo") == "foo");
        assert (buildNormalizedPath("././foo") == "foo");
        assert (buildNormalizedPath("foo/././bar") == "foo/bar");

        // Correct handling of double-dot symbol (previous directory)
        assert (buildNormalizedPath("/foo/../bar") == "/bar");
        assert (buildNormalizedPath("/foo/../../bar") == "/bar");
        assert (buildNormalizedPath("/../foo") == "/foo");
        assert (buildNormalizedPath("/../../foo") == "/foo");
        assert (buildNormalizedPath("/foo/..") == "/");
        assert (buildNormalizedPath("/foo/../..") == "/");

        assert (buildNormalizedPath("foo/../bar") == "bar");
        assert (buildNormalizedPath("foo/../../bar") == "../bar");
        assert (buildNormalizedPath("../foo") == "../foo");
        assert (buildNormalizedPath("../../foo") == "../../foo");
        assert (buildNormalizedPath("../foo/../bar") == "../bar");
        assert (buildNormalizedPath(".././../foo") == "../../foo");
        assert (buildNormalizedPath("foo/bar/..") == "foo");
        assert (buildNormalizedPath("/foo/../..") == "/");

        // The ultimate path
        assert (buildNormalizedPath("/foo/../bar//./../...///baz//") == "/.../baz");
        static assert (buildNormalizedPath("/foo/../bar//./../...///baz//") == "/.../baz");
    }
    else version (Windows)
    {
        // Trivial
        assert (buildNormalizedPath("").empty);
        assert (buildNormalizedPath(`foo\bar`) == `foo\bar`);
        assert (buildNormalizedPath("foo/bar") == `foo\bar`);

        // Correct handling of absolute paths
        assert (buildNormalizedPath("/") == `\`);
        assert (buildNormalizedPath(`\`) == `\`);
        assert (buildNormalizedPath(`\\\`) == `\`);
        assert (buildNormalizedPath(`\\\\`) == `\`);
        assert (buildNormalizedPath(`\foo\bar`) == `\foo\bar`);
        assert (buildNormalizedPath(`\\foo`) == `\\foo`);
        assert (buildNormalizedPath(`\\foo\\`) == `\\foo`);
        assert (buildNormalizedPath(`\\foo/bar`) == `\\foo\bar`);
        assert (buildNormalizedPath(`\\\foo\bar`) == `\foo\bar`);
        assert (buildNormalizedPath(`\\\\foo\bar`) == `\foo\bar`);
        assert (buildNormalizedPath(`c:\`) == `c:\`);
        assert (buildNormalizedPath(`c:\foo\bar`) == `c:\foo\bar`);
        assert (buildNormalizedPath(`c:\\foo\bar`) == `c:\foo\bar`);

        // Correct handling of single-dot symbol (current directory)
        assert (buildNormalizedPath(`\./foo`) == `\foo`);
        assert (buildNormalizedPath(`\foo/.\bar`) == `\foo\bar`);

        assert (buildNormalizedPath(`.\foo`) == `foo`);
        assert (buildNormalizedPath(`./.\foo`) == `foo`);
        assert (buildNormalizedPath(`foo\.\./bar`) == `foo\bar`);

        // Correct handling of double-dot symbol (previous directory)
        assert (buildNormalizedPath(`\foo\..\bar`) == `\bar`);
        assert (buildNormalizedPath(`\foo\../..\bar`) == `\bar`);
        assert (buildNormalizedPath(`\..\foo`) == `\foo`);
        assert (buildNormalizedPath(`\..\..\foo`) == `\foo`);
        assert (buildNormalizedPath(`\foo\..`) == `\`);
        assert (buildNormalizedPath(`\foo\../..`) == `\`);

        assert (buildNormalizedPath(`foo\..\bar`) == `bar`);
        assert (buildNormalizedPath(`foo\..\../bar`) == `..\bar`);
        assert (buildNormalizedPath(`..\foo`) == `..\foo`);
        assert (buildNormalizedPath(`..\..\foo`) == `..\..\foo`);
        assert (buildNormalizedPath(`..\foo\..\bar`) == `..\bar`);
        assert (buildNormalizedPath(`..\.\..\foo`) == `..\..\foo`);
        assert (buildNormalizedPath(`foo\bar\..`) == `foo`);
        assert (buildNormalizedPath(`\foo\..\..`) == `\`);
        assert (buildNormalizedPath(`c:\foo\..\..`) == `c:\`);

        // Correct handling of non-root path with drive specifier
        assert (buildNormalizedPath(`c:foo`) == `c:foo`);
        assert (buildNormalizedPath(`c:..\foo\.\..\bar`) == `c:..\bar`);

        // The ultimate path
        assert (buildNormalizedPath(`c:\foo\..\bar\\.\..\...\\\baz\\`) == `c:\...\baz`);
        static assert (buildNormalizedPath(`c:\foo\..\bar\\.\..\...\\\baz\\`) == `c:\...\baz`);
    }
    else static assert (false);
}




/** Returns a bidirectional range that iterates over the elements of a path.

    Examples:
    ---
    assert (equal(pathSplitter("/"), ["/"]));
    assert (equal(pathSplitter("/foo/bar"), ["/", "foo", "bar"]));
    assert (equal(pathSplitter("//foo/bar"), ["//foo", "bar"]));
    assert (equal(pathSplitter("foo/../bar//./"), ["foo", "..", "bar", "."]));

    version (Windows)
    {
        assert (equal(pathSplitter(`foo\..\bar\/.\`), ["foo", "..", "bar", "."]));
        assert (equal(pathSplitter("c:"), ["c:"]));
        assert (equal(pathSplitter(`c:\foo\bar`), [`c:\`, "foo", "bar"]));
        assert (equal(pathSplitter(`c:foo\bar`), ["c:foo", "bar"]));
    }
    ---
*/
auto pathSplitter(C)(const(C)[] path)  @safe pure nothrow
    if (isSomeChar!C)
{
    static struct PathSplitter
    {
    @safe pure nothrow:
        @property empty() const { return _empty; }

        @property front() const
        {
            assert (!empty, "PathSplitter: called front() on empty range");
            return _front;
        }

        void popFront()
        {
            assert (!empty, "PathSplitter: called popFront() on empty range");
            if (_path.empty)
            {
                if (_front is _back)
                {
                    _empty = true;
                    _front = null;
                    _back = null;
                }
                else
                {
                    _front = _back;
                }
            }
            else
            {
                sizediff_t i = 0;
                while (i < _path.length && !isDirSeparator(_path[i])) ++i;
                _front = _path[0 .. i];
                _path = ltrimDirSeparators(_path[i .. $]);
            }
        }

        @property back() const
        {
            assert (!empty, "PathSplitter: called back() on empty range");
            return _back;
        }

        void popBack()
        {
            assert (!empty, "PathSplitter: called popBack() on empty range");
            if (_path.empty)
            {
                if (_front is _back)
                {
                    _empty = true;
                    _front = null;
                    _back = null;
                }
                else
                {
                    _back = _front;
                }
            }
            else
            {
                auto i = (cast(sizediff_t) _path.length) - 1;
                while (i >= 0 && !isDirSeparator(_path[i])) --i;
                _back = _path[i + 1 .. $];
                _path = rtrimDirSeparators(_path[0 .. i+1]);
            }
        }
        auto save() { return this; }


    private:
        typeof(path) _path, _front, _back;
        bool _empty;

        this(typeof(path) p)
        {
            if (p.empty)
            {
                _empty = true;
                return;
            }
            _path = p;

            // If path is rooted, first element is special
            version (Windows)
            {
                if (isUNC(_path))
                {
                    auto i = uncRootLength(_path);
                    _front = _path[0 .. i];
                    _path = ltrimDirSeparators(_path[i .. $]);
                }
                else if (isDriveRoot(_path))
                {
                    _front = _path[0 .. 3];
                    _path = ltrimDirSeparators(_path[3 .. $]);
                }
                else if (_path.length >= 1 && isDirSeparator(_path[0]))
                {
                    _front = _path[0 .. 1];
                    _path = ltrimDirSeparators(_path[1 .. $]);
                }
                else
                {
                    assert (!isRooted(_path));
                    popFront();
                }
            }
            else version (Posix)
            {
                if (_path.length >= 1 && isDirSeparator(_path[0]))
                {
                    _front = _path[0 .. 1];
                    _path = ltrimDirSeparators(_path[1 .. $]);
                }
                else
                {
                    popFront();
                }
            }
            else static assert (0);

            if (_path.empty) _back = _front;
            else
            {
                _path = rtrimDirSeparators(_path);
                popBack();
            }
        }
    }

    return PathSplitter(path);
}

unittest
{
    // equal2 verifies that the range is the same both ways, i.e.
    // through front/popFront and back/popBack.
    import std.range;
    bool equal2(R1, R2)(R1 r1, R2 r2)
    {
        static assert (isBidirectionalRange!R1);
        return equal(r1, r2) && equal(retro(r1), retro(r2));
    }

    assert (pathSplitter("").empty);

    // Root directories
    assert (equal2(pathSplitter("/"), ["/"]));
    assert (equal2(pathSplitter("//"), ["/"]));
    assert (equal2(pathSplitter("///"w), ["/"w]));

    // Absolute paths
    assert (equal2(pathSplitter("/foo/bar".dup), ["/", "foo", "bar"]));

    // General
    assert (equal2(pathSplitter("foo/bar"d.dup), ["foo"d, "bar"d]));
    assert (equal2(pathSplitter("foo//bar"), ["foo", "bar"]));
    assert (equal2(pathSplitter("foo/bar//"w), ["foo"w, "bar"w]));
    assert (equal2(pathSplitter("foo/../bar//./"d), ["foo"d, ".."d, "bar"d, "."d]));

    // save()
    auto ps1 = pathSplitter("foo/bar/baz");
    auto ps2 = ps1.save();
    ps1.popFront;
    assert (equal2(ps1, ["bar", "baz"]));
    assert (equal2(ps2, ["foo", "bar", "baz"]));

    // Platform specific
    version (Posix)
    {
        assert (equal2(pathSplitter("//foo/bar"w.dup), ["/"w, "foo"w, "bar"w]));
    }
    version (Windows)
    {
        assert (equal2(pathSplitter(`\`), [`\`]));
        assert (equal2(pathSplitter(`foo\..\bar\/.\`), ["foo", "..", "bar", "."]));
        assert (equal2(pathSplitter("c:"), ["c:"]));
        assert (equal2(pathSplitter(`c:\foo\bar`), [`c:\`, "foo", "bar"]));
        assert (equal2(pathSplitter(`c:foo\bar`), ["c:foo", "bar"]));
        assert (equal2(pathSplitter(`\\foo\bar`), [`\\foo\bar`]));
        assert (equal2(pathSplitter(`\\foo\bar\\`), [`\\foo\bar`]));
        assert (equal2(pathSplitter(`\\foo\bar\baz`), [`\\foo\bar`, "baz"]));
    }

    // CTFE
    // Fails due to BUG 6390
    //static assert (equal(pathSplitter("/foo/bar".dup), ["/", "foo", "bar"]));
}




/** Determines whether a path starts at a root directory.

    On POSIX, this function returns true if and only if the path starts
    with a slash (/).
    ---
    version (Posix)
    {
        assert (isRooted("/"));
        assert (isRooted("/foo"));
        assert (!isRooted("foo"));
        assert (!isRooted("../foo"));
    }
    ---

    On Windows, this function returns true if the path starts at
    the root directory of the current drive, of some other drive,
    or of a network drive.
    ---
    version (Windows)
    {
        assert (isRooted(`\`));
        assert (isRooted(`\foo`));
        assert (isRooted(`d:\foo`));
        assert (isRooted(`\\foo\bar`));
        assert (!isRooted("foo"));
        assert (!isRooted("d:foo"));
    }
    ---
*/
bool isRooted(C)(in C[] path)  @safe pure nothrow  if (isSomeChar!C)
{
    if (path.length >= 1 && isDirSeparator(path[0])) return true;
    version (Posix)         return false;
    else version (Windows)  return isAbsolute(path);
}


unittest
{
    assert (isRooted("/"));
    assert (isRooted("/foo"));
    assert (!isRooted("foo"));
    assert (!isRooted("../foo"));

    version (Windows)
    {
    assert (isRooted(`\`));
    assert (isRooted(`\foo`));
    assert (isRooted(`d:\foo`));
    assert (isRooted(`\\foo\bar`));
    assert (!isRooted("foo"));
    assert (!isRooted("d:foo"));
    }

    static assert (isRooted("/foo"));
    static assert (!isRooted("foo"));
}




/** Determines whether a path is absolute or not.

    Examples:
    On POSIX, an absolute path starts at the root directory.
    (In fact, $(D _isAbsolute) is just an alias for $(LREF isRooted).)
    ---
    version (Posix)
    {
        assert (isAbsolute("/"));
        assert (isAbsolute("/foo"));
        assert (!isAbsolute("foo"));
        assert (!isAbsolute("../foo"));
    }
    ---

    On Windows, an absolute path starts at the root directory of
    a specific drive.  Hence, it must start with $(D "d:\") or $(D "d:/"),
    where $(D d) is the drive letter.  Alternatively, it may be a
    network path, i.e. a path starting with a double (back)slash.
    ---
    version (Windows)
    {
        assert (isAbsolute(`d:\`));
        assert (isAbsolute(`d:\foo`));
        assert (isAbsolute(`\\foo\bar`));
        assert (!isAbsolute(`\`));
        assert (!isAbsolute(`\foo`));
        assert (!isAbsolute("d:foo"));
    }
    ---
*/
version (StdDdoc) bool isAbsolute(C)(in C[] path) @safe pure nothrow
    if (isSomeChar!C);

else version (Windows) bool isAbsolute(C)(in C[] path)  @safe pure nothrow
    if (isSomeChar!C)
{
    return isDriveRoot(path) || isUNC(path);
}

else version (Posix) alias isRooted isAbsolute;


unittest
{
    assert (!isAbsolute("foo"));
    assert (!isAbsolute("../foo"w));
    static assert (!isAbsolute("foo"));

    version (Posix)
    {
    assert (isAbsolute("/"d));
    assert (isAbsolute("/foo".dup));
    static assert (isAbsolute("/foo"));
    }

    version (Windows)
    {
    assert (isAbsolute("d:\\"w));
    assert (isAbsolute("d:\\foo"d));
    assert (isAbsolute("\\\\foo\\bar"));
    assert (!isAbsolute("\\"w.dup));
    assert (!isAbsolute("\\foo"d.dup));
    assert (!isAbsolute("d:"));
    assert (!isAbsolute("d:foo"));
    static assert (isAbsolute(`d:\foo`));
    }
}




/** Translate $(D path) into an absolute _path.

    This means:
    $(UL
        $(LI If $(D path) is empty, return $(D null).)
        $(LI If $(D path) is already absolute, return it.)
        $(LI Otherwise, append $(D path) to $(D base) and return
            the result. If $(D base) is not specified, the current
            working directory is used.)
    )

    Examples:
    ---
    version (Posix)
    {
        assert (absolutePath("some/file", "/foo/bar")  == "/foo/bar/some/file");
        assert (absolutePath("../file", "/foo/bar")    == "/foo/bar/../file");
        assert (absolutePath("/some/file", "/foo/bar") == "/some/file");
    }

    version (Windows)
    {
        assert (absolutePath(`some\file`, `c:\foo\bar`)    == `c:\foo\bar\some\file`);
        assert (absolutePath(`..\file`, `c:\foo\bar`)      == `c:\foo\bar\..\file`);
        assert (absolutePath(`c:\some\file`, `c:\foo\bar`) == `c:\some\file`);
    }
    ---

    Throws:
    $(D Exception) if the specified _base directory is not absolute.
*/
string absolutePath(string path, string base = getcwd())
    // TODO: @safe (BUG 6405) pure (because of buildPath())
{
    if (path.empty)  return null;
    if (isAbsolute(path))  return path;
    if (!isAbsolute(base)) throw new Exception("Base directory must be absolute");
    return buildPath(base, path);
}


unittest
{
    version (Posix)
    {
        assert (absolutePath("some/file", "/foo/bar")  == "/foo/bar/some/file");
        assert (absolutePath("../file", "/foo/bar")    == "/foo/bar/../file");
        assert (absolutePath("/some/file", "/foo/bar") == "/some/file");
        static assert (absolutePath("some/file", "/foo/bar") == "/foo/bar/some/file");
    }

    version (Windows)
    {
        assert (absolutePath(`some\file`, `c:\foo\bar`)    == `c:\foo\bar\some\file`);
        assert (absolutePath(`..\file`, `c:\foo\bar`)      == `c:\foo\bar\..\file`);
        assert (absolutePath(`c:\some\file`, `c:\foo\bar`) == `c:\some\file`);
        static assert (absolutePath(`some\file`, `c:\foo\bar`) == `c:\foo\bar\some\file`);
    }

    import std.exception;
    assertThrown(absolutePath("bar", "foo"));
}




/** Translate $(D path) into a relative _path.

    The returned _path is relative to $(D base), which is by default
    taken to be the current working directory.  If specified,
    $(D base) must be an absolute _path, and it is always assumed
    to refer to a directory.  If $(D path) and $(D base) refer to
    the same directory, the function returns $(D ".").

    The following algorithm is used:
    $(OL
        $(LI If $(D path) is a relative directory, return it unaltered.)
        $(LI Find a common root between $(D path) and $(D base).
            If there is no common root, return $(D path) unaltered.)
        $(LI Prepare a string with as many $(D "../") or $(D "..\") as
            necessary to reach the common root from base path.)
        $(LI Append the remaining segments of $(D path) to the string
            and return.)
    )

    In the second step, path components are compared using $(D filenameCmp!cs),
    where $(D cs) is an optional template parameter determining whether
    the comparison is case sensitive or not.  See the
    $(LREF filenameCmp) documentation for details.


    Examples:
    ---
    assert (relativePath("foo") == "foo");

    version (Posix)
    {
        assert (relativePath("foo", "/bar") == "foo");
        assert (relativePath("/foo/bar", "/foo/bar") == ".");
        assert (relativePath("/foo/bar", "/foo/baz") == "../bar");
        assert (relativePath("/foo/bar/baz", "/foo/woo/wee") == "../../bar/baz");
        assert (relativePath("/foo/bar/baz", "/foo/bar") == "baz");
    }
    version (Windows)
    {
        assert (relativePath("foo", `c:\bar`) == "foo");
        assert (relativePath(`c:\foo\bar`, `c:\foo\bar`) == ".");
        assert (relativePath(`c:\foo\bar`, `c:\foo\baz`) == `..\bar`);
        assert (relativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`) == `..\..\bar\baz`);
        assert (relativePath(`c:\foo\bar\baz`, `c:\foo\bar`) == "baz");
        assert (relativePath(`c:\foo\bar`, `d:\foo`) == `c:\foo\bar`);
    }
    ---

    Throws:
    $(D Exception) if the specified _base directory is not absolute.
*/
string relativePath(CaseSensitive cs = CaseSensitive.osDefault)
    (string path, string base = getcwd())
    //TODO: @safe  (object.reserve(T[]) should be @trusted)
{
    if (!isAbsolute(path)) return path;
    if (!isAbsolute(base)) throw new Exception("Base directory must be absolute");

    // Find common root with current working directory
    string result;
    if (!__ctfe) result.reserve(base.length + path.length);

    auto basePS = pathSplitter(base);
    auto pathPS = pathSplitter(path);
    if (filenameCmp!cs(basePS.front, pathPS.front) != 0) return path;

    basePS.popFront();
    pathPS.popFront();

    while (!basePS.empty && !pathPS.empty
        && filenameCmp!cs(basePS.front, pathPS.front) == 0)
    {
        basePS.popFront();
        pathPS.popFront();
    }

    // Append as many "../" as necessary to reach common base from path
    while (!basePS.empty)
    {
        result ~= "..";
        result ~= dirSeparator;
        basePS.popFront();
    }

    // Append the remainder of path
    while (!pathPS.empty)
    {
        result ~= pathPS.front;
        result ~= dirSeparator;
        pathPS.popFront();
    }

    // base == path
    if (result.empty) return ".";

    // Strip off last path separator
    return result[0 .. $-1];
}

unittest
{
    import std.exception;
    assert (relativePath("foo") == "foo");
    version (Posix)
    {
        assert (relativePath("foo", "/bar") == "foo");
        assert (relativePath("/foo/bar", "/foo/bar") == ".");
        assert (relativePath("/foo/bar", "/foo/baz") == "../bar");
        assert (relativePath("/foo/bar/baz", "/foo/woo/wee") == "../../bar/baz");
        assert (relativePath("/foo/bar/baz", "/foo/bar") == "baz");
        assertThrown(relativePath("/foo", "bar"));

        //BUG: std.algorithm.cmp is not CTFEable
        //static assert (relativePath("/foo/bar", "/foo/baz") == "../bar");
    }
    else version (Windows)
    {
        assert (relativePath("foo", `c:\bar`) == "foo");
        assert (relativePath(`c:\foo\bar`, `c:\foo\bar`) == ".");
        assert (relativePath(`c:\foo\bar`, `c:\foo\baz`) == `..\bar`);
        assert (relativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`) == `..\..\bar\baz`);
        assert (relativePath(`c:/foo/bar/baz`, `c:\foo\woo\wee`) == `..\..\bar\baz`);
        assert (relativePath(`c:\foo\bar\baz`, `c:\foo\bar`) == "baz");
        assert (relativePath(`c:\foo\bar`, `d:\foo`) == `c:\foo\bar`);
        assert (relativePath(`\\foo\bar`, `c:\foo`) == `\\foo\bar`);
        assertThrown(relativePath(`c:\foo`, "bar"));

        //BUG: 6390
        //static assert (relativePath(`c:\foo\bar`, `c:\foo\baz`) == `..\bar`);
    }
    else static assert (0);
}




/** Compare filename characters and return $(D < 0) if $(D a < b), $(D 0) if
    $(D a == b) and $(D > 0) if $(D a > b).

    This function can perform a case-sensitive or a case-insensitive
    comparison.  This is controlled through the $(D cs) template parameter
    which, if not specified, is given by
    $(LREF CaseSensitive)$(D .osDefault).

    On Windows, the backslash and slash characters ($(D '\') and $(D '/'))
    are considered equal.

    Examples:
    ---
    assert (filenameCharCmp('a', 'a') == 0);
    assert (filenameCharCmp('a', 'b') < 0);
    assert (filenameCharCmp('b', 'a') > 0);

    version (linux)
    {
        // Same as calling filenameCharCmp!(CaseSensitive.yes)(a, b)
        assert (filenameCharCmp('A', 'a') < 0);
        assert (filenameCharCmp('a', 'A') > 0);
    }
    version (Windows)
    {
        // Same as calling filenameCharCmp!(CaseSensitive.no)(a, b)
        assert (filenameCharCmp('a', 'A') == 0);
        assert (filenameCharCmp('a', 'B') < 0);
        assert (filenameCharCmp('A', 'b') < 0);
    }
    ---
*/
int filenameCharCmp(CaseSensitive cs = CaseSensitive.osDefault)(dchar a, dchar b)
    @safe pure nothrow
{
    if (isDirSeparator(a) && isDirSeparator(b)) return 0;
    static if (!cs)
    {
        import std.uni;
        a = toLower(a);
        b = toLower(b);
    }
    return cast(int)(a - b);
}


unittest
{
    assert (filenameCharCmp!(CaseSensitive.yes)('a', 'a') == 0);
    assert (filenameCharCmp!(CaseSensitive.yes)('a', 'b') < 0);
    assert (filenameCharCmp!(CaseSensitive.yes)('b', 'a') > 0);
    assert (filenameCharCmp!(CaseSensitive.yes)('A', 'a') < 0);
    assert (filenameCharCmp!(CaseSensitive.yes)('a', 'A') > 0);

    assert (filenameCharCmp!(CaseSensitive.no)('a', 'a') == 0);
    assert (filenameCharCmp!(CaseSensitive.no)('a', 'b') < 0);
    assert (filenameCharCmp!(CaseSensitive.no)('b', 'a') > 0);
    assert (filenameCharCmp!(CaseSensitive.no)('A', 'a') == 0);
    assert (filenameCharCmp!(CaseSensitive.no)('a', 'A') == 0);
    assert (filenameCharCmp!(CaseSensitive.no)('a', 'B') < 0);
    assert (filenameCharCmp!(CaseSensitive.no)('B', 'a') > 0);
    assert (filenameCharCmp!(CaseSensitive.no)('A', 'b') < 0);
    assert (filenameCharCmp!(CaseSensitive.no)('b', 'A') > 0);

    version (Posix)   assert (filenameCharCmp('\\', '/') != 0);
    version (Windows) assert (filenameCharCmp('\\', '/') == 0);
}




/** Compare file names and return
    $(D < 0) if $(D filename1 < filename2),
    $(D 0) if $(D filename1 == filename2) and
    $(D > 0) if $(D filename1 > filename2).

    Individual characters are compared using $(D filenameCharCmp!cs),
    where $(D cs) is an optional template parameter determining whether
    the comparison is case sensitive or not.  See the
    $(LREF filenameCharCmp) documentation for details.

    Examples:
    ---
    assert (filenameCmp("abc", "abc") == 0);
    assert (filenameCmp("abc", "abd") < 0);
    assert (filenameCmp("abc", "abb") > 0);
    assert (filenameCmp("abc", "abcd") < 0);
    assert (filenameCmp("abcd", "abc") > 0);

    version (linux)
    {
        // Same as calling filenameCmp!(CaseSensitive.yes)(filename1, filename2)
        assert (filenameCmp("Abc", "abc") < 0);
        assert (filenameCmp("abc", "Abc") > 0);
    }
    version (Windows)
    {
        // Same as calling filenameCmp!(CaseSensitive.no)(filename1, filename2)
        assert (filenameCmp("Abc", "abc") == 0);
        assert (filenameCmp("abc", "Abc") == 0);
        assert (filenameCmp("Abc", "abD") < 0);
        assert (filenameCmp("abc", "AbB") > 0);
    }
    ---
*/
int filenameCmp(CaseSensitive cs = CaseSensitive.osDefault, C1, C2)
    (const(C1)[] filename1, const(C2)[] filename2)
    @safe //TODO: pure nothrow (because of std.array.front())
    if (isSomeChar!C1 && isSomeChar!C2)
{
    for (;;)
    {
        if (filename1.empty) return -(cast(int) !filename2.empty);
        if (filename2.empty) return  (cast(int) !filename1.empty);
        auto c = filenameCharCmp!cs(filename1.front, filename2.front);
        if (c != 0) return c;
        filename1.popFront();
        filename2.popFront();
    }
    assert (0);
}


unittest
{
    assert (filenameCmp!(CaseSensitive.yes)("abc", "abc") == 0);
    assert (filenameCmp!(CaseSensitive.yes)("abc", "abd") < 0);
    assert (filenameCmp!(CaseSensitive.yes)("abc", "abb") > 0);
    assert (filenameCmp!(CaseSensitive.yes)("abc", "abcd") < 0);
    assert (filenameCmp!(CaseSensitive.yes)("abcd", "abc") > 0);
    assert (filenameCmp!(CaseSensitive.yes)("Abc", "abc") < 0);
    assert (filenameCmp!(CaseSensitive.yes)("abc", "Abc") > 0);

    assert (filenameCmp!(CaseSensitive.no)("abc", "abc") == 0);
    assert (filenameCmp!(CaseSensitive.no)("abc", "abd") < 0);
    assert (filenameCmp!(CaseSensitive.no)("abc", "abb") > 0);
    assert (filenameCmp!(CaseSensitive.no)("abc", "abcd") < 0);
    assert (filenameCmp!(CaseSensitive.no)("abcd", "abc") > 0);
    assert (filenameCmp!(CaseSensitive.no)("Abc", "abc") == 0);
    assert (filenameCmp!(CaseSensitive.no)("abc", "Abc") == 0);
    assert (filenameCmp!(CaseSensitive.no)("Abc", "abD") < 0);
    assert (filenameCmp!(CaseSensitive.no)("abc", "AbB") > 0);

    version (Posix)   assert (filenameCmp(`abc\def`, `abc/def`) != 0);
    version (Windows) assert (filenameCmp(`abc\def`, `abc/def`) == 0);
}




/** Matches a pattern against a path.

    Some characters of pattern have a special meaning (they are
    $(I meta-characters)) and can't be escaped. These are:

    $(BOOKTABLE,
    $(TR $(TD $(D *))
         $(TD Matches 0 or more instances of any character.))
    $(TR $(TD $(D ?))
         $(TD Matches exactly one instance of any character.))
    $(TR $(TD $(D [)$(I chars)$(D ]))
         $(TD Matches one instance of any character that appears
              between the brackets.))
    $(TR $(TD $(D [!)$(I chars)$(D ]))
         $(TD Matches one instance of any character that does not
              appear between the brackets after the exclamation mark.))
    $(TR $(TD $(D {)$(I string1)$(D ,)$(I string2)$(D ,)&hellip;$(D }))
         $(TD Matches either of the specified strings.))
    )

    Individual characters are compared using $(D filenameCharCmp!cs),
    where $(D cs) is an optional template parameter determining whether
    the comparison is case sensitive or not.  See the
    $(LREF filenameCharCmp) documentation for details.

    Note that directory
    separators and dots don't stop a meta-character from matching
    further portions of the path.

    Returns:
    $(D true) if pattern matches path, $(D false) otherwise.

    See_also:
    $(LINK2 http://en.wikipedia.org/wiki/Glob_%28programming%29,Wikipedia: _glob (programming))

    Examples:
    -----
    assert (globMatch("foo.bar", "*"));
    assert (globMatch("foo.bar", "*.*"));
    assert (globMatch(`foo/foo\bar`, "f*b*r"));
    assert (globMatch("foo.bar", "f???bar"));
    assert (globMatch("foo.bar", "[fg]???bar"));
    assert (globMatch("foo.bar", "[!gh]*bar"));
    assert (globMatch("bar.fooz", "bar.{foo,bif}z"));
    assert (globMatch("bar.bifz", "bar.{foo,bif}z"));

    version (Windows)
    {
        // Same as calling globMatch!(CaseSensitive.no)(path, pattern)
        assert (globMatch("foo", "Foo"));
        assert (globMatch("Goo.bar", "[fg]???bar"));
    }
    version (linux)
    {
        // Same as calling globMatch!(CaseSensitive.yes)(path, pattern)
        assert (!globMatch("foo", "Foo"));
        assert (!globMatch("Goo.bar", "[fg]???bar"));
    }
    -----
 */
bool globMatch(CaseSensitive cs = CaseSensitive.osDefault, C)
    (const(C)[] path, const(C)[] pattern)
    @safe nothrow //TODO: pure (because of balancedParens())
    if (isSomeChar!C)
in
{
    // Verify that pattern[] is valid
    assert(balancedParens(pattern, '[', ']', 0));
    assert(balancedParens(pattern, '{', '}', 0));
}
body
{
	size_t ni; // current character in path

    foreach (pi; 0 .. pattern.length)
    {
        C pc = pattern[pi];
        switch (pc)
        {
            case '*':
                if (pi + 1 == pattern.length)
                    return true;
                foreach (j; ni .. path.length)
                {
                    if (globMatch!(cs, C)(path[j .. path.length],
                                    pattern[pi + 1 .. pattern.length]))
                        return true;
                }
                return false;

            case '?':
                if (ni == path.length)
                    return false;
                ni++;
                break;

            case '[':
                if (ni == path.length)
                    return false;
                auto nc = path[ni];
                ni++;
                auto not = false;
                pi++;
                if (pattern[pi] == '!')
                {
                    not = true;
                    pi++;
                }
                auto anymatch = false;
                while (1)
                {
                    pc = pattern[pi];
                    if (pc == ']')
                        break;
                    if (!anymatch && (filenameCharCmp!cs(nc, pc) == 0))
                        anymatch = true;
                    pi++;
                }
                if (anymatch == not)
                    return false;
                break;

            case '{':
                // find end of {} section
                auto piRemain = pi;
                for (; piRemain < pattern.length
                         && pattern[piRemain] != '}'; piRemain++)
                {}

                if (piRemain < pattern.length) piRemain++;
                pi++;

                while (pi < pattern.length)
                {
                    auto pi0 = pi;
                    pc = pattern[pi];
                    // find end of current alternative
                    for (; pi<pattern.length && pc!='}' && pc!=','; pi++)
                    {
                        pc = pattern[pi];
                    }

                    if (pi0 == pi)
                    {
                        if (globMatch!(cs, C)(path[ni..$], pattern[piRemain..$]))
                        {
                            return true;
                        }
                        pi++;
                    }
                    else
                    {
                        if (globMatch!(cs, C)(path[ni..$],
                                        pattern[pi0..pi-1]
                                        ~ pattern[piRemain..$]))
                        {
                            return true;
                        }
                    }
                    if (pc == '}')
                    {
                        break;
                    }
                }
                return false;

            default:
                if (ni == path.length)
                    return false;
                if (filenameCharCmp!cs(pc, path[ni]) != 0)
                    return false;
                ni++;
                break;
	    }
	}
    assert(ni >= path.length);
	return ni == path.length;
}

unittest
{
    assert (globMatch!(CaseSensitive.no)("foo", "Foo"));
    assert (!globMatch!(CaseSensitive.yes)("foo", "Foo"));

    assert(globMatch("foo", "*"));
    assert(globMatch("foo.bar"w, "*"w));
    assert(globMatch("foo.bar"d, "*.*"d));
    assert(globMatch("foo.bar", "foo*"));
    assert(globMatch("foo.bar"w, "f*bar"w));
    assert(globMatch("foo.bar"d, "f*b*r"d));
    assert(globMatch("foo.bar", "f???bar"));
    assert(globMatch("foo.bar"w, "[fg]???bar"w));
    assert(globMatch("foo.bar"d, "[!gh]*bar"d));

    assert(!globMatch("foo", "bar"));
    assert(!globMatch("foo"w, "*.*"w));
    assert(!globMatch("foo.bar"d, "f*baz"d));
    assert(!globMatch("foo.bar", "f*b*x"));
    assert(!globMatch("foo.bar", "[gh]???bar"));
    assert(!globMatch("foo.bar"w, "[!fg]*bar"w));
    assert(!globMatch("foo.bar"d, "[fg]???baz"d));

    assert(globMatch("foo.bar", "{foo,bif}.bar"));
    assert(globMatch("bif.bar"w, "{foo,bif}.bar"w));

    assert(globMatch("bar.foo"d, "bar.{foo,bif}"d));
    assert(globMatch("bar.bif", "bar.{foo,bif}"));

    assert(globMatch("bar.fooz"w, "bar.{foo,bif}z"w));
    assert(globMatch("bar.bifz"d, "bar.{foo,bif}z"d));

    assert(globMatch("bar.foo", "bar.{biz,,baz}foo"));
    assert(globMatch("bar.foo"w, "bar.{biz,}foo"w));
    assert(globMatch("bar.foo"d, "bar.{,biz}foo"d));
    assert(globMatch("bar.foo", "bar.{}foo"));

    assert(globMatch("bar.foo"w, "bar.{ar,,fo}o"w));
    assert(globMatch("bar.foo"d, "bar.{,ar,fo}o"d));
    assert(globMatch("bar.o", "bar.{,ar,fo}o"));

    static assert(globMatch("foo.bar", "[!gh]*bar"));
}




/** Checks that the given file or directory name is valid.

    This function returns $(D true) if and only if $(D filename) is not
    empty, not too long, and does not contain invalid characters.

    The maximum length of $(D filename) is given by the constant
    $(D core.stdc.stdio.FILENAME_MAX).  (On Windows, this number is
    defined as the maximum number of UTF-16 code points, and the
    test will therefore only yield strictly correct results when
    $(D filename) is a string of $(D wchar)s.)

    On Windows, the following criteria must be satisfied
    ($(LINK2 http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx,source)):
    $(UL
        $(LI $(D filename) must not contain any characters whose integer
            representation is in the range 0-31.)
        $(LI $(D filename) must not contain any of the following $(I reserved
            characters): <>:"/\|?*)
        $(LI $(D filename) may not end with a space ($(D ' ')) or a period
            ($(D '.')).)
    )

    On POSIX, $(D filename) may not contain a forward slash ($(D '/')) or
    the null character ($(D '\0')).
*/
bool isValidFilename(C)(in C[] filename)  @safe pure nothrow  if (isSomeChar!C)
{
    import core.stdc.stdio;
    if (filename.length == 0 || filename.length >= FILENAME_MAX) return false;
    foreach (c; filename)
    {
        version (Windows)
        {
            switch (c)
            {
                case 0:
                ..
                case 31:
                case '<':
                case '>':
                case ':':
                case '"':
                case '/':
                case '\\':
                case '|':
                case '?':
                case '*':
                    return false;
                default:
            }
        }
        else version (Posix)
        {
            if (c == 0 || c == '/') return false;
        }
        else static assert (0);
    }
    version (Windows)
    {
        if (filename[$-1] == '.' || filename[$-1] == ' ') return false;
    }

    // All criteria passed
    return true;
}


unittest
{
    auto valid = ["foo"];
    auto invalid = ["", "foo\0bar", "foo/bar"];
    auto pfdep = [`foo\bar`, "*.txt"];
    version (Windows) invalid ~= pfdep;
    else version (Posix) valid ~= pfdep;
    else static assert (0);

    import std.typetuple;
    foreach (T; TypeTuple!(char[], const(char)[], string, wchar[],
        const(wchar)[], wstring, dchar[], const(dchar)[], dstring))
    {
        foreach (fn; valid)
            assert (isValidFilename(to!T(fn)));
        foreach (fn; invalid)
            assert (!isValidFilename(to!T(fn)));
    }
}




/** Checks whether $(D path) is a valid _path.

    Generally, this function checks that $(D path) is not empty, and that
    each component of the path either satisfies $(LREF isValidFilename)
    or is equal to $(D ".") or $(D "..").
    It does $(I not) check whether the _path points to an existing file
    or directory; use $(XREF file,exists) for this purpose.

    On Windows, some special rules apply:
    $(UL
        $(LI If the second character of $(D path) is a colon ($(D ':')),
            the first character is interpreted as a drive letter, and
            must be in the range A-Z (case insensitive).)
        $(LI If $(D path) is on the form $(D `\\$(I server)\$(I share)\...`)
            (UNC path), $(LREF isValidFilename) is applied to $(I server)
            and $(I share) as well.)
        $(LI If $(D path) starts with $(D `\\?\`) (long UNC path), the
            only requirement for the rest of the string is that it does
            not contain the null character.)
        $(LI If $(D path) starts with $(D `\\.\`) (Win32 device namespace)
            this function returns $(D false); such paths are beyond the scope
            of this module.)
    )
*/
bool isValidPath(C)(in C[] path)  @safe pure nothrow  if (isSomeChar!C)
{
    if (path.empty) return false;

    // Check whether component is "." or "..", or whether it satisfies
    // isValidFilename.
    bool isValidComponent(in C[] component)  @safe pure nothrow
    {
        assert (component.length > 0);
        if (component[0] == '.')
        {
            if (component.length == 1) return true;
            else if (component.length == 2 && component[1] == '.') return true;
        }
        return isValidFilename(component);
    }

    if (path.length == 1)
        return isDirSeparator(path[0]) || isValidComponent(path);

    const(C)[] remainder;
    version (Windows)
    {
        if (isDirSeparator(path[0]) && isDirSeparator(path[1]))
        {
            // Some kind of UNC path
            if (path.length < 5)
            {
                // All valid UNC paths must have at least 5 characters
                return false;
            }
            else if (path[2] == '?')
            {
                // Long UNC path
                if (!isDirSeparator(path[3])) return false;
                foreach (c; path[4 .. $])
                {
                    if (c == '\0') return false;
                }
                return true;
            }
            else if (path[2] == '.')
            {
                // Win32 device namespace not supported
                return false;
            }
            else
            {
                // Normal UNC path, i.e. \\server\share\...
                size_t i = 2;
                while (i < path.length && !isDirSeparator(path[i])) ++i;
                if (i == path.length || !isValidFilename(path[2 .. i]))
                    return false;
                ++i; // Skip a single dir separator
                size_t j = i;
                while (j < path.length && !isDirSeparator(path[j])) ++j;
                if (!isValidFilename(path[i .. j])) return false;
                remainder = path[j .. $];
            }
        }
        else if (isDriveSeparator(path[1]))
        {
            import std.ascii;
            if (!isAlpha(path[0])) return false;
            remainder = path[2 .. $];
        }
        else
        {
            remainder = path;
        }
    }
    else version (Posix)
    {
        remainder = path;
    }
    else static assert (0);
    assert (remainder !is null);
    remainder = ltrimDirSeparators(remainder);

    // Check that each component satisfies isValidComponent.
    while (!remainder.empty)
    {
        size_t i = 0;
        while (i < remainder.length && !isDirSeparator(remainder[i])) ++i;
        assert (i > 0);
        if (!isValidComponent(remainder[0 .. i])) return false;
        remainder = ltrimDirSeparators(remainder[i .. $]);
    }

    // All criteria passed
    return true;
}


unittest
{
    assert (isValidPath("/foo/bar"));
    assert (!isValidPath("/foo\0/bar"));

    version (Windows)
    {
        assert (isValidPath(`c:\`));
        assert (isValidPath(`c:\foo`));
        assert (isValidPath(`c:\foo\.\bar\\\..\`));
        assert (!isValidPath(`!:\foo`));
        assert (!isValidPath(`c::\foo`));
        assert (!isValidPath(`c:\foo?`));
        assert (!isValidPath(`c:\foo.`));

        assert (isValidPath(`\\server\share`));
        assert (isValidPath(`\\server\share\foo`));
        assert (isValidPath(`\\server\share\\foo`));
        assert (!isValidPath(`\\\server\share\foo`));
        assert (!isValidPath(`\\server\\share\foo`));
        assert (!isValidPath(`\\ser*er\share\foo`));
        assert (!isValidPath(`\\server\sha?e\foo`));
        assert (!isValidPath(`\\server\share\|oo`));

        assert (isValidPath(`\\?\<>:"?*|/\..\.`));
        assert (!isValidPath("\\\\?\\foo\0bar"));

        assert (!isValidPath(`\\.\PhysicalDisk1`));
    }
}




/** Performs tilde expansion in paths on POSIX systems.
    On Windows, this function does nothing.

    There are two ways of using tilde expansion in a path. One
    involves using the tilde alone or followed by a path separator. In
    this case, the tilde will be expanded with the value of the
    environment variable $(D HOME).  The second way is putting
    a username after the tilde (i.e. $(D ~john/Mail)). Here,
    the username will be searched for in the user database
    (i.e. $(D /etc/passwd) on Unix systems) and will expand to
    whatever path is stored there.  The username is considered the
    string after the tilde ending at the first instance of a path
    separator.

    Note that using the $(D ~user) syntax may give different
    values from just $(D ~) if the environment variable doesn't
    match the value stored in the user database.

    When the environment variable version is used, the path won't
    be modified if the environment variable doesn't exist or it
    is empty. When the database version is used, the path won't be
    modified if the user doesn't exist in the database or there is
    not enough memory to perform the query.

    Returns:
    $(D inputPath) with the tilde expanded, or just $(D inputPath)
    if it could not be expanded.
    For Windows, $(D expandTilde) merely returns its argument $(D inputPath).

    Examples:
    -----
    void processFile(string path)
    {
        // Allow calling this function with paths such as ~/foo
        auto fullPath = expandTilde(path);
        ...
    }
    -----
*/
string expandTilde(string inputPath)
{
    version(Posix)
    {
        /*  Joins a path from a C string to the remainder of path.

            The last path separator from c_path is discarded. The result
            is joined to path[char_pos .. length] if char_pos is smaller
            than length, otherwise path is not appended to c_path.
        */
        static string combineCPathWithDPath(char* c_path, string path, size_t char_pos)
        {
            assert(c_path != null);
            assert(path.length > 0);
            assert(char_pos >= 0);

            // Search end of C string
            size_t end = std.c.string.strlen(c_path);

            // Remove trailing path separator, if any
            if (end && isDirSeparator(c_path[end - 1]))
                end--;

            // Create our own copy, as lifetime of c_path is undocumented
            string cp = c_path[0 .. end].idup;

            // Do we append something from path?
            if (char_pos < path.length)
                cp ~= path[char_pos .. $];

            return cp;
        }

        // Replaces the tilde from path with the environment variable HOME.
        static string expandFromEnvironment(string path)
        {
            assert(path.length >= 1);
            assert(path[0] == '~');

            // Get HOME and use that to replace the tilde.
            auto home = core.stdc.stdlib.getenv("HOME");
            if (home == null)
                return path;

            return combineCPathWithDPath(home, path, 1);
        }

        // Replaces the tilde from path with the path from the user database.
        static string expandFromDatabase(string path)
        {
            assert(path.length > 2 || (path.length == 2 && !isDirSeparator(path[1])));
            assert(path[0] == '~');

            // Extract username, searching for path separator.
            string username;
            auto last_char = std.algorithm.countUntil(path, dirSeparator[0]);

            if (last_char == -1)
            {
                username = path[1 .. $] ~ '\0';
                last_char = username.length + 1;
            }
            else
            {
                username = path[1 .. last_char] ~ '\0';
            }
            assert(last_char > 1);

          version (GNU_Unix_Have_getpwnam_r)
          {
            // Reserve C memory for the getpwnam_r() function.
            passwd result;
            int extra_memory_size = 5 * 1024;
            void* extra_memory;

            while (1)
            {
                extra_memory = std.c.stdlib.malloc(extra_memory_size);
                if (extra_memory == null)
                    goto Lerror;

                // Obtain info from database.
                passwd *verify;
                setErrno(0);
                if (getpwnam_r(cast(char*) username.ptr, &result, cast(char*) extra_memory, extra_memory_size,
                        &verify) == 0)
                {
                    // Failure if verify doesn't point at result.
                    if (verify != &result)
                        // username is not found, so return path[]
                        goto Lnotfound;
                    break;
                }

                if (errno != ERANGE)
                    goto Lerror;

                // extra_memory isn't large enough
                std.c.stdlib.free(extra_memory);
                extra_memory_size *= 2;
            }

            path = combineCPathWithDPath(result.pw_dir, path, last_char);

        Lnotfound:
            std.c.stdlib.free(extra_memory);
            return path;

        Lerror:
            // Errors are going to be caused by running out of memory
            if (extra_memory)
                std.c.stdlib.free(extra_memory);
            onOutOfMemoryError();
            return null;
          }
          else
          {
            passwd * result;
            
            /* This does not guarantee another thread will not
               use getpwnam at the same time */
            synchronized
            {
                result = getpwnam(username);
            }
            
            if (result)
                path = combineCPathWithDPath(result.pw_dir, path, last_char);
            return path;
          }
        }

        // Return early if there is no tilde in path.
        if (inputPath.length < 1 || inputPath[0] != '~')
            return inputPath;

        if (inputPath.length == 1 || isDirSeparator(inputPath[1]))
            return expandFromEnvironment(inputPath);
        else
            return expandFromDatabase(inputPath);
    }
    else version(Windows)
    {
        // Put here real windows implementation.
        return inputPath;
    }
    else
    {
        static assert(0); // Guard. Implement on other platforms.
    }
}


version(unittest) import std.process: environment;
unittest
{
    version (Posix)
    {
        // Retrieve the current home variable.
        auto oldHome = environment.get("HOME");

        // Testing when there is no environment variable.
        environment.remove("HOME");
        assert(expandTilde("~/") == "~/");
        assert(expandTilde("~") == "~");

        // Testing when an environment variable is set.
        environment["HOME"] = "dmd/test";
        assert(expandTilde("~/") == "dmd/test/");
        assert(expandTilde("~") == "dmd/test");

        // The same, but with a variable ending in a slash.
        environment["HOME"] = "dmd/test/";
        assert(expandTilde("~/") == "dmd/test/");
        assert(expandTilde("~") == "dmd/test");

        // Recover original HOME variable before continuing.
        if (oldHome !is null) environment["HOME"] = oldHome;
        else environment.remove("HOME");

        // Test user expansion for root. Are there unices without /root?
        version (OSX)
            assert(expandTilde("~root") == "/var/root", expandTilde("~root"));
        else
            assert(expandTilde("~root") == "/root", expandTilde("~root"));
        version (OSX)
            assert(expandTilde("~root/") == "/var/root/", expandTilde("~root/"));
        else
            assert(expandTilde("~root/") == "/root/", expandTilde("~root/"));
        assert(expandTilde("~Idontexist/hey") == "~Idontexist/hey");
    }
}




// =============================================================================
// Everything below this line is from an old version of std.path, and is
// scheduled for deprecation in February 2012.
// =============================================================================

// Deprecation message
import std.metastrings;
private template softDeprec(string vers, string date, string oldFunc, string newFunc)
{
    enum softDeprec = Format!("Notice: As of Phobos %s, std.path.%s has been scheduled " ~
                              "for deprecation in %s. Please use %s instead.",
                              vers, oldFunc, date, newFunc);
}


import std.algorithm, std.array, std.conv, std.file, std.process, std.string,
    std.traits;
import core.stdc.errno, core.stdc.stdlib;

version(Posix)
{
    private import core.sys.posix.pwd;
    private import core.exception : onOutOfMemoryError;
}

version(Windows)
{

    /* * String used to separate directory names in a path. Under
     *  Windows this is a backslash, under Linux a slash. */
    enum string sep = "\\";
    /* * Alternate version of sep[] used in Windows (a slash). Under
     *  Linux this is empty. */
    enum string altsep = "/";
    /* * Path separator string. A semi colon under Windows, a colon
     *  under Linux. */
    enum string pathsep = ";";
    /* * String used to separate lines, \r\n under Windows and \n
     * under Linux. */
    enum string linesep = "\r\n";   // / String used to separate lines.
    enum string curdir = ".";       // / String representing the current directory.
    enum string pardir = "..";      // / String representing the parent directory.
    
    static assert(sep.length == 1 && altsep.length == 1);
    private bool isSep(dchar ch) {
        return ch == sep[0] || ch == altsep[0];
    }
    
    private bool isSepOrDriveSep(dchar ch) {
        return isSep(ch) || ch == ':';
    }
}
version(Posix)
{
    /* * String used to separate directory names in a path. Under
     *  Windows this is a backslash, under Linux a slash. */
    enum string sep = "/";
    /* * Alternate version of sep[] used in Windows (a slash). Under
     *  Linux this is empty. */
    enum string altsep = "";
    /* * Path separator string. A semi colon under Windows, a colon
     *  under Linux. */
    enum string pathsep = ":";
    /* * String used to separate lines, \r\n under Windows and \n
     * under Linux. */
    enum string linesep = "\n";
    enum string curdir = ".";       // / String representing the current directory.
    enum string pardir = "..";      // / String representing the parent directory.
    
    static assert(sep.length == 1 && altsep.length == 0);
    private bool isSep(dchar ch) {
        return ch == sep[0];
    }
}

/* ****************************
 * Compare file names.
 * Returns:
 *      <table border=1 cellpadding=4 cellspacing=0>
 *      <tr> <td> &lt; 0        <td> filename1 &lt; filename2
 *      <tr> <td> = 0   <td> filename1 == filename2
 *      <tr> <td> &gt; 0        <td> filename1 &gt; filename2
 *      </table>
 */
int fcmp(alias pred = "a < b", S1, S2)(S1 s1, S2 s2)
    if (isSomeString!S1 && isSomeString!S2)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "fcmp", "filenameCmp"));
    version (Windows) return std.string.icmp(s1, s2);
    version (Posix)   return std.algorithm.cmp(s1, s2);
}

/* *************************
 * Extracts the extension from a filename or path.
 *
 * This function will search fullname from the end until the
 * first dot, path separator or first character of fullname is
 * reached. Under Windows, the drive letter separator (<i>colon</i>)
 * also terminates the search.
 *
 * Returns: If a dot was found, characters to its right are
 * returned. If a path separator was found, or fullname didn't
 * contain any dots or path separators, returns null.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * version(Windows)
 * {
 *     getExt(r"d:\path\foo.bat") // "bat"
 *     getExt(r"d:\path.two\bar") // null
 * }
 * version(Posix)
 * {
 *     getExt(r"/home/user.name/bar.")  // ""
 *     getExt(r"d:\\path.two\\bar")     // "two\\bar"
 *     getExt(r"/home/user/.resource")  // "resource"
 * }
 * -----
 */

string getExt()(string fullname)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "getExt", "extension"));
    auto i = fullname.length;
    while (i > 0)
    {
        if (fullname[i - 1] == '.')
            return fullname[i .. $];
        i--;
        version(Windows)
        {
            if (isSepOrDriveSep(fullname[i]))
                break;
        }
        else version(Posix)
        {
            if (isSep(fullname[i]))
                break;
        }
        else
        {
            static assert(0);
        }
    }
    return null;
}

version (OldStdPathUnittest) unittest
{
    debug(path) printf("path.getExt.unittest\n");
    string result;

    version (Windows)
        result = getExt("d:\\path\\foo.bat");
    version (Posix)
        result = getExt("/path/foo.bat");
    auto i = cmp(result, "bat");
    assert(i == 0);

    version (Windows)
        result = getExt("d:\\path\\foo.");
    version (Posix)
        result = getExt("d/path/foo.");
    i = cmp(result, "");
    assert(i == 0);

    version (Windows)
        result = getExt("d:\\path\\foo");
    version (Posix)
        result = getExt("d/path/foo");
    i = cmp(result, "");
    assert(i == 0);

    version (Windows)
        result = getExt("d:\\path.bar\\foo");
    version (Posix)
        result = getExt("/path.bar/foo");

    i = cmp(result, "");
    assert(i == 0);

    result = getExt("foo");
    i = cmp(result, "");
    assert(i == 0);
}

/* *************************
 * Returns the extensionless version of a filename or path.
 *
 * This function will search fullname from the end until the
 * first dot, path separator or first character of fullname is
 * reached. Under Windows, the drive letter separator (<i>colon</i>)
 * also terminates the search.
 *
 * Returns: If a dot was found, characters to its left are
 * returned. If a path separator was found, or fullname didn't
 * contain any dots or path separators, returns null.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * version(Windows)
 * {
 *     getName(r"d:\path\foo.bat") => "d:\path\foo"
 *     getName(r"d:\path.two\bar") => null
 * }
 * version(Posix)
 * {
 *     getName("/home/user.name/bar.")  => "/home/user.name/bar"
 *     getName(r"d:\path.two\bar") => "d:\path"
 *     getName("/home/user/.resource") => "/home/user/"
 * }
 * -----
 */

string getName()(string fullname)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "getName", "stripExtension"));
    auto i = fullname.length;
    while (i > 0)
    {
        if (fullname[i - 1] == '.')
            return fullname[0 .. i - 1];
        i--;
        version(Windows)
        {
            if (isSepOrDriveSep(fullname[i]))
                break;
        }
        else version(Posix)
        {
            if (isSep(fullname[i]))
                break;
        }
        else
        {
            static assert(0);
        }
    }
    return null;
}

version (OldStdPathUnittest) unittest
{
    debug(path) printf("path.getName.unittest\n");
    string result;

    result = getName("foo.bar");
    auto i = cmp(result, "foo");
    assert(i == 0);

    result = getName("d:\\path.two\\bar");
    version (Windows)
        i = cmp(result, "");
    version (Posix)
        i = cmp(result, "d:\\path");
    assert(i == 0);
}

/* *************************
 * Extracts the base name of a path and optionally chops off a
 * specific suffix.
 *
 * This function will search $(D_PARAM fullname) from the end until
 * the first path separator or first character of $(D_PARAM fullname)
 * is reached. Under Windows, the drive letter separator ($(I colon))
 * also terminates the search. After the search has ended, keep the
 * portion to the right of the separator if found, or the entire
 * $(D_PARAM fullname) otherwise. If the kept portion has suffix
 * $(D_PARAM extension), remove that suffix. Return the remaining string.
 *
 * Returns: The portion of $(D_PARAM fullname) left after the path
 * part and the extension part, if any, have been removed.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * version(Windows)
 * {
 *     basename(r"d:\path\foo.bat") => "foo.bat"
 *     basename(r"d:\path\foo", ".bat") => "foo"
 * }
 * version(Posix)
 * {
 *     basename("/home/user.name/bar.")  => "bar."
 *     basename("/home/user.name/bar.", ".")  => "bar"
 * }
 * -----
 */

Char[] basename(Char, ExtChar = immutable(char))(
        Char[] fullname, ExtChar[] extension = null)
    if (isSomeChar!Char && isSomeChar!ExtChar)
out (result)
{
    assert(result.length <= fullname.length);
}
body
{
    pragma (msg, softDeprec!("2.055", "February 2012", "basename", "baseName"));
    auto i = fullname.length;
    for (; i > 0; i--)
    {
        version(Windows)
        {
            if (isSepOrDriveSep(fullname[i - 1]))
                break;
        }
        else version(Posix)
        {
            if (isSep(fullname[i - 1]))
                break;
        }
        else
        {
            static assert(0);
        }
    }
    return chomp(fullname[i .. $],
            extension.length ? extension : "");
}

/* * Alias for $(D_PARAM basename), kept for backward
 * compatibility. New code should use $(D_PARAM basename). */
alias basename getBaseName;

version (OldStdPathUnittest) unittest
{
    debug(path) printf("path.basename.unittest\n");
    string result;

    version (Windows)
        result = basename("d:\\path\\foo.bat");
    version (Posix)
        result = basename("/path/foo.bat");
    //printf("result = '%.*s'\n", result);
    assert(result == "foo.bat");

    version (Windows)
        result = basename("a\\b");
    version (Posix)
        result = basename("a/b");
    assert(result == "b");

    version (Windows)
        result = basename("a\\b.cde", ".cde");
    version (Posix)
        result = basename("a/b.cde", ".cde");
    assert(result == "b");

    version (Windows)
    {
        assert(basename("abc/xyz") == "xyz");
        assert(basename("abc/") == "");
        assert(basename("C:/a/b") == "b");
        assert(basename(`C:\a/b`) == "b");
    }

    assert(basename("~/dmd.conf"w, ".conf"d) == "dmd");
    assert(basename("~/dmd.conf"d, ".conf"d) == "dmd");
    assert(basename("dmd.conf"w.dup, ".conf"d.dup) == "dmd");
}

/* *************************
 * Extracts the directory part of a path.
 *
 * This function will search $(D fullname) from the end until the
 * first path separator or first character of $(D fullname) is
 * reached. Under Windows, the drive letter separator ($(I colon))
 * also terminates the search.
 *
 * Returns: If a path separator was found, all the characters to its
 * left without any trailing path separators are returned. Otherwise,
 * $(D ".") is returned.
 *
 * The found path separator will be included in the returned string
 * if and only if it represents the root.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * version(Windows)
 * {
 *     assert(dirname(r"d:\path\foo.bat") == r"d:\path");
 *     assert(dirname(r"d:\path") == r"d:\");
 *     assert(dirname("d:foo.bat") == "d:.");
 *     assert(dirname("foo.bat") == ".");
 * }
 * version(Posix)
 * {
 *     assert(dirname("/home/user") == "/home");
 *     assert(dirname("/home") == "/");
 *     assert(dirname("user") == ".");
 * }
 * -----
 */

Char[] dirname(Char)(Char[] fullname)
    if (isSomeChar!Char)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "dirname", "dirName"));
    alias immutable(Char)[] ImmString;
    Char[] s = fullname;

    version (Posix)
    {
        enum ImmString    sep = .sep;
        enum ImmString curdir = .curdir;

        for (; !s.empty; s.popBack)
        {
            if (s.endsWith(sep))
                break;
        }
        if (s.empty)
        {
            return to!(Char[])(curdir);
        }

        // remove excess non-root slashes: "/home//" --> "/home"
        while (s.length > sep.length && s.endsWith(sep))
        {
            s.popBack;
        }
        return s;
    }
    else version (Windows)
    {
        enum ImmString    sep = .sep;
        enum ImmString altsep = .altsep;
        enum ImmString curdir = .curdir;
        enum ImmString drvsep = ":";

        bool foundSep;
        for (; !s.empty; s.popBack)
        {
            if (uint withWhat = s.endsWith(sep, altsep, drvsep))
            {
                foundSep = (withWhat != 3);
                break;
            }
        }
        if (!foundSep)
        {
            return to!(Char[])(s.empty ? curdir : s ~ curdir);
        }

        // remove excess non-root separators: "C:\\" --> "C:\"
        while (s.endsWith(sep) || s.endsWith(altsep))
        {
            auto ss = s.save;
            s.popBack;
            if (s.empty || s.endsWith(drvsep))
            {
                s = ss; // preserve path separator representing root
                break;
            }
        }
        return s;
    }
    else // unknown platform
    {
        static assert(0);
    }
}

version (OldStdPathUnittest) unittest
{
    assert(dirname("") == ".");
    assert(dirname("fileonly") == ".");

    version (Posix)
    {
        assert(dirname("/path/to/file") == "/path/to");
        assert(dirname("/home") == "/");

        assert(dirname("/dev/zero"w) == "/dev");
        assert(dirname("/dev/null"d) == "/dev");
        assert(dirname(".login"w.dup) == ".");
        assert(dirname(".login"d.dup) == ".");

        // doc example
        assert(dirname("/home/user") == "/home");
        assert(dirname("/home") == "/");
        assert(dirname("user") == ".");
    }
    version (Windows)
    {
        assert(dirname(r"\path\to\file") == r"\path\to");
        assert(dirname(r"\foo") == r"\");
        assert(dirname(r"c:\foo") == r"c:\");

        assert(dirname("\\Windows"w) == "\\");
        assert(dirname("\\Users"d) == "\\");
        assert(dirname("ntuser.dat"w.dup) == ".");
        assert(dirname("ntuser.dat"d.dup) == ".");

        // doc example
        assert(dirname(r"d:\path\foo.bat") == r"d:\path");
        assert(dirname(r"d:\path") == "d:\\");
        assert(dirname("d:foo.bat") == "d:.");
        assert(dirname("foo.bat") == ".");
    }

    {
        // fixed-length strings
        char[4] u = "abcd";
        wchar[4] w = "abcd";
        dchar[4] d = "abcd";
        assert(dirname(u) == ".");
        assert(dirname(w) == "."w);
        assert(dirname(d) == "."d);
    }
}

/* * Alias for $(D_PARAM dirname), kept for backward
 * compatibility. New code should use $(D_PARAM dirname). */
alias dirname getDirName;

version (OldStdPathUnittest) unittest
{
    string filename = "foo/bar";
    auto d = getDirName(filename);
    assert(d == "foo");
}

version (OldStdPathUnittest) unittest // dirname + basename
{
    static immutable Common_dirbasename_testcases =
    [
        [ "/usr/lib"  , "/usr"   , "lib"    ],
        [ "/usr/"     , "/usr"   , ""       ],
        [ "/usr"      , "/"      , "usr"    ],
        [ "/"         , "/"      , ""       ],

        [ "var/run"   , "var"    , "run"    ],
        [ "var/"      , "var"    , ""       ],
        [ "var"       , "."      , "var"    ],
        [ "."         , "."      , "."      ],

        [ "/usr///lib", "/usr"   , "lib"    ],
        [ "///usr///" , "///usr" , ""       ],
        [ "///usr"    , "/"      , "usr"    ],
        [ "///"       , "/"      , ""       ],
        [ "var///run" , "var"    , "run"    ],
        [ "var///"    , "var"    , ""       ],

        [ "a/b/c"     , "a/b"    , "c"      ],
        [ "a///c"     , "a"      , "c"      ],
        [ "/\u7A74"   , "/"      , "\u7A74" ],
        [ "/\u7A74/." , "/\u7A74", "."      ]
    ];

    static immutable Windows_dirbasename_testcases =
        Common_dirbasename_testcases ~
    [
        [ "C:\\Users\\7mi", "C:\\Users", "7mi"   ],
        [ "C:\\Users\\"   , "C:\\Users", ""      ],
        [ "C:\\Users"     , "C:\\"     , "Users" ],
        [ "C:\\"          , "C:\\"     , ""      ],

        [ "C:Temp"        , "C:."      , "Temp"  ],
        [ "C:"            , "C:."      , ""      ],
        [ "\\dmd\\src"    , "\\dmd"    , "src"   ],
        [ "\\dmd\\"       , "\\dmd"    , ""      ],
        [ "\\dmd"         , "\\"       , "dmd"   ],

        [ "C:/Users/7mi"  , "C:/Users" , "7mi"   ],
        [ "C:/Users/"     , "C:/Users" , ""      ],
        [ "C:/Users"      , "C:/"      , "Users" ],
        [ "C:/"           , "C:/"      , ""      ],

        [ "C:\\//WinNT"   , "C:\\"     , "WinNT" ],
        [ "C://\\WinNT"   , "C:/"      , "WinNT" ],

        [ `a\b\c`         , `a\b`      , "c"     ],
        [ `a\\\c`         , "a"        , "c"     ]
    ];

    version (Windows)
        alias Windows_dirbasename_testcases testcases;
    else
        alias Common_dirbasename_testcases testcases;

    foreach (tc; testcases)
    {
        string path = tc[0];
        string dir  = tc[1];
        string base = tc[2];

        assert(path.dirname == dir);
        assert(path.basename == base);
    }
}


/* *******************************
 * Extracts the drive letter of a path.
 *
 * This function will search fullname for a colon from the beginning.
 *
 * Returns: If a colon is found, all the characters to its left
 * plus the colon are returned.  Otherwise, null is returned.
 *
 * Under Linux, this function always returns null immediately.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * getDrive(r"d:\path\foo.bat") => "d:"
 * -----
 */

Char[] getDrive(Char)(Char[] fullname) if (isSomeChar!Char)
// out(result)
// {
//     assert(result.length <= fullname.length);
// }
body
{
    pragma (msg, softDeprec!("2.055", "February 2012", "getDrive", "driveName"));
    version(Windows)
    {
        foreach (i; 0 .. fullname.length)
        {
            if (fullname[i] == ':')
                return fullname[0 .. i + 1];
        }
        return null;
    }
    else version(Posix)
    {
        return null;
    }
    else
    {
        static assert(0);
    }
}

/* ***************************
 * Appends a default extension to a filename.
 *
 * This function first searches filename for an extension and
 * appends ext if there is none. ext should not have any leading
 * dots, one will be inserted between filename and ext if filename
 * doesn't already end with one.
 *
 * Returns: filename if it contains an extension, otherwise filename
 * + ext.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * defaultExt("foo.txt", "raw") => "foo.txt"
 * defaultExt("foo.", "raw") => "foo.raw"
 * defaultExt("bar", "raw") => "bar.raw"
 * -----
 */

string defaultExt()(string filename, string ext)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "defaultExt", "defaultExtension"));
    string existing;

    existing = getExt(filename);
    if (existing.length == 0)
    {
        // Check for filename ending in '.'
        if (filename.length && filename[$ - 1] == '.')
            filename ~= ext;
        else
            filename = filename ~ "." ~ ext;
    }
    return filename;
}


/* ***************************
 * Adds or replaces an extension to a filename.
 *
 * This function first searches filename for an extension and
 * replaces it with ext if found.  If there is no extension, ext
 * will be appended. ext should not have any leading dots, one will
 * be inserted between filename and ext if filename doesn't already
 * end with one.
 *
 * Returns: filename + ext if filename is extensionless. Otherwise
 * strips filename's extension off, appends ext and returns the
 * result.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * addExt("foo.txt", "raw") => "foo.raw"
 * addExt("foo.", "raw") => "foo.raw"
 * addExt("bar", "raw") => "bar.raw"
 * -----
 */

string addExt()(string filename, string ext)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "addExt", "setExtension"));
    string existing;

    existing = getExt(filename);
    if (existing.length == 0)
    {
        // Check for filename ending in '.'
        if (filename.length && filename[$ - 1] == '.')
            filename ~= ext;
        else
            filename = filename ~ "." ~ ext;
    }
    else
    {
        filename = filename[0 .. $ - existing.length] ~ ext;
    }
    return filename;
}


/* ************************************
 * Checks if path is absolute.
 *
 * Returns: non-zero if the path starts from the root directory (Linux) or
 * drive letter and root directory (Windows),
 * zero otherwise.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * version(Windows)
 * {
 *     isabs(r"relative\path") => 0
 *     isabs(r"\relative\path") => 0
 *     isabs(r"d:\absolute") => 1
 * }
 * version(Posix)
 * {
 *     isabs("/home/user") => 1
 *     isabs("foo") => 0
 * }
 * -----
 */

bool isabs()(in char[] path)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "isabs", "isAbsolute"));
    auto d = getDrive(path);
    version (Windows)
    {
        return d.length < path.length && isSep(path[d.length]);
    }
    else version (Posix)
    {
        return d.length < path.length && isSep(path[d.length]);
    }
    else
    {
        static assert(0);
    }
}

version (OldStdPathUnittest) unittest
{
    debug(path) printf("path.isabs.unittest\n");

    version (Windows)
    {
        assert(!isabs(r"relative\path"));
        assert(isabs(r"\relative\path"));
        assert(isabs(r"d:\absolute"));
    }
    version (Posix)
    {
        assert(isabs("/home/user"));
        assert(!isabs("foo"));
    }
}

/* *
 * Converts a relative path into an absolute path.
 */
string rel2abs()(string path)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "rel2abs", "absolutePath"));
    if (!path.length || isabs(path))
    {
        return path;
    }
    auto myDir = getcwd;
    if (path.startsWith(curdir))
    {
        auto p = path[curdir.length .. $];
        if (p.startsWith(sep))
            path = p[sep.length .. $];
        else if (altsep.length && p.startsWith(altsep))
            path = p[altsep.length .. $];
        else if (!p.length)
            path = null;
    }
    return myDir.endsWith(sep) || path.length
        ? join(myDir, path)
        : myDir;
}

version (OldStdPathUnittest) unittest
{
    version (Posix)
    {
        auto myDir = getcwd();
        scope(exit) std.file.chdir(myDir);
        std.file.chdir("/");
        assert(rel2abs(".") == "/", rel2abs("."));
        assert(rel2abs("bin") == "/bin", rel2abs("bin"));
        assert(rel2abs("./bin") == "/bin", rel2abs("./bin"));
        std.file.chdir("bin");
        assert(rel2abs(".") == "/bin", rel2abs("."));
    }
}

/* ************************************
 * Joins two or more path components.
 *
 * If p1 doesn't have a trailing path separator, one will be appended
 * to it before concatenating p2.
 *
 * Returns: p1 ~ p2. However, if p2 is an absolute path, only p2
 * will be returned.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * version(Windows)
 * {
 *     join(r"c:\foo", "bar") => r"c:\foo\bar"
 *     join("foo", r"d:\bar") => r"d:\bar"
 * }
 * version(Posix)
 * {
 *     join("/foo/", "bar") => "/foo/bar"
 *     join("/foo", "/bar") => "/bar"
 * }
 * -----
 */

string join()(const(char)[] p1, const(char)[] p2, const(char)[][] more...)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "join", "buildPath"));
    if (more.length)
    {
        // more than two components present
        return join(join(p1, p2), more[0], more[1 .. $]);
    }

    // Focus on exactly two components
    if (!p2.length)
        return p1.idup;
    if (!p1.length)
        return p2.idup;

    version (Posix)
    {
        if (isabs(p2)) return p2.idup;
        if (p1.endsWith(sep) || altsep.length && p1.endsWith(altsep))
        {
            return cast(string) (p1 ~ p2);
        }
        return cast(string) (p1 ~ sep ~ p2);
    }
    else version (Windows)
    {
        string p;
        const(char)[] d1;

        if (getDrive(p2))
        {
            p = p2.idup;
        }
        else
        {
            d1 = getDrive(p1);
            if (p1.length == d1.length)
            {
                p = cast(string) (p1 ~ p2);
            }
            else if (isSep(p2[0]))
            {
                if (d1.length == 0)
                    p = p2.idup;
                else if (isSep(p1[$ - 1]))
                    p = cast(string) (p1 ~ p2[1 .. $]);
                else
                    p = cast(string) (p1 ~ p2);
            }
            else if (isSep(p1[$ - 1]))
            {
                p = cast(string) (p1 ~ p2);
            }
            else
            {
                p = cast(string)(p1 ~ sep ~ p2);
            }
        }
        return p;
    }
    else // unknown platform
    {
        static assert(0);
    }
}

version (OldStdPathUnittest) unittest
{
    debug(path) printf("path.join.unittest\n");

    string p;
    sizediff_t i;

    p = join("foo", "bar");
    version (Windows)
        i = cmp(p, "foo\\bar");
    version (Posix)
        i = cmp(p, "foo/bar");
    assert(i == 0);

    version (Windows)
    {   p = join("foo\\", "bar");
        i = cmp(p, "foo\\bar");
    }
    version (Posix)
    {   p = join("foo/", "bar");
        i = cmp(p, "foo/bar");
    }
    assert(i == 0);

    version (Windows)
    {   p = join("foo", "\\bar");
        i = cmp(p, "\\bar");
    }
    version (Posix)
    {   p = join("foo", "/bar");
        i = cmp(p, "/bar");
    }
    assert(i == 0);

    version (Windows)
    {   p = join("foo\\", "\\bar");
        i = cmp(p, "\\bar");
    }
    version (Posix)
    {   p = join("foo/", "/bar");
        i = cmp(p, "/bar");
    }
    assert(i == 0);

    version(Windows)
    {
        p = join("d:", "bar");
        i = cmp(p, "d:bar");
        assert(i == 0);

        p = join("d:\\", "bar");
        i = cmp(p, "d:\\bar");
        assert(i == 0);

        p = join("d:\\", "\\bar");
        i = cmp(p, "d:\\bar");
        assert(i == 0);

        p = join("d:\\foo", "bar");
        i = cmp(p, "d:\\foo\\bar");
        assert(i == 0);

        p = join("d:", "\\bar");
        i = cmp(p, "d:\\bar");
        assert(i == 0);

        p = join("foo", "d:");
        i = cmp(p, "d:");
        assert(i == 0);

        p = join("foo", "d:\\");
        i = cmp(p, "d:\\");
        assert(i == 0);

        p = join("foo", "d:\\bar");
        i = cmp(p, "d:\\bar");
        assert(i == 0);

        assert(join("d","dmd","src") == "d\\dmd\\src");
    }

    assert (join("", "foo") == "foo");
    assert (join("foo", "") == "foo");
}


/* ********************************
 * Matches filename characters.
 *
 * Under Windows, the comparison is done ignoring case. Under Linux
 * an exact match is performed.
 *
 * Returns: non zero if c1 matches c2, zero otherwise.
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * version(Windows)
 * {
 *     fncharmatch('a', 'b') => 0
 *     fncharmatch('A', 'a') => 1
 * }
 * version(Posix)
 * {
 *     fncharmatch('a', 'b') => 0
 *     fncharmatch('A', 'a') => 0
 * }
 * -----
 */

bool fncharmatch()(dchar c1, dchar c2)
{
    pragma (msg, softDeprec!("2.055", "February 2012", "fncharmatch", "filenameCharCmp"));
    version (Windows)
    {
        if (c1 != c2)
        {
            if ('A' <= c1 && c1 <= 'Z')
                c1 += cast(char)'a' - 'A';
            if ('A' <= c2 && c2 <= 'Z')
                c2 += cast(char)'a' - 'A';
            return c1 == c2;
        }
        return true;
    }
    else version (Posix)
    {
        return c1 == c2;
    }
    else
    {
        static assert(0);
    }
}

/* ***********************************
 * Matches a pattern against a filename.
 *
 * Some characters of pattern have special a meaning (they are
 * <i>meta-characters</i>) and <b>can't</b> be escaped. These are:
 * <p><table>
 * <tr><td><b>*</b></td>
 *     <td>Matches 0 or more instances of any character.</td></tr>
 * <tr><td><b>?</b></td>
 *     <td>Matches exactly one instances of any character.</td></tr>
 * <tr><td><b>[</b><i>chars</i><b>]</b></td>
 *     <td>Matches one instance of any character that appears
 *     between the brackets.</td></tr>
 * <tr><td><b>[!</b><i>chars</i><b>]</b></td>
 *     <td>Matches one instance of any character that does not appear
 *     between the brackets after the exclamation mark.</td></tr>
 * </table><p>
 * Internally individual character comparisons are done calling
 * fncharmatch(), so its rules apply here too. Note that path
 * separators and dots don't stop a meta-character from matching
 * further portions of the filename.
 *
 * Returns: non zero if pattern matches filename, zero otherwise.
 *
 * See_Also: fncharmatch().
 *
 * Throws: Nothing.
 *
 * Examples:
 * -----
 * version(Windows)
 * {
 *     fnmatch("foo.bar", "*") => 1
 *     fnmatch(r"foo/foo\bar", "f*b*r") => 1
 *     fnmatch("foo.bar", "f?bar") => 0
 *     fnmatch("Goo.bar", "[fg]???bar") => 1
 *     fnmatch(r"d:\foo\bar", "d*foo?bar") => 1
 * }
 * version(Posix)
 * {
 *     fnmatch("Go*.bar", "[fg]???bar") => 0
 *     fnmatch("/foo*home/bar", "?foo*bar") => 1
 *     fnmatch("foobar", "foo?bar") => 1
 * }
 * -----
 */
bool fnmatch()(const(char)[] filename, const(char)[] pattern)
in
{
    // Verify that pattern[] is valid
    assert(balancedParens(pattern, '[', ']', 0));
    assert(balancedParens(pattern, '{', '}', 0));
}
body
{
    pragma (msg, softDeprec!("2.055", "February 2012", "fnmatch", "globMatch"));
        size_t ni; // current character in filename

        foreach (pi; 0 .. pattern.length)
        {
            char pc = pattern[pi];
            switch (pc)
            {
            case '*':
                if (pi + 1 == pattern.length)
                    return true;
                foreach (j; ni .. filename.length)
                {
                    if (fnmatch(filename[j .. $],
                                    pattern[pi + 1 .. $]))
                        return true;
                }
                return false;

            case '?':
                if (ni == filename.length)
                    return false;
                ni++;
                break;

            case '[': {
                if (ni == filename.length)
                    return false;
                auto nc = filename[ni];
                ni++;
                auto not = false;
                pi++;
                if (pattern[pi] == '!')
                {
                    not = true;
                    pi++;
                }
                auto anymatch = false;
                while (1)
                {
                    pc = pattern[pi];
                    if (pc == ']')
                        break;
                    if (!anymatch && fncharmatch(nc, pc))
                        anymatch = true;
                    pi++;
                }
                if (anymatch == not)
                    return false;
            }
                break;

            case '{': {
                // find end of {} section
                auto piRemain = pi;
                for (; piRemain < pattern.length
                         && pattern[piRemain] != '}'; piRemain++)
                {}

                if (piRemain < pattern.length) piRemain++;
                pi++;

                while (pi < pattern.length)
                {
                    auto pi0 = pi;
                    pc = pattern[pi];
                    // find end of current alternative
                    for (; pi<pattern.length && pc!='}' && pc!=','; pi++)
                    {
                        pc = pattern[pi];
                    }

                    if (pi0 == pi)
                    {
                        if (fnmatch(filename[ni..$], pattern[piRemain..$]))
                        {
                            return true;
                        }
                        pi++;
                    }
                    else
                    {
                        if (fnmatch(filename[ni..$],
                                        pattern[pi0..pi-1]
                                        ~ pattern[piRemain..$]))
                        {
                            return true;
                        }
                    }
                    if (pc == '}')
                    {
                        break;
                    }
                }
            }
                return false;

            default:
                if (ni == filename.length)
                    return false;
                if (!fncharmatch(pc, filename[ni]))
                    return false;
                ni++;
                break;
            }
        }
    assert(ni >= filename.length);
        return ni == filename.length;
}

version (OldStdPathUnittest) unittest
{
    debug(path) printf("path.fnmatch.unittest\n");

    version (Win32)
        assert(fnmatch("foo", "Foo"));
    version (linux)
        assert(!fnmatch("foo", "Foo"));
    assert(fnmatch("foo", "*"));
    assert(fnmatch("foo.bar", "*"));
    assert(fnmatch("foo.bar", "*.*"));
    assert(fnmatch("foo.bar", "foo*"));
    assert(fnmatch("foo.bar", "f*bar"));
    assert(fnmatch("foo.bar", "f*b*r"));
    assert(fnmatch("foo.bar", "f???bar"));
    assert(fnmatch("foo.bar", "[fg]???bar"));
    assert(fnmatch("foo.bar", "[!gh]*bar"));

    assert(!fnmatch("foo", "bar"));
    assert(!fnmatch("foo", "*.*"));
    assert(!fnmatch("foo.bar", "f*baz"));
    assert(!fnmatch("foo.bar", "f*b*x"));
    assert(!fnmatch("foo.bar", "[gh]???bar"));
    assert(!fnmatch("foo.bar", "[!fg]*bar"));
    assert(!fnmatch("foo.bar", "[fg]???baz"));

    assert(fnmatch("foo.bar", "{foo,bif}.bar"));
    assert(fnmatch("bif.bar", "{foo,bif}.bar"));

    assert(fnmatch("bar.foo", "bar.{foo,bif}"));
    assert(fnmatch("bar.bif", "bar.{foo,bif}"));

    assert(fnmatch("bar.fooz", "bar.{foo,bif}z"));
    assert(fnmatch("bar.bifz", "bar.{foo,bif}z"));

    assert(fnmatch("bar.foo", "bar.{biz,,baz}foo"));
    assert(fnmatch("bar.foo", "bar.{biz,}foo"));
    assert(fnmatch("bar.foo", "bar.{,biz}foo"));
    assert(fnmatch("bar.foo", "bar.{}foo"));

    assert(fnmatch("bar.foo", "bar.{ar,,fo}o"));
    assert(fnmatch("bar.foo", "bar.{,ar,fo}o"));
    assert(fnmatch("bar.o", "bar.{,ar,fo}o"));
}