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
// Copyright (c) The camino Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
#![warn(missing_docs)]
#![cfg_attr(doc_cfg, feature(doc_cfg, doc_auto_cfg))]
//! UTF-8 encoded paths.
//!
//! `camino` is an extension of the `std::path` module that adds new [`Utf8PathBuf`] and [`Utf8Path`]
//! types. These are like the standard library's [`PathBuf`] and [`Path`] types, except they are
//! guaranteed to only contain UTF-8 encoded data. Therefore, they expose the ability to get their
//! contents as strings, they implement `Display`, etc.
//!
//! The `std::path` types are not guaranteed to be valid UTF-8. This is the right decision for the standard library,
//! since it must be as general as possible. However, on all platforms, non-Unicode paths are vanishingly uncommon for a
//! number of reasons:
//! * Unicode won. There are still some legacy codebases that store paths in encodings like Shift-JIS, but most
//! have been converted to Unicode at this point.
//! * Unicode is the common subset of supported paths across Windows and Unix platforms. (On Windows, Rust stores paths
//! as [an extension to UTF-8](https://simonsapin.github.io/wtf-8/), and converts them to UTF-16 at Win32
//! API boundaries.)
//! * There are already many systems, such as Cargo, that only support UTF-8 paths. If your own tool interacts with any such
//! system, you can assume that paths are valid UTF-8 without creating any additional burdens on consumers.
//! * The ["makefile problem"](https://www.mercurial-scm.org/wiki/EncodingStrategy#The_.22makefile_problem.22)
//! (which also applies to `Cargo.toml`, and any other metadata file that lists the names of other files) has *no general,
//! cross-platform solution* in systems that support non-UTF-8 paths. However, restricting paths to UTF-8 eliminates
//! this problem.
//!
//! Therefore, many programs that want to manipulate paths *do* assume they contain UTF-8 data, and convert them to `str`s
//! as necessary. However, because this invariant is not encoded in the `Path` type, conversions such as
//! `path.to_str().unwrap()` need to be repeated again and again, creating a frustrating experience.
//!
//! Instead, `camino` allows you to check that your paths are UTF-8 *once*, and then manipulate them
//! as valid UTF-8 from there on, avoiding repeated lossy and confusing conversions.
use std::{
borrow::{Borrow, Cow},
cmp::Ordering,
convert::{Infallible, TryFrom, TryInto},
error,
ffi::{OsStr, OsString},
fmt,
fs::{self, Metadata},
hash::{Hash, Hasher},
io,
iter::FusedIterator,
ops::Deref,
path::*,
rc::Rc,
str::FromStr,
sync::Arc,
};
#[cfg(feature = "proptest1")]
mod proptest_impls;
#[cfg(feature = "serde1")]
mod serde_impls;
#[cfg(test)]
mod tests;
/// An owned, mutable UTF-8 path (akin to [`String`]).
///
/// This type provides methods like [`push`] and [`set_extension`] that mutate
/// the path in place. It also implements [`Deref`] to [`Utf8Path`], meaning that
/// all methods on [`Utf8Path`] slices are available on `Utf8PathBuf` values as well.
///
/// [`push`]: Utf8PathBuf::push
/// [`set_extension`]: Utf8PathBuf::set_extension
///
/// # Examples
///
/// You can use [`push`] to build up a `Utf8PathBuf` from
/// components:
///
/// ```
/// use camino::Utf8PathBuf;
///
/// let mut path = Utf8PathBuf::new();
///
/// path.push(r"C:\");
/// path.push("windows");
/// path.push("system32");
///
/// path.set_extension("dll");
/// ```
///
/// However, [`push`] is best used for dynamic situations. This is a better way
/// to do this when you know all of the components ahead of time:
///
/// ```
/// use camino::Utf8PathBuf;
///
/// let path: Utf8PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
/// ```
///
/// We can still do better than this! Since these are all strings, we can use
/// `From::from`:
///
/// ```
/// use camino::Utf8PathBuf;
///
/// let path = Utf8PathBuf::from(r"C:\windows\system32.dll");
/// ```
///
/// Which method works best depends on what kind of situation you're in.
// NB: Internal PathBuf must only contain utf8 data
#[derive(Clone, Default)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde1", serde(transparent))]
#[repr(transparent)]
pub struct Utf8PathBuf(PathBuf);
impl Utf8PathBuf {
/// Allocates an empty `Utf8PathBuf`.
///
/// # Examples
///
/// ```
/// use camino::Utf8PathBuf;
///
/// let path = Utf8PathBuf::new();
/// ```
#[must_use]
pub fn new() -> Utf8PathBuf {
Utf8PathBuf(PathBuf::new())
}
/// Creates a new `Utf8PathBuf` from a `PathBuf` containing valid UTF-8 characters.
///
/// Errors with the original `PathBuf` if it is not valid UTF-8.
///
/// For a version that returns a type that implements [`std::error::Error`], use the
/// `TryFrom<PathBuf>` impl.
///
/// # Examples
///
/// ```
/// use camino::Utf8PathBuf;
/// use std::ffi::OsStr;
/// # #[cfg(unix)]
/// use std::os::unix::ffi::OsStrExt;
/// use std::path::PathBuf;
///
/// let unicode_path = PathBuf::from("/valid/unicode");
/// Utf8PathBuf::from_path_buf(unicode_path).expect("valid Unicode path succeeded");
///
/// // Paths on Unix can be non-UTF-8.
/// # #[cfg(unix)]
/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
/// # #[cfg(unix)]
/// let non_unicode_path = PathBuf::from(non_unicode_str);
/// # #[cfg(unix)]
/// Utf8PathBuf::from_path_buf(non_unicode_path).expect_err("non-Unicode path failed");
/// ```
pub fn from_path_buf(path: PathBuf) -> Result<Utf8PathBuf, PathBuf> {
match path.into_os_string().into_string() {
Ok(string) => Ok(Utf8PathBuf::from(string)),
Err(os_string) => Err(PathBuf::from(os_string)),
}
}
/// Converts a `Utf8PathBuf` to a [`PathBuf`].
///
/// This is equivalent to the `From<Utf8PathBuf> for PathBuf` impl, but may aid in type
/// inference.
///
/// # Examples
///
/// ```
/// use camino::Utf8PathBuf;
/// use std::path::PathBuf;
///
/// let utf8_path_buf = Utf8PathBuf::from("foo.txt");
/// let std_path_buf = utf8_path_buf.into_std_path_buf();
/// assert_eq!(std_path_buf.to_str(), Some("foo.txt"));
///
/// // Convert back to a Utf8PathBuf.
/// let new_utf8_path_buf = Utf8PathBuf::from_path_buf(std_path_buf).unwrap();
/// assert_eq!(new_utf8_path_buf, "foo.txt");
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
pub fn into_std_path_buf(self) -> PathBuf {
self.into()
}
/// Creates a new `Utf8PathBuf` with a given capacity used to create the internal [`PathBuf`].
/// See [`with_capacity`] defined on [`PathBuf`].
///
/// *Requires Rust 1.44 or newer.*
///
/// # Examples
///
/// ```
/// use camino::Utf8PathBuf;
///
/// let mut path = Utf8PathBuf::with_capacity(10);
/// let capacity = path.capacity();
///
/// // This push is done without reallocating
/// path.push(r"C:\");
///
/// assert_eq!(capacity, path.capacity());
/// ```
///
/// [`with_capacity`]: PathBuf::with_capacity
#[cfg(path_buf_capacity)]
#[must_use]
pub fn with_capacity(capacity: usize) -> Utf8PathBuf {
Utf8PathBuf(PathBuf::with_capacity(capacity))
}
/// Coerces to a [`Utf8Path`] slice.
///
/// # Examples
///
/// ```
/// use camino::{Utf8Path, Utf8PathBuf};
///
/// let p = Utf8PathBuf::from("/test");
/// assert_eq!(Utf8Path::new("/test"), p.as_path());
/// ```
#[must_use]
pub fn as_path(&self) -> &Utf8Path {
// SAFETY: every Utf8PathBuf constructor ensures that self is valid UTF-8
unsafe { Utf8Path::assume_utf8(&*self.0) }
}
/// Extends `self` with `path`.
///
/// If `path` is absolute, it replaces the current path.
///
/// On Windows:
///
/// * if `path` has a root but no prefix (e.g., `\windows`), it
/// replaces everything except for the prefix (if any) of `self`.
/// * if `path` has a prefix but no root, it replaces `self`.
///
/// # Examples
///
/// Pushing a relative path extends the existing path:
///
/// ```
/// use camino::Utf8PathBuf;
///
/// let mut path = Utf8PathBuf::from("/tmp");
/// path.push("file.bk");
/// assert_eq!(path, Utf8PathBuf::from("/tmp/file.bk"));
/// ```
///
/// Pushing an absolute path replaces the existing path:
///
/// ```
/// use camino::Utf8PathBuf;
///
/// let mut path = Utf8PathBuf::from("/tmp");
/// path.push("/etc");
/// assert_eq!(path, Utf8PathBuf::from("/etc"));
/// ```
pub fn push(&mut self, path: impl AsRef<Utf8Path>) {
self.0.push(&path.as_ref().0)
}
/// Truncates `self` to [`self.parent`].
///
/// Returns `false` and does nothing if [`self.parent`] is [`None`].
/// Otherwise, returns `true`.
///
/// [`self.parent`]: Utf8Path::parent
///
/// # Examples
///
/// ```
/// use camino::{Utf8Path, Utf8PathBuf};
///
/// let mut p = Utf8PathBuf::from("/spirited/away.rs");
///
/// p.pop();
/// assert_eq!(Utf8Path::new("/spirited"), p);
/// p.pop();
/// assert_eq!(Utf8Path::new("/"), p);
/// ```
pub fn pop(&mut self) -> bool {
self.0.pop()
}
/// Updates [`self.file_name`] to `file_name`.
///
/// If [`self.file_name`] was [`None`], this is equivalent to pushing
/// `file_name`.
///
/// Otherwise it is equivalent to calling [`pop`] and then pushing
/// `file_name`. The new path will be a sibling of the original path.
/// (That is, it will have the same parent.)
///
/// [`self.file_name`]: Utf8Path::file_name
/// [`pop`]: Utf8PathBuf::pop
///
/// # Examples
///
/// ```
/// use camino::Utf8PathBuf;
///
/// let mut buf = Utf8PathBuf::from("/");
/// assert_eq!(buf.file_name(), None);
/// buf.set_file_name("bar");
/// assert_eq!(buf, Utf8PathBuf::from("/bar"));
/// assert!(buf.file_name().is_some());
/// buf.set_file_name("baz.txt");
/// assert_eq!(buf, Utf8PathBuf::from("/baz.txt"));
/// ```
pub fn set_file_name(&mut self, file_name: impl AsRef<str>) {
self.0.set_file_name(file_name.as_ref())
}
/// Updates [`self.extension`] to `extension`.
///
/// Returns `false` and does nothing if [`self.file_name`] is [`None`],
/// returns `true` and updates the extension otherwise.
///
/// If [`self.extension`] is [`None`], the extension is added; otherwise
/// it is replaced.
///
/// [`self.file_name`]: Utf8Path::file_name
/// [`self.extension`]: Utf8Path::extension
///
/// # Examples
///
/// ```
/// use camino::{Utf8Path, Utf8PathBuf};
///
/// let mut p = Utf8PathBuf::from("/feel/the");
///
/// p.set_extension("force");
/// assert_eq!(Utf8Path::new("/feel/the.force"), p.as_path());
///
/// p.set_extension("dark_side");
/// assert_eq!(Utf8Path::new("/feel/the.dark_side"), p.as_path());
/// ```
pub fn set_extension(&mut self, extension: impl AsRef<str>) -> bool {
self.0.set_extension(extension.as_ref())
}
/// Consumes the `Utf8PathBuf`, yielding its internal [`String`] storage.
///
/// # Examples
///
/// ```
/// use camino::Utf8PathBuf;
///
/// let p = Utf8PathBuf::from("/the/head");
/// let s = p.into_string();
/// assert_eq!(s, "/the/head");
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
pub fn into_string(self) -> String {
self.into_os_string().into_string().unwrap()
}
/// Consumes the `Utf8PathBuf`, yielding its internal [`OsString`] storage.
///
/// # Examples
///
/// ```
/// use camino::Utf8PathBuf;
/// use std::ffi::OsStr;
///
/// let p = Utf8PathBuf::from("/the/head");
/// let s = p.into_os_string();
/// assert_eq!(s, OsStr::new("/the/head"));
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
pub fn into_os_string(self) -> OsString {
self.0.into_os_string()
}
/// Converts this `Utf8PathBuf` into a [boxed](Box) [`Utf8Path`].
#[must_use = "`self` will be dropped if the result is not used"]
pub fn into_boxed_path(self) -> Box<Utf8Path> {
let ptr = Box::into_raw(self.0.into_boxed_path()) as *mut Utf8Path;
// SAFETY:
// * self is valid UTF-8
// * ptr was constructed by consuming self so it represents an owned path
// * Utf8Path is marked as #[repr(transparent)] so the conversion from *mut Path to
// *mut Utf8Path is valid
unsafe { Box::from_raw(ptr) }
}
/// Invokes [`capacity`] on the underlying instance of [`PathBuf`].
///
/// *Requires Rust 1.44 or newer.*
///
/// [`capacity`]: PathBuf::capacity
#[cfg(path_buf_capacity)]
#[must_use]
pub fn capacity(&self) -> usize {
self.0.capacity()
}
/// Invokes [`clear`] on the underlying instance of [`PathBuf`].
///
/// *Requires Rust 1.44 or newer.*
///
/// [`clear`]: PathBuf::clear
#[cfg(path_buf_capacity)]
pub fn clear(&mut self) {
self.0.clear()
}
/// Invokes [`reserve`] on the underlying instance of [`PathBuf`].
///
/// *Requires Rust 1.44 or newer.*
///
/// [`reserve`]: PathBuf::reserve
#[cfg(path_buf_capacity)]
pub fn reserve(&mut self, additional: usize) {
self.0.reserve(additional)
}
/// Invokes [`try_reserve`] on the underlying instance of [`PathBuf`].
///
/// *Requires Rust 1.63 or newer.*
///
/// [`try_reserve`]: PathBuf::try_reserve
#[cfg(try_reserve_2)]
#[inline]
pub fn try_reserve(
&mut self,
additional: usize,
) -> Result<(), std::collections::TryReserveError> {
self.0.try_reserve(additional)
}
/// Invokes [`reserve_exact`] on the underlying instance of [`PathBuf`].
///
/// *Requires Rust 1.44 or newer.*
///
/// [`reserve_exact`]: PathBuf::reserve_exact
#[cfg(path_buf_capacity)]
pub fn reserve_exact(&mut self, additional: usize) {
self.0.reserve_exact(additional)
}
/// Invokes [`try_reserve_exact`] on the underlying instance of [`PathBuf`].
///
/// *Requires Rust 1.63 or newer.*
///
/// [`try_reserve_exact`]: PathBuf::try_reserve_exact
#[cfg(try_reserve_2)]
#[inline]
pub fn try_reserve_exact(
&mut self,
additional: usize,
) -> Result<(), std::collections::TryReserveError> {
self.0.try_reserve_exact(additional)
}
/// Invokes [`shrink_to_fit`] on the underlying instance of [`PathBuf`].
///
/// *Requires Rust 1.44 or newer.*
///
/// [`shrink_to_fit`]: PathBuf::shrink_to_fit
#[cfg(path_buf_capacity)]
pub fn shrink_to_fit(&mut self) {
self.0.shrink_to_fit()
}
/// Invokes [`shrink_to`] on the underlying instance of [`PathBuf`].
///
/// *Requires Rust 1.56 or newer.*
///
/// [`shrink_to`]: PathBuf::shrink_to
#[cfg(shrink_to)]
#[inline]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.0.shrink_to(min_capacity)
}
}
impl Deref for Utf8PathBuf {
type Target = Utf8Path;
fn deref(&self) -> &Utf8Path {
self.as_path()
}
}
impl fmt::Debug for Utf8PathBuf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl fmt::Display for Utf8PathBuf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.as_str(), f)
}
}
impl<P: AsRef<Utf8Path>> Extend<P> for Utf8PathBuf {
fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
for path in iter {
self.push(path);
}
}
}
/// A slice of a UTF-8 path (akin to [`str`]).
///
/// This type supports a number of operations for inspecting a path, including
/// breaking the path into its components (separated by `/` on Unix and by either
/// `/` or `\` on Windows), extracting the file name, determining whether the path
/// is absolute, and so on.
///
/// This is an *unsized* type, meaning that it must always be used behind a
/// pointer like `&` or [`Box`]. For an owned version of this type,
/// see [`Utf8PathBuf`].
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// // Note: this example does work on Windows
/// let path = Utf8Path::new("./foo/bar.txt");
///
/// let parent = path.parent();
/// assert_eq!(parent, Some(Utf8Path::new("./foo")));
///
/// let file_stem = path.file_stem();
/// assert_eq!(file_stem, Some("bar"));
///
/// let extension = path.extension();
/// assert_eq!(extension, Some("txt"));
/// ```
// NB: Internal Path must only contain utf8 data
#[repr(transparent)]
pub struct Utf8Path(Path);
impl Utf8Path {
/// Directly wraps a string slice as a `Utf8Path` slice.
///
/// This is a cost-free conversion.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// Utf8Path::new("foo.txt");
/// ```
///
/// You can create `Utf8Path`s from `String`s, or even other `Utf8Path`s:
///
/// ```
/// use camino::Utf8Path;
///
/// let string = String::from("foo.txt");
/// let from_string = Utf8Path::new(&string);
/// let from_path = Utf8Path::new(&from_string);
/// assert_eq!(from_string, from_path);
/// ```
pub fn new(s: &(impl AsRef<str> + ?Sized)) -> &Utf8Path {
let path = Path::new(s.as_ref());
// SAFETY: s is a str which means it is always valid UTF-8
unsafe { Utf8Path::assume_utf8(path) }
}
/// Converts a [`Path`] to a `Utf8Path`.
///
/// Returns `None` if the path is not valid UTF-8.
///
/// For a version that returns a type that implements [`std::error::Error`], use the
/// `TryFrom<&Path>` impl.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
/// use std::ffi::OsStr;
/// # #[cfg(unix)]
/// use std::os::unix::ffi::OsStrExt;
/// use std::path::Path;
///
/// let unicode_path = Path::new("/valid/unicode");
/// Utf8Path::from_path(unicode_path).expect("valid Unicode path succeeded");
///
/// // Paths on Unix can be non-UTF-8.
/// # #[cfg(unix)]
/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
/// # #[cfg(unix)]
/// let non_unicode_path = Path::new(non_unicode_str);
/// # #[cfg(unix)]
/// assert!(Utf8Path::from_path(non_unicode_path).is_none(), "non-Unicode path failed");
/// ```
pub fn from_path(path: &Path) -> Option<&Utf8Path> {
path.as_os_str().to_str().map(Utf8Path::new)
}
/// Converts a `Utf8Path` to a [`Path`].
///
/// This is equivalent to the `AsRef<&Path> for &Utf8Path` impl, but may aid in type inference.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
/// use std::path::Path;
///
/// let utf8_path = Utf8Path::new("foo.txt");
/// let std_path: &Path = utf8_path.as_std_path();
/// assert_eq!(std_path.to_str(), Some("foo.txt"));
///
/// // Convert back to a Utf8Path.
/// let new_utf8_path = Utf8Path::from_path(std_path).unwrap();
/// assert_eq!(new_utf8_path, "foo.txt");
/// ```
pub fn as_std_path(&self) -> &Path {
self.as_ref()
}
/// Yields the underlying [`str`] slice.
///
/// Unlike [`Path::to_str`], this always returns a slice because the contents of a `Utf8Path`
/// are guaranteed to be valid UTF-8.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let s = Utf8Path::new("foo.txt").as_str();
/// assert_eq!(s, "foo.txt");
/// ```
///
/// [`str`]: str
#[must_use]
pub fn as_str(&self) -> &str {
// SAFETY: every Utf8Path constructor ensures that self is valid UTF-8
unsafe { assume_utf8(self.as_os_str()) }
}
/// Yields the underlying [`OsStr`] slice.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let os_str = Utf8Path::new("foo.txt").as_os_str();
/// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
/// ```
#[must_use]
pub fn as_os_str(&self) -> &OsStr {
self.0.as_os_str()
}
/// Converts a `Utf8Path` to an owned [`Utf8PathBuf`].
///
/// # Examples
///
/// ```
/// use camino::{Utf8Path, Utf8PathBuf};
///
/// let path_buf = Utf8Path::new("foo.txt").to_path_buf();
/// assert_eq!(path_buf, Utf8PathBuf::from("foo.txt"));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
pub fn to_path_buf(&self) -> Utf8PathBuf {
Utf8PathBuf(self.0.to_path_buf())
}
/// Returns `true` if the `Utf8Path` is absolute, i.e., if it is independent of
/// the current directory.
///
/// * On Unix, a path is absolute if it starts with the root, so
/// `is_absolute` and [`has_root`] are equivalent.
///
/// * On Windows, a path is absolute if it has a prefix and starts with the
/// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// assert!(!Utf8Path::new("foo.txt").is_absolute());
/// ```
///
/// [`has_root`]: Utf8Path::has_root
#[must_use]
pub fn is_absolute(&self) -> bool {
self.0.is_absolute()
}
/// Returns `true` if the `Utf8Path` is relative, i.e., not absolute.
///
/// See [`is_absolute`]'s documentation for more details.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// assert!(Utf8Path::new("foo.txt").is_relative());
/// ```
///
/// [`is_absolute`]: Utf8Path::is_absolute
#[must_use]
pub fn is_relative(&self) -> bool {
self.0.is_relative()
}
/// Returns `true` if the `Utf8Path` has a root.
///
/// * On Unix, a path has a root if it begins with `/`.
///
/// * On Windows, a path has a root if it:
/// * has no prefix and begins with a separator, e.g., `\windows`
/// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
/// * has any non-disk prefix, e.g., `\\server\share`
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// assert!(Utf8Path::new("/etc/passwd").has_root());
/// ```
#[must_use]
pub fn has_root(&self) -> bool {
self.0.has_root()
}
/// Returns the `Path` without its final component, if there is one.
///
/// Returns [`None`] if the path terminates in a root or prefix.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/foo/bar");
/// let parent = path.parent().unwrap();
/// assert_eq!(parent, Utf8Path::new("/foo"));
///
/// let grand_parent = parent.parent().unwrap();
/// assert_eq!(grand_parent, Utf8Path::new("/"));
/// assert_eq!(grand_parent.parent(), None);
/// ```
#[must_use]
pub fn parent(&self) -> Option<&Utf8Path> {
self.0.parent().map(|path| {
// SAFETY: self is valid UTF-8, so parent is valid UTF-8 as well
unsafe { Utf8Path::assume_utf8(path) }
})
}
/// Produces an iterator over `Utf8Path` and its ancestors.
///
/// The iterator will yield the `Utf8Path` that is returned if the [`parent`] method is used zero
/// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
/// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
/// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
/// namely `&self`.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let mut ancestors = Utf8Path::new("/foo/bar").ancestors();
/// assert_eq!(ancestors.next(), Some(Utf8Path::new("/foo/bar")));
/// assert_eq!(ancestors.next(), Some(Utf8Path::new("/foo")));
/// assert_eq!(ancestors.next(), Some(Utf8Path::new("/")));
/// assert_eq!(ancestors.next(), None);
///
/// let mut ancestors = Utf8Path::new("../foo/bar").ancestors();
/// assert_eq!(ancestors.next(), Some(Utf8Path::new("../foo/bar")));
/// assert_eq!(ancestors.next(), Some(Utf8Path::new("../foo")));
/// assert_eq!(ancestors.next(), Some(Utf8Path::new("..")));
/// assert_eq!(ancestors.next(), Some(Utf8Path::new("")));
/// assert_eq!(ancestors.next(), None);
/// ```
///
/// [`parent`]: Utf8Path::parent
pub fn ancestors(&self) -> Utf8Ancestors<'_> {
Utf8Ancestors(self.0.ancestors())
}
/// Returns the final component of the `Utf8Path`, if there is one.
///
/// If the path is a normal file, this is the file name. If it's the path of a directory, this
/// is the directory name.
///
/// Returns [`None`] if the path terminates in `..`.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// assert_eq!(Some("bin"), Utf8Path::new("/usr/bin/").file_name());
/// assert_eq!(Some("foo.txt"), Utf8Path::new("tmp/foo.txt").file_name());
/// assert_eq!(Some("foo.txt"), Utf8Path::new("foo.txt/.").file_name());
/// assert_eq!(Some("foo.txt"), Utf8Path::new("foo.txt/.//").file_name());
/// assert_eq!(None, Utf8Path::new("foo.txt/..").file_name());
/// assert_eq!(None, Utf8Path::new("/").file_name());
/// ```
#[must_use]
pub fn file_name(&self) -> Option<&str> {
self.0.file_name().map(|s| {
// SAFETY: self is valid UTF-8, so file_name is valid UTF-8 as well
unsafe { assume_utf8(s) }
})
}
/// Returns a path that, when joined onto `base`, yields `self`.
///
/// # Errors
///
/// If `base` is not a prefix of `self` (i.e., [`starts_with`]
/// returns `false`), returns [`Err`].
///
/// [`starts_with`]: Utf8Path::starts_with
///
/// # Examples
///
/// ```
/// use camino::{Utf8Path, Utf8PathBuf};
///
/// let path = Utf8Path::new("/test/haha/foo.txt");
///
/// assert_eq!(path.strip_prefix("/"), Ok(Utf8Path::new("test/haha/foo.txt")));
/// assert_eq!(path.strip_prefix("/test"), Ok(Utf8Path::new("haha/foo.txt")));
/// assert_eq!(path.strip_prefix("/test/"), Ok(Utf8Path::new("haha/foo.txt")));
/// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Utf8Path::new("")));
/// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Utf8Path::new("")));
///
/// assert!(path.strip_prefix("test").is_err());
/// assert!(path.strip_prefix("/haha").is_err());
///
/// let prefix = Utf8PathBuf::from("/test/");
/// assert_eq!(path.strip_prefix(prefix), Ok(Utf8Path::new("haha/foo.txt")));
/// ```
pub fn strip_prefix(&self, base: impl AsRef<Path>) -> Result<&Utf8Path, StripPrefixError> {
self.0.strip_prefix(base).map(|path| {
// SAFETY: self is valid UTF-8, and strip_prefix returns a part of self (or an empty
// string), so it is valid UTF-8 as well.
unsafe { Utf8Path::assume_utf8(path) }
})
}
/// Determines whether `base` is a prefix of `self`.
///
/// Only considers whole path components to match.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/etc/passwd");
///
/// assert!(path.starts_with("/etc"));
/// assert!(path.starts_with("/etc/"));
/// assert!(path.starts_with("/etc/passwd"));
/// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
/// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
///
/// assert!(!path.starts_with("/e"));
/// assert!(!path.starts_with("/etc/passwd.txt"));
///
/// assert!(!Utf8Path::new("/etc/foo.rs").starts_with("/etc/foo"));
/// ```
#[must_use]
pub fn starts_with(&self, base: impl AsRef<Path>) -> bool {
self.0.starts_with(base)
}
/// Determines whether `child` is a suffix of `self`.
///
/// Only considers whole path components to match.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/etc/resolv.conf");
///
/// assert!(path.ends_with("resolv.conf"));
/// assert!(path.ends_with("etc/resolv.conf"));
/// assert!(path.ends_with("/etc/resolv.conf"));
///
/// assert!(!path.ends_with("/resolv.conf"));
/// assert!(!path.ends_with("conf")); // use .extension() instead
/// ```
#[must_use]
pub fn ends_with(&self, base: impl AsRef<Path>) -> bool {
self.0.ends_with(base)
}
/// Extracts the stem (non-extension) portion of [`self.file_name`].
///
/// [`self.file_name`]: Utf8Path::file_name
///
/// The stem is:
///
/// * [`None`], if there is no file name;
/// * The entire file name if there is no embedded `.`;
/// * The entire file name if the file name begins with `.` and has no other `.`s within;
/// * Otherwise, the portion of the file name before the final `.`
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// assert_eq!("foo", Utf8Path::new("foo.rs").file_stem().unwrap());
/// assert_eq!("foo.tar", Utf8Path::new("foo.tar.gz").file_stem().unwrap());
/// ```
#[must_use]
pub fn file_stem(&self) -> Option<&str> {
self.0.file_stem().map(|s| {
// SAFETY: self is valid UTF-8, so file_stem is valid UTF-8 as well
unsafe { assume_utf8(s) }
})
}
/// Extracts the extension of [`self.file_name`], if possible.
///
/// The extension is:
///
/// * [`None`], if there is no file name;
/// * [`None`], if there is no embedded `.`;
/// * [`None`], if the file name begins with `.` and has no other `.`s within;
/// * Otherwise, the portion of the file name after the final `.`
///
/// [`self.file_name`]: Utf8Path::file_name
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// assert_eq!("rs", Utf8Path::new("foo.rs").extension().unwrap());
/// assert_eq!("gz", Utf8Path::new("foo.tar.gz").extension().unwrap());
/// ```
#[must_use]
pub fn extension(&self) -> Option<&str> {
self.0.extension().map(|s| {
// SAFETY: self is valid UTF-8, so extension is valid UTF-8 as well
unsafe { assume_utf8(s) }
})
}
/// Creates an owned [`Utf8PathBuf`] with `path` adjoined to `self`.
///
/// See [`Utf8PathBuf::push`] for more details on what it means to adjoin a path.
///
/// # Examples
///
/// ```
/// use camino::{Utf8Path, Utf8PathBuf};
///
/// assert_eq!(Utf8Path::new("/etc").join("passwd"), Utf8PathBuf::from("/etc/passwd"));
/// ```
#[must_use]
pub fn join(&self, path: impl AsRef<Utf8Path>) -> Utf8PathBuf {
Utf8PathBuf(self.0.join(&path.as_ref().0))
}
/// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
///
/// See [`PathBuf::push`] for more details on what it means to adjoin a path.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
/// use std::path::PathBuf;
///
/// assert_eq!(Utf8Path::new("/etc").join_os("passwd"), PathBuf::from("/etc/passwd"));
/// ```
#[must_use]
pub fn join_os(&self, path: impl AsRef<Path>) -> PathBuf {
self.0.join(path)
}
/// Creates an owned [`Utf8PathBuf`] like `self` but with the given file name.
///
/// See [`Utf8PathBuf::set_file_name`] for more details.
///
/// # Examples
///
/// ```
/// use camino::{Utf8Path, Utf8PathBuf};
///
/// let path = Utf8Path::new("/tmp/foo.txt");
/// assert_eq!(path.with_file_name("bar.txt"), Utf8PathBuf::from("/tmp/bar.txt"));
///
/// let path = Utf8Path::new("/tmp");
/// assert_eq!(path.with_file_name("var"), Utf8PathBuf::from("/var"));
/// ```
#[must_use]
pub fn with_file_name(&self, file_name: impl AsRef<str>) -> Utf8PathBuf {
Utf8PathBuf(self.0.with_file_name(file_name.as_ref()))
}
/// Creates an owned [`Utf8PathBuf`] like `self` but with the given extension.
///
/// See [`Utf8PathBuf::set_extension`] for more details.
///
/// # Examples
///
/// ```
/// use camino::{Utf8Path, Utf8PathBuf};
///
/// let path = Utf8Path::new("foo.rs");
/// assert_eq!(path.with_extension("txt"), Utf8PathBuf::from("foo.txt"));
///
/// let path = Utf8Path::new("foo.tar.gz");
/// assert_eq!(path.with_extension(""), Utf8PathBuf::from("foo.tar"));
/// assert_eq!(path.with_extension("xz"), Utf8PathBuf::from("foo.tar.xz"));
/// assert_eq!(path.with_extension("").with_extension("txt"), Utf8PathBuf::from("foo.txt"));
/// ```
pub fn with_extension(&self, extension: impl AsRef<str>) -> Utf8PathBuf {
Utf8PathBuf(self.0.with_extension(extension.as_ref()))
}
/// Produces an iterator over the [`Utf8Component`]s of the path.
///
/// When parsing the path, there is a small amount of normalization:
///
/// * Repeated separators are ignored, so `a/b` and `a//b` both have
/// `a` and `b` as components.
///
/// * Occurrences of `.` are normalized away, except if they are at the
/// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
/// `a/b` all have `a` and `b` as components, but `./a/b` starts with
/// an additional [`CurDir`] component.
///
/// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
///
/// Note that no other normalization takes place; in particular, `a/c`
/// and `a/b/../c` are distinct, to account for the possibility that `b`
/// is a symbolic link (so its parent isn't `a`).
///
/// # Examples
///
/// ```
/// use camino::{Utf8Component, Utf8Path};
///
/// let mut components = Utf8Path::new("/tmp/foo.txt").components();
///
/// assert_eq!(components.next(), Some(Utf8Component::RootDir));
/// assert_eq!(components.next(), Some(Utf8Component::Normal("tmp")));
/// assert_eq!(components.next(), Some(Utf8Component::Normal("foo.txt")));
/// assert_eq!(components.next(), None)
/// ```
///
/// [`CurDir`]: Utf8Component::CurDir
pub fn components(&self) -> Utf8Components {
Utf8Components(self.0.components())
}
/// Produces an iterator over the path's components viewed as [`str`]
/// slices.
///
/// For more information about the particulars of how the path is separated
/// into components, see [`components`].
///
/// [`components`]: Utf8Path::components
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let mut it = Utf8Path::new("/tmp/foo.txt").iter();
/// assert_eq!(it.next(), Some(std::path::MAIN_SEPARATOR.to_string().as_str()));
/// assert_eq!(it.next(), Some("tmp"));
/// assert_eq!(it.next(), Some("foo.txt"));
/// assert_eq!(it.next(), None)
/// ```
pub fn iter(&self) -> Iter<'_> {
Iter {
inner: self.components(),
}
}
/// Queries the file system to get information about a file, directory, etc.
///
/// This function will traverse symbolic links to query information about the
/// destination file.
///
/// This is an alias to [`fs::metadata`].
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/Minas/tirith");
/// let metadata = path.metadata().expect("metadata call failed");
/// println!("{:?}", metadata.file_type());
/// ```
pub fn metadata(&self) -> io::Result<fs::Metadata> {
self.0.metadata()
}
/// Queries the metadata about a file without following symlinks.
///
/// This is an alias to [`fs::symlink_metadata`].
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/Minas/tirith");
/// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
/// println!("{:?}", metadata.file_type());
/// ```
pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
self.0.symlink_metadata()
}
/// Returns the canonical, absolute form of the path with all intermediate
/// components normalized and symbolic links resolved.
///
/// This returns a [`PathBuf`] because even if a symlink is valid Unicode, its target may not
/// be. For a version that returns a [`Utf8PathBuf`], see
/// [`canonicalize_utf8`](Self::canonicalize_utf8).
///
/// This is an alias to [`fs::canonicalize`].
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
/// use std::path::PathBuf;
///
/// let path = Utf8Path::new("/foo/test/../test/bar.rs");
/// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
/// ```
pub fn canonicalize(&self) -> io::Result<PathBuf> {
self.0.canonicalize()
}
/// Returns the canonical, absolute form of the path with all intermediate
/// components normalized and symbolic links resolved.
///
/// This method attempts to convert the resulting [`PathBuf`] into a [`Utf8PathBuf`]. For a
/// version that does not attempt to do this conversion, see
/// [`canonicalize`](Self::canonicalize).
///
/// # Errors
///
/// The I/O operation may return an error: see the [`fs::canonicalize`]
/// documentation for more.
///
/// If the resulting path is not UTF-8, an [`io::Error`] is returned with the
/// [`ErrorKind`](io::ErrorKind) set to `InvalidData` and the payload set to a
/// [`FromPathBufError`].
///
/// # Examples
///
/// ```no_run
/// use camino::{Utf8Path, Utf8PathBuf};
///
/// let path = Utf8Path::new("/foo/test/../test/bar.rs");
/// assert_eq!(path.canonicalize_utf8().unwrap(), Utf8PathBuf::from("/foo/test/bar.rs"));
/// ```
pub fn canonicalize_utf8(&self) -> io::Result<Utf8PathBuf> {
self.canonicalize().and_then(|path| {
path.try_into()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
})
}
/// Reads a symbolic link, returning the file that the link points to.
///
/// This returns a [`PathBuf`] because even if a symlink is valid Unicode, its target may not
/// be. For a version that returns a [`Utf8PathBuf`], see
/// [`read_link_utf8`](Self::read_link_utf8).
///
/// This is an alias to [`fs::read_link`].
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/laputa/sky_castle.rs");
/// let path_link = path.read_link().expect("read_link call failed");
/// ```
pub fn read_link(&self) -> io::Result<PathBuf> {
self.0.read_link()
}
/// Reads a symbolic link, returning the file that the link points to.
///
/// This method attempts to convert the resulting [`PathBuf`] into a [`Utf8PathBuf`]. For a
/// version that does not attempt to do this conversion, see [`read_link`](Self::read_link).
///
/// # Errors
///
/// The I/O operation may return an error: see the [`fs::read_link`]
/// documentation for more.
///
/// If the resulting path is not UTF-8, an [`io::Error`] is returned with the
/// [`ErrorKind`](io::ErrorKind) set to `InvalidData` and the payload set to a
/// [`FromPathBufError`].
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/laputa/sky_castle.rs");
/// let path_link = path.read_link_utf8().expect("read_link call failed");
/// ```
pub fn read_link_utf8(&self) -> io::Result<Utf8PathBuf> {
self.read_link().and_then(|path| {
path.try_into()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
})
}
/// Returns an iterator over the entries within a directory.
///
/// The iterator will yield instances of [`io::Result`]`<`[`fs::DirEntry`]`>`. New
/// errors may be encountered after an iterator is initially constructed.
///
/// This is an alias to [`fs::read_dir`].
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/laputa");
/// for entry in path.read_dir().expect("read_dir call failed") {
/// if let Ok(entry) = entry {
/// println!("{:?}", entry.path());
/// }
/// }
/// ```
pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
self.0.read_dir()
}
/// Returns an iterator over the entries within a directory.
///
/// The iterator will yield instances of [`io::Result`]`<`[`Utf8DirEntry`]`>`. New
/// errors may be encountered after an iterator is initially constructed.
///
/// # Errors
///
/// The I/O operation may return an error: see the [`fs::read_dir`]
/// documentation for more.
///
/// If a directory entry is not UTF-8, an [`io::Error`] is returned with the
/// [`ErrorKind`](io::ErrorKind) set to `InvalidData` and the payload set to a
/// [`FromPathBufError`].
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/laputa");
/// for entry in path.read_dir_utf8().expect("read_dir call failed") {
/// if let Ok(entry) = entry {
/// println!("{}", entry.path());
/// }
/// }
/// ```
#[inline]
pub fn read_dir_utf8(&self) -> io::Result<ReadDirUtf8> {
self.0.read_dir().map(|inner| ReadDirUtf8 { inner })
}
/// Returns `true` if the path points at an existing entity.
///
/// Warning: this method may be error-prone, consider using [`try_exists()`] instead!
/// It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs.
///
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
/// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
/// assert!(!Utf8Path::new("does_not_exist.txt").exists());
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::metadata`].
///
/// [`try_exists()`]: Self::try_exists
#[must_use]
pub fn exists(&self) -> bool {
self.0.exists()
}
/// Returns `Ok(true)` if the path points at an existing entity.
///
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `Ok(false)`.
///
/// As opposed to the [`exists()`] method, this one doesn't silently ignore errors
/// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
/// denied on some of the parent directories.)
///
/// Note that while this avoids some pitfalls of the `exists()` method, it still can not
/// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios
/// where those bugs are not an issue.
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
/// assert!(!Utf8Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
/// assert!(Utf8Path::new("/root/secret_file.txt").try_exists().is_err());
/// ```
///
/// [`exists()`]: Self::exists
#[inline]
pub fn try_exists(&self) -> io::Result<bool> {
// Note: this block is written this way rather than with a pattern guard to appease Rust
// 1.34.
match fs::metadata(self) {
Ok(_) => Ok(true),
Err(error) => {
if error.kind() == io::ErrorKind::NotFound {
Ok(false)
} else {
Err(error)
}
}
}
}
/// Returns `true` if the path exists on disk and is pointing at a regular file.
///
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
/// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
/// assert_eq!(Utf8Path::new("./is_a_directory/").is_file(), false);
/// assert_eq!(Utf8Path::new("a_file.txt").is_file(), true);
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
/// [`fs::Metadata::is_file`] if it was [`Ok`].
///
/// When the goal is simply to read from (or write to) the source, the most
/// reliable way to test the source can be read (or written to) is to open
/// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
/// a Unix-like system for example. See [`fs::File::open`] or
/// [`fs::OpenOptions::open`] for more information.
#[must_use]
pub fn is_file(&self) -> bool {
self.0.is_file()
}
/// Returns `true` if the path exists on disk and is pointing at a directory.
///
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
/// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
/// assert_eq!(Utf8Path::new("./is_a_directory/").is_dir(), true);
/// assert_eq!(Utf8Path::new("a_file.txt").is_dir(), false);
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
/// [`fs::Metadata::is_dir`] if it was [`Ok`].
#[must_use]
pub fn is_dir(&self) -> bool {
self.0.is_dir()
}
/// Returns `true` if the path exists on disk and is pointing at a symbolic link.
///
/// This function will not traverse symbolic links.
/// In case of a broken symbolic link this will also return true.
///
/// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return false.
///
/// # Examples
///
#[cfg_attr(unix, doc = "```no_run")]
#[cfg_attr(not(unix), doc = "```ignore")]
/// use camino::Utf8Path;
/// use std::os::unix::fs::symlink;
///
/// let link_path = Utf8Path::new("link");
/// symlink("/origin_does_not_exist/", link_path).unwrap();
/// assert_eq!(link_path.is_symlink(), true);
/// assert_eq!(link_path.exists(), false);
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`Utf8Path::symlink_metadata`] and handle its [`Result`]. Then call
/// [`fs::Metadata::is_symlink`] if it was [`Ok`].
#[must_use]
pub fn is_symlink(&self) -> bool {
self.symlink_metadata()
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
}
/// Converts a `Box<Utf8Path>` into a [`Utf8PathBuf`] without copying or allocating.
#[must_use = "`self` will be dropped if the result is not used"]
pub fn into_path_buf(self: Box<Utf8Path>) -> Utf8PathBuf {
let ptr = Box::into_raw(self) as *mut Path;
// SAFETY:
// * self is valid UTF-8
// * ptr was constructed by consuming self so it represents an owned path.
// * Utf8Path is marked as #[repr(transparent)] so the conversion from a *mut Utf8Path to a
// *mut Path is valid.
let boxed_path = unsafe { Box::from_raw(ptr) };
Utf8PathBuf(boxed_path.into_path_buf())
}
// invariant: Path must be guaranteed to be utf-8 data
unsafe fn assume_utf8(path: &Path) -> &Utf8Path {
// SAFETY: Utf8Path is marked as #[repr(transparent)] so the conversion from a
// *const Path to a *const Utf8Path is valid.
&*(path as *const Path as *const Utf8Path)
}
}
impl Clone for Box<Utf8Path> {
fn clone(&self) -> Self {
let boxed: Box<Path> = self.0.into();
let ptr = Box::into_raw(boxed) as *mut Utf8Path;
// SAFETY:
// * self is valid UTF-8
// * ptr was created by consuming a Box<Path> so it represents an rced pointer
// * Utf8Path is marked as #[repr(transparent)] so the conversion from *mut Path to
// *mut Utf8Path is valid
unsafe { Box::from_raw(ptr) }
}
}
impl fmt::Display for Utf8Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.as_str(), f)
}
}
impl fmt::Debug for Utf8Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), f)
}
}
/// An iterator over [`Utf8Path`] and its ancestors.
///
/// This `struct` is created by the [`ancestors`] method on [`Utf8Path`].
/// See its documentation for more.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/foo/bar");
///
/// for ancestor in path.ancestors() {
/// println!("{}", ancestor);
/// }
/// ```
///
/// [`ancestors`]: Utf8Path::ancestors
#[derive(Copy, Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[repr(transparent)]
pub struct Utf8Ancestors<'a>(Ancestors<'a>);
impl<'a> fmt::Debug for Utf8Ancestors<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl<'a> Iterator for Utf8Ancestors<'a> {
type Item = &'a Utf8Path;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|path| {
// SAFETY: Utf8Ancestors was constructed from a Utf8Path, so it is guaranteed to
// be valid UTF-8
unsafe { Utf8Path::assume_utf8(path) }
})
}
}
impl<'a> FusedIterator for Utf8Ancestors<'a> {}
/// An iterator over the [`Utf8Component`]s of a [`Utf8Path`].
///
/// This `struct` is created by the [`components`] method on [`Utf8Path`].
/// See its documentation for more.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("/tmp/foo/bar.txt");
///
/// for component in path.components() {
/// println!("{:?}", component);
/// }
/// ```
///
/// [`components`]: Utf8Path::components
#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Utf8Components<'a>(Components<'a>);
impl<'a> Utf8Components<'a> {
/// Extracts a slice corresponding to the portion of the path remaining for iteration.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let mut components = Utf8Path::new("/tmp/foo/bar.txt").components();
/// components.next();
/// components.next();
///
/// assert_eq!(Utf8Path::new("foo/bar.txt"), components.as_path());
/// ```
#[must_use]
pub fn as_path(&self) -> &'a Utf8Path {
// SAFETY: Utf8Components was constructed from a Utf8Path, so it is guaranteed to be valid
// UTF-8
unsafe { Utf8Path::assume_utf8(self.0.as_path()) }
}
}
impl<'a> Iterator for Utf8Components<'a> {
type Item = Utf8Component<'a>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|component| {
// SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be
// valid UTF-8
unsafe { Utf8Component::new(component) }
})
}
}
impl<'a> FusedIterator for Utf8Components<'a> {}
impl<'a> DoubleEndedIterator for Utf8Components<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back().map(|component| {
// SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be
// valid UTF-8
unsafe { Utf8Component::new(component) }
})
}
}
impl<'a> fmt::Debug for Utf8Components<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl AsRef<Utf8Path> for Utf8Components<'_> {
fn as_ref(&self) -> &Utf8Path {
self.as_path()
}
}
impl AsRef<Path> for Utf8Components<'_> {
fn as_ref(&self) -> &Path {
self.as_path().as_ref()
}
}
impl AsRef<str> for Utf8Components<'_> {
fn as_ref(&self) -> &str {
self.as_path().as_ref()
}
}
impl AsRef<OsStr> for Utf8Components<'_> {
fn as_ref(&self) -> &OsStr {
self.as_path().as_os_str()
}
}
/// An iterator over the [`Utf8Component`]s of a [`Utf8Path`], as [`str`] slices.
///
/// This `struct` is created by the [`iter`] method on [`Utf8Path`].
/// See its documentation for more.
///
/// [`iter`]: Utf8Path::iter
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Iter<'a> {
inner: Utf8Components<'a>,
}
impl fmt::Debug for Iter<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct DebugHelper<'a>(&'a Utf8Path);
impl fmt::Debug for DebugHelper<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.0.iter()).finish()
}
}
f.debug_tuple("Iter")
.field(&DebugHelper(self.as_path()))
.finish()
}
}
impl<'a> Iter<'a> {
/// Extracts a slice corresponding to the portion of the path remaining for iteration.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let mut iter = Utf8Path::new("/tmp/foo/bar.txt").iter();
/// iter.next();
/// iter.next();
///
/// assert_eq!(Utf8Path::new("foo/bar.txt"), iter.as_path());
/// ```
#[must_use]
pub fn as_path(&self) -> &'a Utf8Path {
self.inner.as_path()
}
}
impl AsRef<Utf8Path> for Iter<'_> {
fn as_ref(&self) -> &Utf8Path {
self.as_path()
}
}
impl AsRef<Path> for Iter<'_> {
fn as_ref(&self) -> &Path {
self.as_path().as_ref()
}
}
impl AsRef<str> for Iter<'_> {
fn as_ref(&self) -> &str {
self.as_path().as_ref()
}
}
impl AsRef<OsStr> for Iter<'_> {
fn as_ref(&self) -> &OsStr {
self.as_path().as_os_str()
}
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
self.inner.next().map(|component| component.as_str())
}
}
impl<'a> DoubleEndedIterator for Iter<'a> {
fn next_back(&mut self) -> Option<&'a str> {
self.inner.next_back().map(|component| component.as_str())
}
}
impl FusedIterator for Iter<'_> {}
/// A single component of a path.
///
/// A `Utf8Component` roughly corresponds to a substring between path separators
/// (`/` or `\`).
///
/// This `enum` is created by iterating over [`Utf8Components`], which in turn is
/// created by the [`components`](Utf8Path::components) method on [`Utf8Path`].
///
/// # Examples
///
/// ```rust
/// use camino::{Utf8Component, Utf8Path};
///
/// let path = Utf8Path::new("/tmp/foo/bar.txt");
/// let components = path.components().collect::<Vec<_>>();
/// assert_eq!(&components, &[
/// Utf8Component::RootDir,
/// Utf8Component::Normal("tmp"),
/// Utf8Component::Normal("foo"),
/// Utf8Component::Normal("bar.txt"),
/// ]);
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum Utf8Component<'a> {
/// A Windows path prefix, e.g., `C:` or `\\server\share`.
///
/// There is a large variety of prefix types, see [`Utf8Prefix`]'s documentation
/// for more.
///
/// Does not occur on Unix.
Prefix(Utf8PrefixComponent<'a>),
/// The root directory component, appears after any prefix and before anything else.
///
/// It represents a separator that designates that a path starts from root.
RootDir,
/// A reference to the current directory, i.e., `.`.
CurDir,
/// A reference to the parent directory, i.e., `..`.
ParentDir,
/// A normal component, e.g., `a` and `b` in `a/b`.
///
/// This variant is the most common one, it represents references to files
/// or directories.
Normal(&'a str),
}
impl<'a> Utf8Component<'a> {
unsafe fn new(component: Component<'a>) -> Utf8Component<'a> {
match component {
Component::Prefix(prefix) => Utf8Component::Prefix(Utf8PrefixComponent(prefix)),
Component::RootDir => Utf8Component::RootDir,
Component::CurDir => Utf8Component::CurDir,
Component::ParentDir => Utf8Component::ParentDir,
Component::Normal(s) => Utf8Component::Normal(assume_utf8(s)),
}
}
/// Extracts the underlying [`str`] slice.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("./tmp/foo/bar.txt");
/// let components: Vec<_> = path.components().map(|comp| comp.as_str()).collect();
/// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
/// ```
#[must_use]
pub fn as_str(&self) -> &'a str {
// SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be
// valid UTF-8
unsafe { assume_utf8(self.as_os_str()) }
}
/// Extracts the underlying [`OsStr`] slice.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// let path = Utf8Path::new("./tmp/foo/bar.txt");
/// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
/// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
/// ```
#[must_use]
pub fn as_os_str(&self) -> &'a OsStr {
match *self {
Utf8Component::Prefix(prefix) => prefix.as_os_str(),
Utf8Component::RootDir => Component::RootDir.as_os_str(),
Utf8Component::CurDir => Component::CurDir.as_os_str(),
Utf8Component::ParentDir => Component::ParentDir.as_os_str(),
Utf8Component::Normal(s) => OsStr::new(s),
}
}
}
impl<'a> fmt::Debug for Utf8Component<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.as_os_str(), f)
}
}
impl<'a> fmt::Display for Utf8Component<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.as_str(), f)
}
}
impl AsRef<Utf8Path> for Utf8Component<'_> {
fn as_ref(&self) -> &Utf8Path {
self.as_str().as_ref()
}
}
impl AsRef<Path> for Utf8Component<'_> {
fn as_ref(&self) -> &Path {
self.as_os_str().as_ref()
}
}
impl AsRef<str> for Utf8Component<'_> {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<OsStr> for Utf8Component<'_> {
fn as_ref(&self) -> &OsStr {
self.as_os_str()
}
}
/// Windows path prefixes, e.g., `C:` or `\\server\share`.
///
/// Windows uses a variety of path prefix styles, including references to drive
/// volumes (like `C:`), network shared folders (like `\\server\share`), and
/// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
/// `\\?\`), in which case `/` is *not* treated as a separator and essentially
/// no normalization is performed.
///
/// # Examples
///
/// ```
/// use camino::{Utf8Component, Utf8Path, Utf8Prefix};
/// use camino::Utf8Prefix::*;
///
/// fn get_path_prefix(s: &str) -> Utf8Prefix {
/// let path = Utf8Path::new(s);
/// match path.components().next().unwrap() {
/// Utf8Component::Prefix(prefix_component) => prefix_component.kind(),
/// _ => panic!(),
/// }
/// }
///
/// # if cfg!(windows) {
/// assert_eq!(Verbatim("pictures"), get_path_prefix(r"\\?\pictures\kittens"));
/// assert_eq!(VerbatimUNC("server", "share"), get_path_prefix(r"\\?\UNC\server\share"));
/// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
/// assert_eq!(DeviceNS("BrainInterface"), get_path_prefix(r"\\.\BrainInterface"));
/// assert_eq!(UNC("server", "share"), get_path_prefix(r"\\server\share"));
/// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
/// # }
/// ```
#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub enum Utf8Prefix<'a> {
/// Verbatim prefix, e.g., `\\?\cat_pics`.
///
/// Verbatim prefixes consist of `\\?\` immediately followed by the given
/// component.
Verbatim(&'a str),
/// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
/// e.g., `\\?\UNC\server\share`.
///
/// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
/// server's hostname and a share name.
VerbatimUNC(&'a str, &'a str),
/// Verbatim disk prefix, e.g., `\\?\C:`.
///
/// Verbatim disk prefixes consist of `\\?\` immediately followed by the
/// drive letter and `:`.
VerbatimDisk(u8),
/// Device namespace prefix, e.g., `\\.\COM42`.
///
/// Device namespace prefixes consist of `\\.\` immediately followed by the
/// device name.
DeviceNS(&'a str),
/// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
/// `\\server\share`.
///
/// UNC prefixes consist of the server's hostname and a share name.
UNC(&'a str, &'a str),
/// Prefix `C:` for the given disk drive.
Disk(u8),
}
impl<'a> Utf8Prefix<'a> {
/// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
///
/// # Examples
///
/// ```
/// use camino::Utf8Prefix::*;
///
/// assert!(Verbatim("pictures").is_verbatim());
/// assert!(VerbatimUNC("server", "share").is_verbatim());
/// assert!(VerbatimDisk(b'C').is_verbatim());
/// assert!(!DeviceNS("BrainInterface").is_verbatim());
/// assert!(!UNC("server", "share").is_verbatim());
/// assert!(!Disk(b'C').is_verbatim());
/// ```
#[must_use]
pub fn is_verbatim(&self) -> bool {
use Utf8Prefix::*;
match self {
Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
_ => false,
}
}
}
/// A structure wrapping a Windows path prefix as well as its unparsed string
/// representation.
///
/// In addition to the parsed [`Utf8Prefix`] information returned by [`kind`],
/// `Utf8PrefixComponent` also holds the raw and unparsed [`str`] slice,
/// returned by [`as_str`].
///
/// Instances of this `struct` can be obtained by matching against the
/// [`Prefix` variant] on [`Utf8Component`].
///
/// Does not occur on Unix.
///
/// # Examples
///
/// ```
/// # if cfg!(windows) {
/// use camino::{Utf8Component, Utf8Path, Utf8Prefix};
/// use std::ffi::OsStr;
///
/// let path = Utf8Path::new(r"c:\you\later\");
/// match path.components().next().unwrap() {
/// Utf8Component::Prefix(prefix_component) => {
/// assert_eq!(Utf8Prefix::Disk(b'C'), prefix_component.kind());
/// assert_eq!("c:", prefix_component.as_str());
/// }
/// _ => unreachable!(),
/// }
/// # }
/// ```
///
/// [`as_str`]: Utf8PrefixComponent::as_str
/// [`kind`]: Utf8PrefixComponent::kind
/// [`Prefix` variant]: Utf8Component::Prefix
#[repr(transparent)]
#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Utf8PrefixComponent<'a>(PrefixComponent<'a>);
impl<'a> Utf8PrefixComponent<'a> {
/// Returns the parsed prefix data.
///
/// See [`Utf8Prefix`]'s documentation for more information on the different
/// kinds of prefixes.
#[must_use]
pub fn kind(&self) -> Utf8Prefix<'a> {
// SAFETY for all the below unsafe blocks: the path self was originally constructed from was
// UTF-8 so any parts of it are valid UTF-8
match self.0.kind() {
Prefix::Verbatim(prefix) => Utf8Prefix::Verbatim(unsafe { assume_utf8(prefix) }),
Prefix::VerbatimUNC(server, share) => {
let server = unsafe { assume_utf8(server) };
let share = unsafe { assume_utf8(share) };
Utf8Prefix::VerbatimUNC(server, share)
}
Prefix::VerbatimDisk(drive) => Utf8Prefix::VerbatimDisk(drive),
Prefix::DeviceNS(prefix) => Utf8Prefix::DeviceNS(unsafe { assume_utf8(prefix) }),
Prefix::UNC(server, share) => {
let server = unsafe { assume_utf8(server) };
let share = unsafe { assume_utf8(share) };
Utf8Prefix::UNC(server, share)
}
Prefix::Disk(drive) => Utf8Prefix::Disk(drive),
}
}
/// Returns the [`str`] slice for this prefix.
#[must_use]
pub fn as_str(&self) -> &'a str {
// SAFETY: Utf8PrefixComponent was constructed from a Utf8Path, so it is guaranteed to be
// valid UTF-8
unsafe { assume_utf8(self.as_os_str()) }
}
/// Returns the raw [`OsStr`] slice for this prefix.
#[must_use]
pub fn as_os_str(&self) -> &'a OsStr {
self.0.as_os_str()
}
}
impl<'a> fmt::Debug for Utf8PrefixComponent<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl<'a> fmt::Display for Utf8PrefixComponent<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.as_str(), f)
}
}
// ---
// read_dir_utf8
// ---
/// Iterator over the entries in a directory.
///
/// This iterator is returned from [`Utf8Path::read_dir_utf8`] and will yield instances of
/// <code>[io::Result]<[Utf8DirEntry]></code>. Through a [`Utf8 DirEntry`] information like the entry's path
/// and possibly other metadata can be learned.
///
/// The order in which this iterator returns entries is platform and filesystem
/// dependent.
///
/// # Errors
///
/// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
/// IO error during iteration.
///
/// If a directory entry is not UTF-8, an [`io::Error`] is returned with the
/// [`ErrorKind`](io::ErrorKind) set to `InvalidData` and the payload set to a [`FromPathBufError`].
#[derive(Debug)]
pub struct ReadDirUtf8 {
inner: fs::ReadDir,
}
impl Iterator for ReadDirUtf8 {
type Item = io::Result<Utf8DirEntry>;
fn next(&mut self) -> Option<io::Result<Utf8DirEntry>> {
self.inner
.next()
.map(|entry| entry.and_then(Utf8DirEntry::new))
}
}
/// Entries returned by the [`ReadDirUtf8`] iterator.
///
/// An instance of `Utf8DirEntry` represents an entry inside of a directory on the filesystem. Each
/// entry can be inspected via methods to learn about the full path or possibly other metadata.
#[derive(Debug)]
pub struct Utf8DirEntry {
inner: fs::DirEntry,
path: Utf8PathBuf,
}
impl Utf8DirEntry {
fn new(inner: fs::DirEntry) -> io::Result<Self> {
let path = inner
.path()
.try_into()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
Ok(Self { inner, path })
}
/// Returns the full path to the file that this entry represents.
///
/// The full path is created by joining the original path to `read_dir`
/// with the filename of this entry.
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
///
/// fn main() -> std::io::Result<()> {
/// for entry in Utf8Path::new(".").read_dir_utf8()? {
/// let dir = entry?;
/// println!("{}", dir.path());
/// }
/// Ok(())
/// }
/// ```
///
/// This prints output like:
///
/// ```text
/// ./whatever.txt
/// ./foo.html
/// ./hello_world.rs
/// ```
///
/// The exact text, of course, depends on what files you have in `.`.
#[inline]
pub fn path(&self) -> &Utf8Path {
&self.path
}
/// Returns the metadata for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a symlink. To traverse
/// symlinks use [`Utf8Path::metadata`] or [`fs::File::metadata`].
///
/// # Platform-specific behavior
///
/// On Windows this function is cheap to call (no extra system calls
/// needed), but on Unix platforms this function is the equivalent of
/// calling `symlink_metadata` on the path.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
/// for entry in entries {
/// if let Ok(entry) = entry {
/// // Here, `entry` is a `Utf8DirEntry`.
/// if let Ok(metadata) = entry.metadata() {
/// // Now let's show our entry's permissions!
/// println!("{}: {:?}", entry.path(), metadata.permissions());
/// } else {
/// println!("Couldn't get metadata for {}", entry.path());
/// }
/// }
/// }
/// }
/// ```
#[inline]
pub fn metadata(&self) -> io::Result<Metadata> {
self.inner.metadata()
}
/// Returns the file type for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a
/// symlink.
///
/// # Platform-specific behavior
///
/// On Windows and most Unix platforms this function is free (no extra
/// system calls needed), but some Unix platforms may require the equivalent
/// call to `symlink_metadata` to learn about the target file type.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
/// for entry in entries {
/// if let Ok(entry) = entry {
/// // Here, `entry` is a `DirEntry`.
/// if let Ok(file_type) = entry.file_type() {
/// // Now let's show our entry's file type!
/// println!("{}: {:?}", entry.path(), file_type);
/// } else {
/// println!("Couldn't get file type for {}", entry.path());
/// }
/// }
/// }
/// }
/// ```
#[inline]
pub fn file_type(&self) -> io::Result<fs::FileType> {
self.inner.file_type()
}
/// Returns the bare file name of this directory entry without any other
/// leading path component.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
/// for entry in entries {
/// if let Ok(entry) = entry {
/// // Here, `entry` is a `DirEntry`.
/// println!("{}", entry.file_name());
/// }
/// }
/// }
/// ```
pub fn file_name(&self) -> &str {
self.path
.file_name()
.expect("path created through DirEntry must have a filename")
}
/// Returns the original [`fs::DirEntry`] within this [`Utf8DirEntry`].
#[inline]
pub fn into_inner(self) -> fs::DirEntry {
self.inner
}
}
impl From<String> for Utf8PathBuf {
fn from(string: String) -> Utf8PathBuf {
Utf8PathBuf(string.into())
}
}
impl FromStr for Utf8PathBuf {
type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Utf8PathBuf(s.into()))
}
}
// ---
// From impls: borrowed -> borrowed
// ---
impl<'a> From<&'a str> for &'a Utf8Path {
fn from(s: &'a str) -> &'a Utf8Path {
Utf8Path::new(s)
}
}
// ---
// From impls: borrowed -> owned
// ---
impl<T: ?Sized + AsRef<str>> From<&T> for Utf8PathBuf {
fn from(s: &T) -> Utf8PathBuf {
Utf8PathBuf::from(s.as_ref().to_owned())
}
}
impl<T: ?Sized + AsRef<str>> From<&T> for Box<Utf8Path> {
fn from(s: &T) -> Box<Utf8Path> {
Utf8PathBuf::from(s).into_boxed_path()
}
}
impl From<&'_ Utf8Path> for Arc<Utf8Path> {
fn from(path: &Utf8Path) -> Arc<Utf8Path> {
let arc: Arc<Path> = Arc::from(AsRef::<Path>::as_ref(path));
let ptr = Arc::into_raw(arc) as *const Utf8Path;
// SAFETY:
// * path is valid UTF-8
// * ptr was created by consuming an Arc<Path> so it represents an arced pointer
// * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
// *const Utf8Path is valid
unsafe { Arc::from_raw(ptr) }
}
}
impl From<&'_ Utf8Path> for Rc<Utf8Path> {
fn from(path: &Utf8Path) -> Rc<Utf8Path> {
let rc: Rc<Path> = Rc::from(AsRef::<Path>::as_ref(path));
let ptr = Rc::into_raw(rc) as *const Utf8Path;
// SAFETY:
// * path is valid UTF-8
// * ptr was created by consuming an Rc<Path> so it represents an rced pointer
// * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
// *const Utf8Path is valid
unsafe { Rc::from_raw(ptr) }
}
}
impl<'a> From<&'a Utf8Path> for Cow<'a, Utf8Path> {
fn from(path: &'a Utf8Path) -> Cow<'a, Utf8Path> {
Cow::Borrowed(path)
}
}
impl From<&'_ Utf8Path> for Box<Path> {
fn from(path: &Utf8Path) -> Box<Path> {
AsRef::<Path>::as_ref(path).into()
}
}
impl From<&'_ Utf8Path> for Arc<Path> {
fn from(path: &Utf8Path) -> Arc<Path> {
AsRef::<Path>::as_ref(path).into()
}
}
impl From<&'_ Utf8Path> for Rc<Path> {
fn from(path: &Utf8Path) -> Rc<Path> {
AsRef::<Path>::as_ref(path).into()
}
}
impl<'a> From<&'a Utf8Path> for Cow<'a, Path> {
fn from(path: &'a Utf8Path) -> Cow<'a, Path> {
Cow::Borrowed(path.as_ref())
}
}
// ---
// From impls: owned -> owned
// ---
impl From<Box<Utf8Path>> for Utf8PathBuf {
fn from(path: Box<Utf8Path>) -> Utf8PathBuf {
path.into_path_buf()
}
}
impl From<Utf8PathBuf> for Box<Utf8Path> {
fn from(path: Utf8PathBuf) -> Box<Utf8Path> {
path.into_boxed_path()
}
}
impl<'a> From<Cow<'a, Utf8Path>> for Utf8PathBuf {
fn from(path: Cow<'a, Utf8Path>) -> Utf8PathBuf {
path.into_owned()
}
}
impl From<Utf8PathBuf> for String {
fn from(path: Utf8PathBuf) -> String {
path.into_string()
}
}
impl From<Utf8PathBuf> for OsString {
fn from(path: Utf8PathBuf) -> OsString {
path.into_os_string()
}
}
impl<'a> From<Utf8PathBuf> for Cow<'a, Utf8Path> {
fn from(path: Utf8PathBuf) -> Cow<'a, Utf8Path> {
Cow::Owned(path)
}
}
impl From<Utf8PathBuf> for Arc<Utf8Path> {
fn from(path: Utf8PathBuf) -> Arc<Utf8Path> {
let arc: Arc<Path> = Arc::from(path.0);
let ptr = Arc::into_raw(arc) as *const Utf8Path;
// SAFETY:
// * path is valid UTF-8
// * ptr was created by consuming an Arc<Path> so it represents an arced pointer
// * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
// *const Utf8Path is valid
unsafe { Arc::from_raw(ptr) }
}
}
impl From<Utf8PathBuf> for Rc<Utf8Path> {
fn from(path: Utf8PathBuf) -> Rc<Utf8Path> {
let rc: Rc<Path> = Rc::from(path.0);
let ptr = Rc::into_raw(rc) as *const Utf8Path;
// SAFETY:
// * path is valid UTF-8
// * ptr was created by consuming an Rc<Path> so it represents an rced pointer
// * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
// *const Utf8Path is valid
unsafe { Rc::from_raw(ptr) }
}
}
impl From<Utf8PathBuf> for PathBuf {
fn from(path: Utf8PathBuf) -> PathBuf {
path.0
}
}
impl From<Utf8PathBuf> for Box<Path> {
fn from(path: Utf8PathBuf) -> Box<Path> {
PathBuf::from(path).into_boxed_path()
}
}
impl From<Utf8PathBuf> for Arc<Path> {
fn from(path: Utf8PathBuf) -> Arc<Path> {
PathBuf::from(path).into()
}
}
impl From<Utf8PathBuf> for Rc<Path> {
fn from(path: Utf8PathBuf) -> Rc<Path> {
PathBuf::from(path).into()
}
}
impl<'a> From<Utf8PathBuf> for Cow<'a, Path> {
fn from(path: Utf8PathBuf) -> Cow<'a, Path> {
PathBuf::from(path).into()
}
}
// ---
// TryFrom impls
// ---
impl TryFrom<PathBuf> for Utf8PathBuf {
type Error = FromPathBufError;
fn try_from(path: PathBuf) -> Result<Utf8PathBuf, Self::Error> {
Utf8PathBuf::from_path_buf(path).map_err(|path| FromPathBufError {
path,
error: FromPathError(()),
})
}
}
impl<'a> TryFrom<&'a Path> for &'a Utf8Path {
type Error = FromPathError;
fn try_from(path: &'a Path) -> Result<&'a Utf8Path, Self::Error> {
Utf8Path::from_path(path).ok_or(FromPathError(()))
}
}
/// A possible error value while converting a [`PathBuf`] to a [`Utf8PathBuf`].
///
/// Produced by the `TryFrom<PathBuf>` implementation for [`Utf8PathBuf`].
///
/// # Examples
///
/// ```
/// use camino::{Utf8PathBuf, FromPathBufError};
/// use std::convert::{TryFrom, TryInto};
/// use std::ffi::OsStr;
/// # #[cfg(unix)]
/// use std::os::unix::ffi::OsStrExt;
/// use std::path::PathBuf;
///
/// let unicode_path = PathBuf::from("/valid/unicode");
/// let utf8_path_buf: Utf8PathBuf = unicode_path.try_into().expect("valid Unicode path succeeded");
///
/// // Paths on Unix can be non-UTF-8.
/// # #[cfg(unix)]
/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
/// # #[cfg(unix)]
/// let non_unicode_path = PathBuf::from(non_unicode_str);
/// # #[cfg(unix)]
/// let err: FromPathBufError = Utf8PathBuf::try_from(non_unicode_path.clone())
/// .expect_err("non-Unicode path failed");
/// # #[cfg(unix)]
/// assert_eq!(err.as_path(), &non_unicode_path);
/// # #[cfg(unix)]
/// assert_eq!(err.into_path_buf(), non_unicode_path);
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FromPathBufError {
path: PathBuf,
error: FromPathError,
}
impl FromPathBufError {
/// Returns the [`Path`] slice that was attempted to be converted to [`Utf8PathBuf`].
pub fn as_path(&self) -> &Path {
&self.path
}
/// Returns the [`PathBuf`] that was attempted to be converted to [`Utf8PathBuf`].
pub fn into_path_buf(self) -> PathBuf {
self.path
}
/// Fetch a [`FromPathError`] for more about the conversion failure.
///
/// At the moment this struct does not contain any additional information, but is provided for
/// completeness.
pub fn from_path_error(&self) -> FromPathError {
self.error
}
}
impl fmt::Display for FromPathBufError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PathBuf contains invalid UTF-8: {}", self.path.display())
}
}
impl error::Error for FromPathBufError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
Some(&self.error)
}
}
/// A possible error value while converting a [`Path`] to a [`Utf8Path`].
///
/// Produced by the `TryFrom<&Path>` implementation for [`&Utf8Path`](Utf8Path).
///
///
/// # Examples
///
/// ```
/// use camino::{Utf8Path, FromPathError};
/// use std::convert::{TryFrom, TryInto};
/// use std::ffi::OsStr;
/// # #[cfg(unix)]
/// use std::os::unix::ffi::OsStrExt;
/// use std::path::Path;
///
/// let unicode_path = Path::new("/valid/unicode");
/// let utf8_path: &Utf8Path = unicode_path.try_into().expect("valid Unicode path succeeded");
///
/// // Paths on Unix can be non-UTF-8.
/// # #[cfg(unix)]
/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
/// # #[cfg(unix)]
/// let non_unicode_path = Path::new(non_unicode_str);
/// # #[cfg(unix)]
/// let err: FromPathError = <&Utf8Path>::try_from(non_unicode_path)
/// .expect_err("non-Unicode path failed");
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct FromPathError(());
impl fmt::Display for FromPathError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Path contains invalid UTF-8")
}
}
impl error::Error for FromPathError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
None
}
}
// ---
// AsRef impls
// ---
impl AsRef<Utf8Path> for Utf8Path {
fn as_ref(&self) -> &Utf8Path {
self
}
}
impl AsRef<Utf8Path> for Utf8PathBuf {
fn as_ref(&self) -> &Utf8Path {
self.as_path()
}
}
impl AsRef<Utf8Path> for str {
fn as_ref(&self) -> &Utf8Path {
Utf8Path::new(self)
}
}
impl AsRef<Utf8Path> for String {
fn as_ref(&self) -> &Utf8Path {
Utf8Path::new(self)
}
}
impl AsRef<Path> for Utf8Path {
fn as_ref(&self) -> &Path {
&self.0
}
}
impl AsRef<Path> for Utf8PathBuf {
fn as_ref(&self) -> &Path {
&*self.0
}
}
impl AsRef<str> for Utf8Path {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<str> for Utf8PathBuf {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<OsStr> for Utf8Path {
fn as_ref(&self) -> &OsStr {
self.as_os_str()
}
}
impl AsRef<OsStr> for Utf8PathBuf {
fn as_ref(&self) -> &OsStr {
self.as_os_str()
}
}
// ---
// Borrow and ToOwned
// ---
impl Borrow<Utf8Path> for Utf8PathBuf {
fn borrow(&self) -> &Utf8Path {
self.as_path()
}
}
impl ToOwned for Utf8Path {
type Owned = Utf8PathBuf;
fn to_owned(&self) -> Utf8PathBuf {
self.to_path_buf()
}
}
impl<P: AsRef<Utf8Path>> std::iter::FromIterator<P> for Utf8PathBuf {
fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> Utf8PathBuf {
let mut buf = Utf8PathBuf::new();
buf.extend(iter);
buf
}
}
// ---
// [Partial]Eq, [Partial]Ord, Hash
// ---
impl PartialEq for Utf8PathBuf {
fn eq(&self, other: &Utf8PathBuf) -> bool {
self.components() == other.components()
}
}
impl Eq for Utf8PathBuf {}
impl Hash for Utf8PathBuf {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_path().hash(state)
}
}
impl PartialOrd for Utf8PathBuf {
fn partial_cmp(&self, other: &Utf8PathBuf) -> Option<Ordering> {
self.components().partial_cmp(other.components())
}
}
impl Ord for Utf8PathBuf {
fn cmp(&self, other: &Utf8PathBuf) -> Ordering {
self.components().cmp(other.components())
}
}
impl PartialEq for Utf8Path {
fn eq(&self, other: &Utf8Path) -> bool {
self.components().eq(other.components())
}
}
impl Eq for Utf8Path {}
impl Hash for Utf8Path {
fn hash<H: Hasher>(&self, state: &mut H) {
for component in self.components() {
component.hash(state)
}
}
}
impl PartialOrd for Utf8Path {
fn partial_cmp(&self, other: &Utf8Path) -> Option<Ordering> {
self.components().partial_cmp(other.components())
}
}
impl Ord for Utf8Path {
fn cmp(&self, other: &Utf8Path) -> Ordering {
self.components().cmp(other.components())
}
}
impl<'a> IntoIterator for &'a Utf8PathBuf {
type Item = &'a str;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
impl<'a> IntoIterator for &'a Utf8Path {
type Item = &'a str;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
macro_rules! impl_cmp {
($lhs:ty, $rhs: ty) => {
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool {
<Utf8Path as PartialEq>::eq(self, other)
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool {
<Utf8Path as PartialEq>::eq(self, other)
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialOrd<$rhs> for $lhs {
#[inline]
fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> {
<Utf8Path as PartialOrd>::partial_cmp(self, other)
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialOrd<$lhs> for $rhs {
#[inline]
fn partial_cmp(&self, other: &$lhs) -> Option<Ordering> {
<Utf8Path as PartialOrd>::partial_cmp(self, other)
}
}
};
}
impl_cmp!(Utf8PathBuf, Utf8Path);
impl_cmp!(Utf8PathBuf, &'a Utf8Path);
impl_cmp!(Cow<'a, Utf8Path>, Utf8Path);
impl_cmp!(Cow<'a, Utf8Path>, &'b Utf8Path);
impl_cmp!(Cow<'a, Utf8Path>, Utf8PathBuf);
macro_rules! impl_cmp_std_path {
($lhs:ty, $rhs: ty) => {
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialOrd<$rhs> for $lhs {
#[inline]
fn partial_cmp(&self, other: &$rhs) -> Option<std::cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialOrd<$lhs> for $rhs {
#[inline]
fn partial_cmp(&self, other: &$lhs) -> Option<std::cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
};
}
impl_cmp_std_path!(Utf8PathBuf, Path);
impl_cmp_std_path!(Utf8PathBuf, &'a Path);
impl_cmp_std_path!(Utf8PathBuf, Cow<'a, Path>);
impl_cmp_std_path!(Utf8PathBuf, PathBuf);
impl_cmp_std_path!(Utf8Path, Path);
impl_cmp_std_path!(Utf8Path, &'a Path);
impl_cmp_std_path!(Utf8Path, Cow<'a, Path>);
impl_cmp_std_path!(Utf8Path, PathBuf);
impl_cmp_std_path!(&'a Utf8Path, Path);
impl_cmp_std_path!(&'a Utf8Path, Cow<'b, Path>);
impl_cmp_std_path!(&'a Utf8Path, PathBuf);
// NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117)
macro_rules! impl_cmp_str {
($lhs:ty, $rhs: ty) => {
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool {
<Utf8Path as PartialEq>::eq(self, Utf8Path::new(other))
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool {
<Utf8Path as PartialEq>::eq(Utf8Path::new(self), other)
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialOrd<$rhs> for $lhs {
#[inline]
fn partial_cmp(&self, other: &$rhs) -> Option<std::cmp::Ordering> {
<Utf8Path as PartialOrd>::partial_cmp(self, Utf8Path::new(other))
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialOrd<$lhs> for $rhs {
#[inline]
fn partial_cmp(&self, other: &$lhs) -> Option<std::cmp::Ordering> {
<Utf8Path as PartialOrd>::partial_cmp(Utf8Path::new(self), other)
}
}
};
}
impl_cmp_str!(Utf8PathBuf, str);
impl_cmp_str!(Utf8PathBuf, &'a str);
impl_cmp_str!(Utf8PathBuf, Cow<'a, str>);
impl_cmp_str!(Utf8PathBuf, String);
impl_cmp_str!(Utf8Path, str);
impl_cmp_str!(Utf8Path, &'a str);
impl_cmp_str!(Utf8Path, Cow<'a, str>);
impl_cmp_str!(Utf8Path, String);
impl_cmp_str!(&'a Utf8Path, str);
impl_cmp_str!(&'a Utf8Path, Cow<'b, str>);
impl_cmp_str!(&'a Utf8Path, String);
// NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117)
macro_rules! impl_cmp_os_str {
($lhs:ty, $rhs: ty) => {
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other.as_ref())
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other.as_ref())
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialOrd<$rhs> for $lhs {
#[inline]
fn partial_cmp(&self, other: &$rhs) -> Option<std::cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other.as_ref())
}
}
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'b> PartialOrd<$lhs> for $rhs {
#[inline]
fn partial_cmp(&self, other: &$lhs) -> Option<std::cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other.as_ref())
}
}
};
}
impl_cmp_os_str!(Utf8PathBuf, OsStr);
impl_cmp_os_str!(Utf8PathBuf, &'a OsStr);
impl_cmp_os_str!(Utf8PathBuf, Cow<'a, OsStr>);
impl_cmp_os_str!(Utf8PathBuf, OsString);
impl_cmp_os_str!(Utf8Path, OsStr);
impl_cmp_os_str!(Utf8Path, &'a OsStr);
impl_cmp_os_str!(Utf8Path, Cow<'a, OsStr>);
impl_cmp_os_str!(Utf8Path, OsString);
impl_cmp_os_str!(&'a Utf8Path, OsStr);
impl_cmp_os_str!(&'a Utf8Path, Cow<'b, OsStr>);
impl_cmp_os_str!(&'a Utf8Path, OsString);
// NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117)
// invariant: OsStr must be guaranteed to be utf8 data
unsafe fn assume_utf8(string: &OsStr) -> &str {
&*(string as *const OsStr as *const str)
}