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
//! Tools and combinators for I/O.
//!
//! # Examples
//!
//! ```
//! use futures_lite::io::{self, AsyncReadExt};
//!
//! # spin_on::spin_on(async {
//! let input: &[u8] = b"hello";
//! let mut reader = io::BufReader::new(input);
//!
//! let mut contents = String::new();
//! reader.read_to_string(&mut contents).await?;
//! # std::io::Result::Ok(()) });
//! ```
#[doc(no_inline)]
pub use std::io::{Error, ErrorKind, Result, SeekFrom};
#[doc(no_inline)]
pub use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite};
use std::cmp;
use std::fmt;
use std::future::Future;
use std::io::{IoSlice, IoSliceMut};
use std::mem;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use futures_core::stream::Stream;
use pin_project_lite::pin_project;
use crate::future;
use crate::ready;
const DEFAULT_BUF_SIZE: usize = 8 * 1024;
/// Copies the entire contents of a reader into a writer.
///
/// This function will read data from `reader` and write it into `writer` in a streaming fashion
/// until `reader` returns EOF.
///
/// On success, returns the total number of bytes copied.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{self, BufReader, BufWriter};
///
/// # spin_on::spin_on(async {
/// let input: &[u8] = b"hello";
/// let reader = BufReader::new(input);
///
/// let mut output = Vec::new();
/// let writer = BufWriter::new(&mut output);
///
/// io::copy(reader, writer).await?;
/// # std::io::Result::Ok(()) });
/// ```
pub async fn copy<R, W>(reader: R, writer: W) -> Result<u64>
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
pin_project! {
struct CopyFuture<R, W> {
#[pin]
reader: R,
#[pin]
writer: W,
amt: u64,
}
}
impl<R, W> Future for CopyFuture<R, W>
where
R: AsyncBufRead,
W: AsyncWrite + Unpin,
{
type Output = Result<u64>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
loop {
let buffer = ready!(this.reader.as_mut().poll_fill_buf(cx))?;
if buffer.is_empty() {
ready!(this.writer.as_mut().poll_flush(cx))?;
return Poll::Ready(Ok(*this.amt));
}
let i = ready!(this.writer.as_mut().poll_write(cx, buffer))?;
if i == 0 {
return Poll::Ready(Err(ErrorKind::WriteZero.into()));
}
*this.amt += i as u64;
this.reader.as_mut().consume(i);
}
}
}
let future = CopyFuture {
reader: BufReader::new(reader),
writer,
amt: 0,
};
future.await
}
/// Asserts that a type implementing [`std::io`] traits can be used as an async type.
///
/// The underlying I/O handle should never block nor return the [`ErrorKind::WouldBlock`] error.
/// This is usually the case for in-memory buffered I/O.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AssertAsync, AsyncReadExt};
///
/// let reader: &[u8] = b"hello";
///
/// # spin_on::spin_on(async {
/// let mut async_reader = AssertAsync::new(reader);
/// let mut contents = String::new();
///
/// // This line works in async manner - note that there is await:
/// async_reader.read_to_string(&mut contents).await?;
/// # std::io::Result::Ok(()) });
/// ```
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct AssertAsync<T>(T);
impl<T> Unpin for AssertAsync<T> {}
impl<T> AssertAsync<T> {
/// Wraps an I/O handle implementing [`std::io`] traits.
///
/// # Examples
///
/// ```
/// use futures_lite::io::AssertAsync;
///
/// let reader: &[u8] = b"hello";
///
/// let async_reader = AssertAsync::new(reader);
/// ```
pub fn new(io: T) -> Self {
AssertAsync(io)
}
/// Gets a reference to the inner I/O handle.
///
/// # Examples
///
/// ```
/// use futures_lite::io::AssertAsync;
///
/// let reader: &[u8] = b"hello";
///
/// let async_reader = AssertAsync::new(reader);
/// let r = async_reader.get_ref();
/// ```
pub fn get_ref(&self) -> &T {
&self.0
}
/// Gets a mutable reference to the inner I/O handle.
///
/// # Examples
///
/// ```
/// use futures_lite::io::AssertAsync;
///
/// let reader: &[u8] = b"hello";
///
/// let mut async_reader = AssertAsync::new(reader);
/// let r = async_reader.get_mut();
/// ```
pub fn get_mut(&mut self) -> &mut T {
&mut self.0
}
/// Extracts the inner I/O handle.
///
/// # Examples
///
/// ```
/// use futures_lite::io::AssertAsync;
///
/// let reader: &[u8] = b"hello";
///
/// let async_reader = AssertAsync::new(reader);
/// let inner = async_reader.into_inner();
/// ```
pub fn into_inner(self) -> T {
self.0
}
}
impl<T: std::io::Read> AsyncRead for AssertAsync<T> {
fn poll_read(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
loop {
match self.0.read(buf) {
Err(err) if err.kind() == ErrorKind::Interrupted => {}
res => return Poll::Ready(res),
}
}
}
fn poll_read_vectored(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<Result<usize>> {
loop {
match self.0.read_vectored(bufs) {
Err(err) if err.kind() == ErrorKind::Interrupted => {}
res => return Poll::Ready(res),
}
}
}
}
impl<T: std::io::Write> AsyncWrite for AssertAsync<T> {
fn poll_write(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
loop {
match self.0.write(buf) {
Err(err) if err.kind() == ErrorKind::Interrupted => {}
res => return Poll::Ready(res),
}
}
}
fn poll_write_vectored(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<Result<usize>> {
loop {
match self.0.write_vectored(bufs) {
Err(err) if err.kind() == ErrorKind::Interrupted => {}
res => return Poll::Ready(res),
}
}
}
fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<()>> {
loop {
match self.0.flush() {
Err(err) if err.kind() == ErrorKind::Interrupted => {}
res => return Poll::Ready(res),
}
}
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.poll_flush(cx)
}
}
impl<T: std::io::Seek> AsyncSeek for AssertAsync<T> {
fn poll_seek(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
pos: SeekFrom,
) -> Poll<Result<u64>> {
loop {
match self.0.seek(pos) {
Err(err) if err.kind() == ErrorKind::Interrupted => {}
res => return Poll::Ready(res),
}
}
}
}
/// Blocks on all async I/O operations and implements [`std::io`] traits.
///
/// Sometimes async I/O needs to be used in a blocking manner. If calling [`future::block_on()`]
/// manually all the time becomes too tedious, use this type for more convenient blocking on async
/// I/O operations.
///
/// This type implements traits [`Read`][`std::io::Read`], [`Write`][`std::io::Write`], or
/// [`Seek`][`std::io::Seek`] if the inner type implements [`AsyncRead`], [`AsyncWrite`], or
/// [`AsyncSeek`], respectively.
///
/// If writing data through the [`Write`][`std::io::Write`] trait, make sure to flush before
/// dropping the [`BlockOn`] handle or some buffered data might get lost.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BlockOn;
/// use futures_lite::pin;
/// use std::io::Read;
///
/// let reader: &[u8] = b"hello";
/// pin!(reader);
///
/// let mut blocking_reader = BlockOn::new(reader);
/// let mut contents = String::new();
///
/// // This line blocks - note that there is no await:
/// blocking_reader.read_to_string(&mut contents)?;
/// # std::io::Result::Ok(())
/// ```
#[derive(Debug)]
pub struct BlockOn<T>(T);
impl<T> BlockOn<T> {
/// Wraps an async I/O handle into a blocking interface.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BlockOn;
/// use futures_lite::pin;
///
/// let reader: &[u8] = b"hello";
/// pin!(reader);
///
/// let blocking_reader = BlockOn::new(reader);
/// ```
pub fn new(io: T) -> BlockOn<T> {
BlockOn(io)
}
/// Gets a reference to the async I/O handle.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BlockOn;
/// use futures_lite::pin;
///
/// let reader: &[u8] = b"hello";
/// pin!(reader);
///
/// let blocking_reader = BlockOn::new(reader);
/// let r = blocking_reader.get_ref();
/// ```
pub fn get_ref(&self) -> &T {
&self.0
}
/// Gets a mutable reference to the async I/O handle.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BlockOn;
/// use futures_lite::pin;
///
/// let reader: &[u8] = b"hello";
/// pin!(reader);
///
/// let mut blocking_reader = BlockOn::new(reader);
/// let r = blocking_reader.get_mut();
/// ```
pub fn get_mut(&mut self) -> &mut T {
&mut self.0
}
/// Extracts the inner async I/O handle.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BlockOn;
/// use futures_lite::pin;
///
/// let reader: &[u8] = b"hello";
/// pin!(reader);
///
/// let blocking_reader = BlockOn::new(reader);
/// let inner = blocking_reader.into_inner();
/// ```
pub fn into_inner(self) -> T {
self.0
}
}
impl<T: AsyncRead + Unpin> std::io::Read for BlockOn<T> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
future::block_on(self.0.read(buf))
}
}
impl<T: AsyncBufRead + Unpin> std::io::BufRead for BlockOn<T> {
fn fill_buf(&mut self) -> Result<&[u8]> {
future::block_on(self.0.fill_buf())
}
fn consume(&mut self, amt: usize) {
Pin::new(&mut self.0).consume(amt)
}
}
impl<T: AsyncWrite + Unpin> std::io::Write for BlockOn<T> {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
future::block_on(self.0.write(buf))
}
fn flush(&mut self) -> Result<()> {
future::block_on(self.0.flush())
}
}
impl<T: AsyncSeek + Unpin> std::io::Seek for BlockOn<T> {
fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
future::block_on(self.0.seek(pos))
}
}
pin_project! {
/// Adds buffering to a reader.
///
/// It can be excessively inefficient to work directly with an [`AsyncRead`] instance. A
/// [`BufReader`] performs large, infrequent reads on the underlying [`AsyncRead`] and
/// maintains an in-memory buffer of the incoming byte stream.
///
/// [`BufReader`] can improve the speed of programs that make *small* and *repeated* reads to
/// the same file or networking socket. It does not help when reading very large amounts at
/// once, or reading just once or a few times. It also provides no advantage when reading from
/// a source that is already in memory, like a `Vec<u8>`.
///
/// When a [`BufReader`] is dropped, the contents of its buffer are discarded. Creating
/// multiple instances of [`BufReader`] on the same reader can cause data loss.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncBufReadExt, BufReader};
///
/// # spin_on::spin_on(async {
/// let input: &[u8] = b"hello";
/// let mut reader = BufReader::new(input);
///
/// let mut line = String::new();
/// reader.read_line(&mut line).await?;
/// # std::io::Result::Ok(()) });
/// ```
pub struct BufReader<R> {
#[pin]
inner: R,
buf: Box<[u8]>,
pos: usize,
cap: usize,
}
}
impl<R: AsyncRead> BufReader<R> {
/// Creates a buffered reader with the default buffer capacity.
///
/// The default capacity is currently 8 KB, but that may change in the future.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufReader;
///
/// let input: &[u8] = b"hello";
/// let reader = BufReader::new(input);
/// ```
pub fn new(inner: R) -> BufReader<R> {
BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
}
/// Creates a buffered reader with the specified capacity.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufReader;
///
/// let input: &[u8] = b"hello";
/// let reader = BufReader::with_capacity(1024, input);
/// ```
pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
BufReader {
inner,
buf: vec![0; capacity].into_boxed_slice(),
pos: 0,
cap: 0,
}
}
}
impl<R> BufReader<R> {
/// Gets a reference to the underlying reader.
///
/// It is not advisable to directly read from the underlying reader.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufReader;
///
/// let input: &[u8] = b"hello";
/// let reader = BufReader::new(input);
///
/// let r = reader.get_ref();
/// ```
pub fn get_ref(&self) -> &R {
&self.inner
}
/// Gets a mutable reference to the underlying reader.
///
/// It is not advisable to directly read from the underlying reader.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufReader;
///
/// let input: &[u8] = b"hello";
/// let mut reader = BufReader::new(input);
///
/// let r = reader.get_mut();
/// ```
pub fn get_mut(&mut self) -> &mut R {
&mut self.inner
}
/// Gets a pinned mutable reference to the underlying reader.
///
/// It is not advisable to directly read from the underlying reader.
fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R> {
self.project().inner
}
/// Returns a reference to the internal buffer.
///
/// This method will not attempt to fill the buffer if it is empty.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufReader;
///
/// let input: &[u8] = b"hello";
/// let reader = BufReader::new(input);
///
/// // The internal buffer is empty until the first read request.
/// assert_eq!(reader.buffer(), &[]);
/// ```
pub fn buffer(&self) -> &[u8] {
&self.buf[self.pos..self.cap]
}
/// Unwraps the buffered reader, returning the underlying reader.
///
/// Note that any leftover data in the internal buffer will be lost.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufReader;
///
/// let input: &[u8] = b"hello";
/// let reader = BufReader::new(input);
///
/// assert_eq!(reader.into_inner(), input);
/// ```
pub fn into_inner(self) -> R {
self.inner
}
/// Invalidates all data in the internal buffer.
#[inline]
fn discard_buffer(self: Pin<&mut Self>) {
let this = self.project();
*this.pos = 0;
*this.cap = 0;
}
}
impl<R: AsyncRead> AsyncRead for BufReader<R> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
// If we don't have any buffered data and we're doing a massive read
// (larger than our internal buffer), bypass our internal buffer
// entirely.
if self.pos == self.cap && buf.len() >= self.buf.len() {
let res = ready!(self.as_mut().get_pin_mut().poll_read(cx, buf));
self.discard_buffer();
return Poll::Ready(res);
}
let mut rem = ready!(self.as_mut().poll_fill_buf(cx))?;
let nread = std::io::Read::read(&mut rem, buf)?;
self.consume(nread);
Poll::Ready(Ok(nread))
}
fn poll_read_vectored(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<Result<usize>> {
let total_len = bufs.iter().map(|b| b.len()).sum::<usize>();
if self.pos == self.cap && total_len >= self.buf.len() {
let res = ready!(self.as_mut().get_pin_mut().poll_read_vectored(cx, bufs));
self.discard_buffer();
return Poll::Ready(res);
}
let mut rem = ready!(self.as_mut().poll_fill_buf(cx))?;
let nread = std::io::Read::read_vectored(&mut rem, bufs)?;
self.consume(nread);
Poll::Ready(Ok(nread))
}
}
impl<R: AsyncRead> AsyncBufRead for BufReader<R> {
fn poll_fill_buf<'a>(self: Pin<&'a mut Self>, cx: &mut Context<'_>) -> Poll<Result<&'a [u8]>> {
let mut this = self.project();
// If we've reached the end of our internal buffer then we need to fetch
// some more data from the underlying reader.
// Branch using `>=` instead of the more correct `==`
// to tell the compiler that the pos..cap slice is always valid.
if *this.pos >= *this.cap {
debug_assert!(*this.pos == *this.cap);
*this.cap = ready!(this.inner.as_mut().poll_read(cx, this.buf))?;
*this.pos = 0;
}
Poll::Ready(Ok(&this.buf[*this.pos..*this.cap]))
}
fn consume(self: Pin<&mut Self>, amt: usize) {
let this = self.project();
*this.pos = cmp::min(*this.pos + amt, *this.cap);
}
}
impl<R: AsyncRead + fmt::Debug> fmt::Debug for BufReader<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BufReader")
.field("reader", &self.inner)
.field(
"buffer",
&format_args!("{}/{}", self.cap - self.pos, self.buf.len()),
)
.finish()
}
}
impl<R: AsyncSeek> AsyncSeek for BufReader<R> {
/// Seeks to an offset, in bytes, in the underlying reader.
///
/// The position used for seeking with [`SeekFrom::Current`] is the position the underlying
/// reader would be at if the [`BufReader`] had no internal buffer.
///
/// Seeking always discards the internal buffer, even if the seek position would otherwise fall
/// within it. This guarantees that calling [`into_inner()`][`BufReader::into_inner()`]
/// immediately after a seek yields the underlying reader at the same position.
///
/// See [`AsyncSeek`] for more details.
///
/// Note: In the edge case where you're seeking with `SeekFrom::Current(n)` where `n` minus the
/// internal buffer length overflows an `i64`, two seeks will be performed instead of one. If
/// the second seek returns `Err`, the underlying reader will be left at the same position it
/// would have if you called [`seek()`][`AsyncSeekExt::seek()`] with `SeekFrom::Current(0)`.
fn poll_seek(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
pos: SeekFrom,
) -> Poll<Result<u64>> {
let result: u64;
if let SeekFrom::Current(n) = pos {
let remainder = (self.cap - self.pos) as i64;
// it should be safe to assume that remainder fits within an i64 as the alternative
// means we managed to allocate 8 exbibytes and that's absurd.
// But it's not out of the realm of possibility for some weird underlying reader to
// support seeking by i64::min_value() so we need to handle underflow when subtracting
// remainder.
if let Some(offset) = n.checked_sub(remainder) {
result = ready!(self
.as_mut()
.get_pin_mut()
.poll_seek(cx, SeekFrom::Current(offset)))?;
} else {
// seek backwards by our remainder, and then by the offset
ready!(self
.as_mut()
.get_pin_mut()
.poll_seek(cx, SeekFrom::Current(-remainder)))?;
self.as_mut().discard_buffer();
result = ready!(self
.as_mut()
.get_pin_mut()
.poll_seek(cx, SeekFrom::Current(n)))?;
}
} else {
// Seeking with Start/End doesn't care about our buffer length.
result = ready!(self.as_mut().get_pin_mut().poll_seek(cx, pos))?;
}
self.discard_buffer();
Poll::Ready(Ok(result))
}
}
impl<R: AsyncWrite> AsyncWrite for BufReader<R> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
self.as_mut().get_pin_mut().poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.as_mut().get_pin_mut().poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.as_mut().get_pin_mut().poll_close(cx)
}
}
pin_project! {
/// Adds buffering to a writer.
///
/// It can be excessively inefficient to work directly with something that implements
/// [`AsyncWrite`]. For example, every call to [`write()`][`AsyncWriteExt::write()`] on a TCP
/// stream results in a system call. A [`BufWriter`] keeps an in-memory buffer of data and
/// writes it to the underlying writer in large, infrequent batches.
///
/// [`BufWriter`] can improve the speed of programs that make *small* and *repeated* writes to
/// the same file or networking socket. It does not help when writing very large amounts at
/// once, or writing just once or a few times. It also provides no advantage when writing to a
/// destination that is in memory, like a `Vec<u8>`.
///
/// Unlike [`std::io::BufWriter`], this type does not write out the contents of its buffer when
/// it is dropped. Therefore, it is important that users explicitly flush the buffer before
/// dropping the [`BufWriter`].
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncWriteExt, BufWriter};
///
/// # spin_on::spin_on(async {
/// let mut output = Vec::new();
/// let mut writer = BufWriter::new(&mut output);
///
/// writer.write_all(b"hello").await?;
/// writer.flush().await?;
/// # std::io::Result::Ok(()) });
/// ```
pub struct BufWriter<W> {
#[pin]
inner: W,
buf: Vec<u8>,
written: usize,
}
}
impl<W: AsyncWrite> BufWriter<W> {
/// Creates a buffered writer with the default buffer capacity.
///
/// The default capacity is currently 8 KB, but that may change in the future.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufWriter;
///
/// let mut output = Vec::new();
/// let writer = BufWriter::new(&mut output);
/// ```
pub fn new(inner: W) -> BufWriter<W> {
BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner)
}
/// Creates a buffered writer with the specified buffer capacity.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufWriter;
///
/// let mut output = Vec::new();
/// let writer = BufWriter::with_capacity(100, &mut output);
/// ```
pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W> {
BufWriter {
inner,
buf: Vec::with_capacity(capacity),
written: 0,
}
}
/// Gets a reference to the underlying writer.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufWriter;
///
/// let mut output = Vec::new();
/// let writer = BufWriter::new(&mut output);
///
/// let r = writer.get_ref();
/// ```
pub fn get_ref(&self) -> &W {
&self.inner
}
/// Gets a mutable reference to the underlying writer.
///
/// It is not advisable to directly write to the underlying writer.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufWriter;
///
/// let mut output = Vec::new();
/// let mut writer = BufWriter::new(&mut output);
///
/// let r = writer.get_mut();
/// ```
pub fn get_mut(&mut self) -> &mut W {
&mut self.inner
}
/// Gets a pinned mutable reference to the underlying writer.
///
/// It is not not advisable to directly write to the underlying writer.
fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W> {
self.project().inner
}
/// Unwraps the buffered writer, returning the underlying writer.
///
/// Note that any leftover data in the internal buffer will be lost. If you don't want to lose
/// that data, flush the buffered writer before unwrapping it.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncWriteExt, BufWriter};
///
/// # spin_on::spin_on(async {
/// let mut output = vec![1, 2, 3];
/// let mut writer = BufWriter::new(&mut output);
///
/// writer.write_all(&[4]).await?;
/// writer.flush().await?;
/// assert_eq!(writer.into_inner(), &[1, 2, 3, 4]);
/// # std::io::Result::Ok(()) });
/// ```
pub fn into_inner(self) -> W {
self.inner
}
/// Returns a reference to the internal buffer.
///
/// # Examples
///
/// ```
/// use futures_lite::io::BufWriter;
///
/// let mut output = Vec::new();
/// let writer = BufWriter::new(&mut output);
///
/// // The internal buffer is empty until the first write request.
/// assert_eq!(writer.buffer(), &[]);
/// ```
pub fn buffer(&self) -> &[u8] {
&self.buf
}
/// Flush the buffer.
fn poll_flush_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
let mut this = self.project();
let len = this.buf.len();
let mut ret = Ok(());
while *this.written < len {
match this
.inner
.as_mut()
.poll_write(cx, &this.buf[*this.written..])
{
Poll::Ready(Ok(0)) => {
ret = Err(Error::new(
ErrorKind::WriteZero,
"Failed to write buffered data",
));
break;
}
Poll::Ready(Ok(n)) => *this.written += n,
Poll::Ready(Err(ref e)) if e.kind() == ErrorKind::Interrupted => {}
Poll::Ready(Err(e)) => {
ret = Err(e);
break;
}
Poll::Pending => return Poll::Pending,
}
}
if *this.written > 0 {
this.buf.drain(..*this.written);
}
*this.written = 0;
Poll::Ready(ret)
}
}
impl<W: AsyncWrite + fmt::Debug> fmt::Debug for BufWriter<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BufWriter")
.field("writer", &self.inner)
.field("buf", &self.buf)
.finish()
}
}
impl<W: AsyncWrite> AsyncWrite for BufWriter<W> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
if self.buf.len() + buf.len() > self.buf.capacity() {
ready!(self.as_mut().poll_flush_buf(cx))?;
}
if buf.len() >= self.buf.capacity() {
self.get_pin_mut().poll_write(cx, buf)
} else {
Pin::new(&mut *self.project().buf).poll_write(cx, buf)
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
ready!(self.as_mut().poll_flush_buf(cx))?;
self.get_pin_mut().poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
ready!(self.as_mut().poll_flush_buf(cx))?;
self.get_pin_mut().poll_close(cx)
}
}
impl<W: AsyncWrite + AsyncSeek> AsyncSeek for BufWriter<W> {
/// Seek to the offset, in bytes, in the underlying writer.
///
/// Seeking always writes out the internal buffer before seeking.
fn poll_seek(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
pos: SeekFrom,
) -> Poll<Result<u64>> {
ready!(self.as_mut().poll_flush_buf(cx))?;
self.get_pin_mut().poll_seek(cx, pos)
}
}
/// Gives an in-memory buffer a cursor for reading and writing.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt, Cursor, SeekFrom};
///
/// # spin_on::spin_on(async {
/// let mut bytes = b"hello".to_vec();
/// let mut cursor = Cursor::new(&mut bytes);
///
/// // Overwrite 'h' with 'H'.
/// cursor.write_all(b"H").await?;
///
/// // Move the cursor one byte forward.
/// cursor.seek(SeekFrom::Current(1)).await?;
///
/// // Read a byte.
/// let mut byte = [0];
/// cursor.read_exact(&mut byte).await?;
/// assert_eq!(&byte, b"l");
///
/// // Check the final buffer.
/// assert_eq!(bytes, b"Hello");
/// # std::io::Result::Ok(()) });
/// ```
#[derive(Clone, Debug, Default)]
pub struct Cursor<T> {
inner: std::io::Cursor<T>,
}
impl<T> Cursor<T> {
/// Creates a cursor for an in-memory buffer.
///
/// Cursor's initial position is 0 even if the underlying buffer is not empty. Writing using
/// [`Cursor`] will overwrite the existing contents unless the cursor is moved to the end of
/// the buffer using [`set_position()`][Cursor::set_position()`] or
/// [`seek()`][`AsyncSeekExt::seek()`].
///
/// # Examples
///
/// ```
/// use futures_lite::io::Cursor;
///
/// let cursor = Cursor::new(Vec::<u8>::new());
/// ```
pub fn new(inner: T) -> Cursor<T> {
Cursor {
inner: std::io::Cursor::new(inner),
}
}
/// Gets a reference to the underlying buffer.
///
/// # Examples
///
/// ```
/// use futures_lite::io::Cursor;
///
/// let cursor = Cursor::new(Vec::<u8>::new());
/// let r = cursor.get_ref();
/// ```
pub fn get_ref(&self) -> &T {
self.inner.get_ref()
}
/// Gets a mutable reference to the underlying buffer.
///
/// # Examples
///
/// ```
/// use futures_lite::io::Cursor;
///
/// let mut cursor = Cursor::new(Vec::<u8>::new());
/// let r = cursor.get_mut();
/// ```
pub fn get_mut(&mut self) -> &mut T {
self.inner.get_mut()
}
/// Unwraps the cursor, returning the underlying buffer.
///
/// # Examples
///
/// ```
/// use futures_lite::io::Cursor;
///
/// let cursor = Cursor::new(vec![1, 2, 3]);
/// assert_eq!(cursor.into_inner(), [1, 2, 3]);
/// ```
pub fn into_inner(self) -> T {
self.inner.into_inner()
}
/// Returns the current position of this cursor.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncSeekExt, Cursor, SeekFrom};
///
/// # spin_on::spin_on(async {
/// let mut cursor = Cursor::new(b"hello");
/// assert_eq!(cursor.position(), 0);
///
/// cursor.seek(SeekFrom::Start(2)).await?;
/// assert_eq!(cursor.position(), 2);
/// # std::io::Result::Ok(()) });
/// ```
pub fn position(&self) -> u64 {
self.inner.position()
}
/// Sets the position of this cursor.
///
/// # Examples
///
/// ```
/// use futures_lite::io::Cursor;
///
/// let mut cursor = Cursor::new(b"hello");
/// assert_eq!(cursor.position(), 0);
///
/// cursor.set_position(2);
/// assert_eq!(cursor.position(), 2);
/// ```
pub fn set_position(&mut self, pos: u64) {
self.inner.set_position(pos)
}
}
impl<T> AsyncSeek for Cursor<T>
where
T: AsRef<[u8]> + Unpin,
{
fn poll_seek(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
pos: SeekFrom,
) -> Poll<Result<u64>> {
Poll::Ready(std::io::Seek::seek(&mut self.inner, pos))
}
}
impl<T> AsyncRead for Cursor<T>
where
T: AsRef<[u8]> + Unpin,
{
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
Poll::Ready(std::io::Read::read(&mut self.inner, buf))
}
fn poll_read_vectored(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<Result<usize>> {
Poll::Ready(std::io::Read::read_vectored(&mut self.inner, bufs))
}
}
impl<T> AsyncBufRead for Cursor<T>
where
T: AsRef<[u8]> + Unpin,
{
fn poll_fill_buf(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<&[u8]>> {
Poll::Ready(std::io::BufRead::fill_buf(&mut self.get_mut().inner))
}
fn consume(mut self: Pin<&mut Self>, amt: usize) {
std::io::BufRead::consume(&mut self.inner, amt)
}
}
impl AsyncWrite for Cursor<&mut [u8]> {
fn poll_write(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
Poll::Ready(std::io::Write::write(&mut self.inner, buf))
}
fn poll_write_vectored(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<Result<usize>> {
Poll::Ready(std::io::Write::write_vectored(&mut self.inner, bufs))
}
fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(std::io::Write::flush(&mut self.inner))
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.poll_flush(cx)
}
}
impl AsyncWrite for Cursor<&mut Vec<u8>> {
fn poll_write(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
Poll::Ready(std::io::Write::write(&mut self.inner, buf))
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.poll_flush(cx)
}
fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(std::io::Write::flush(&mut self.inner))
}
}
impl AsyncWrite for Cursor<Vec<u8>> {
fn poll_write(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
Poll::Ready(std::io::Write::write(&mut self.inner, buf))
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.poll_flush(cx)
}
fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(std::io::Write::flush(&mut self.inner))
}
}
/// Creates an empty reader.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{self, AsyncReadExt};
///
/// # spin_on::spin_on(async {
/// let mut reader = io::empty();
///
/// let mut contents = Vec::new();
/// reader.read_to_end(&mut contents).await?;
/// assert!(contents.is_empty());
/// # std::io::Result::Ok(()) });
/// ```
pub fn empty() -> Empty {
Empty { _private: () }
}
/// Reader for the [`empty()`] function.
pub struct Empty {
_private: (),
}
impl fmt::Debug for Empty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("Empty { .. }")
}
}
impl AsyncRead for Empty {
#[inline]
fn poll_read(self: Pin<&mut Self>, _: &mut Context<'_>, _: &mut [u8]) -> Poll<Result<usize>> {
Poll::Ready(Ok(0))
}
}
impl AsyncBufRead for Empty {
#[inline]
fn poll_fill_buf<'a>(self: Pin<&'a mut Self>, _: &mut Context<'_>) -> Poll<Result<&'a [u8]>> {
Poll::Ready(Ok(&[]))
}
#[inline]
fn consume(self: Pin<&mut Self>, _: usize) {}
}
/// Creates an infinite reader that reads the same byte repeatedly.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{self, AsyncReadExt};
///
/// # spin_on::spin_on(async {
/// let mut reader = io::repeat(b'a');
///
/// let mut contents = vec![0; 5];
/// reader.read_exact(&mut contents).await?;
/// assert_eq!(contents, b"aaaaa");
/// # std::io::Result::Ok(()) });
/// ```
pub fn repeat(byte: u8) -> Repeat {
Repeat { byte }
}
/// Reader for the [`repeat()`] function.
#[derive(Debug)]
pub struct Repeat {
byte: u8,
}
impl AsyncRead for Repeat {
#[inline]
fn poll_read(self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>> {
for b in &mut *buf {
*b = self.byte;
}
Poll::Ready(Ok(buf.len()))
}
}
/// Creates a writer that consumes and drops all data.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{self, AsyncWriteExt};
///
/// # spin_on::spin_on(async {
/// let mut writer = io::sink();
/// writer.write_all(b"hello").await?;
/// # std::io::Result::Ok(()) });
/// ```
pub fn sink() -> Sink {
Sink { _private: () }
}
/// Writer for the [`sink()`] function.
#[derive(Debug)]
pub struct Sink {
_private: (),
}
impl AsyncWrite for Sink {
#[inline]
fn poll_write(self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> {
Poll::Ready(Ok(buf.len()))
}
#[inline]
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
#[inline]
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
}
/// Extension trait for [`AsyncBufRead`].
pub trait AsyncBufReadExt: AsyncBufRead {
/// Returns the contents of the internal buffer, filling it with more data if empty.
///
/// If the stream has reached EOF, an empty buffer will be returned.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncBufReadExt, BufReader};
/// use std::pin::Pin;
///
/// # spin_on::spin_on(async {
/// let input: &[u8] = b"hello world";
/// let mut reader = BufReader::with_capacity(5, input);
///
/// assert_eq!(reader.fill_buf().await?, b"hello");
/// reader.consume(2);
/// assert_eq!(reader.fill_buf().await?, b"llo");
/// reader.consume(3);
/// assert_eq!(reader.fill_buf().await?, b" worl");
/// # std::io::Result::Ok(()) });
/// ```
fn fill_buf(&mut self) -> FillBuf<'_, Self>
where
Self: Unpin,
{
FillBuf { reader: Some(self) }
}
/// Consumes `amt` buffered bytes.
///
/// This method does not perform any I/O, it simply consumes some amount of bytes from the
/// internal buffer.
///
/// The `amt` must be <= the number of bytes in the buffer returned by
/// [`fill_buf()`][`AsyncBufReadExt::fill_buf()`].
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncBufReadExt, BufReader};
/// use std::pin::Pin;
///
/// # spin_on::spin_on(async {
/// let input: &[u8] = b"hello";
/// let mut reader = BufReader::with_capacity(4, input);
///
/// assert_eq!(reader.fill_buf().await?, b"hell");
/// reader.consume(2);
/// assert_eq!(reader.fill_buf().await?, b"ll");
/// # std::io::Result::Ok(()) });
/// ```
fn consume(&mut self, amt: usize)
where
Self: Unpin,
{
AsyncBufRead::consume(Pin::new(self), amt);
}
/// Reads all bytes and appends them into `buf` until the delimiter `byte` or EOF is found.
///
/// This method will read bytes from the underlying stream until the delimiter or EOF is
/// found. All bytes up to and including the delimiter (if found) will be appended to `buf`.
///
/// If successful, returns the total number of bytes read.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncBufReadExt, BufReader};
///
/// # spin_on::spin_on(async {
/// let input: &[u8] = b"hello";
/// let mut reader = BufReader::new(input);
///
/// let mut buf = Vec::new();
/// let n = reader.read_until(b'\n', &mut buf).await?;
/// # std::io::Result::Ok(()) });
/// ```
fn read_until<'a>(&'a mut self, byte: u8, buf: &'a mut Vec<u8>) -> ReadUntilFuture<'_, Self>
where
Self: Unpin,
{
ReadUntilFuture {
reader: self,
byte,
buf,
read: 0,
}
}
/// Reads all bytes and appends them into `buf` until a newline (the 0xA byte) or EOF is found.
///
/// This method will read bytes from the underlying stream until the newline delimiter (the
/// 0xA byte) or EOF is found. All bytes up to, and including, the newline delimiter (if found)
/// will be appended to `buf`.
///
/// If successful, returns the total number of bytes read.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncBufReadExt, BufReader};
///
/// # spin_on::spin_on(async {
/// let input: &[u8] = b"hello";
/// let mut reader = BufReader::new(input);
///
/// let mut line = String::new();
/// let n = reader.read_line(&mut line).await?;
/// # std::io::Result::Ok(()) });
/// ```
fn read_line<'a>(&'a mut self, buf: &'a mut String) -> ReadLineFuture<'_, Self>
where
Self: Unpin,
{
ReadLineFuture {
reader: self,
buf,
bytes: Vec::new(),
read: 0,
}
}
/// Returns a stream over the lines of this byte stream.
///
/// The stream returned from this method yields items of type
/// [`io::Result`][`super::io::Result`]`<`[`String`]`>`.
/// Each string returned will *not* have a newline byte (the 0xA byte) or CRLF (0xD, 0xA bytes)
/// at the end.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncBufReadExt, BufReader};
/// use futures_lite::stream::StreamExt;
///
/// # spin_on::spin_on(async {
/// let input: &[u8] = b"hello\nworld\n";
/// let mut reader = BufReader::new(input);
/// let mut lines = reader.lines();
///
/// while let Some(line) = lines.next().await {
/// println!("{}", line?);
/// }
/// # std::io::Result::Ok(()) });
/// ```
fn lines(self) -> Lines<Self>
where
Self: Unpin + Sized,
{
Lines {
reader: self,
buf: String::new(),
bytes: Vec::new(),
read: 0,
}
}
/// Returns a stream over the contents of this reader split on the specified `byte`.
///
/// The stream returned from this method yields items of type
/// [`io::Result`][`super::io::Result`]`<`[`Vec<u8>`][`Vec`]`>`.
/// Each vector returned will *not* have the delimiter byte at the end.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncBufReadExt, Cursor};
/// use futures_lite::stream::StreamExt;
///
/// # spin_on::spin_on(async {
/// let cursor = Cursor::new(b"lorem-ipsum-dolor");
/// let items: Vec<Vec<u8>> = cursor.split(b'-').try_collect().await?;
///
/// assert_eq!(items[0], b"lorem");
/// assert_eq!(items[1], b"ipsum");
/// assert_eq!(items[2], b"dolor");
/// # std::io::Result::Ok(()) });
/// ```
fn split(self, byte: u8) -> Split<Self>
where
Self: Sized,
{
Split {
reader: self,
buf: Vec::new(),
delim: byte,
read: 0,
}
}
}
impl<R: AsyncBufRead + ?Sized> AsyncBufReadExt for R {}
/// Future for the [`AsyncBufReadExt::fill_buf()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct FillBuf<'a, R: ?Sized> {
reader: Option<&'a mut R>,
}
impl<R: ?Sized> Unpin for FillBuf<'_, R> {}
impl<'a, R> Future for FillBuf<'a, R>
where
R: AsyncBufRead + Unpin + ?Sized,
{
type Output = Result<&'a [u8]>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
let reader = this
.reader
.take()
.expect("polled `FillBuf` after completion");
match Pin::new(&mut *reader).poll_fill_buf(cx) {
Poll::Ready(Ok(_)) => match Pin::new(reader).poll_fill_buf(cx) {
Poll::Ready(Ok(slice)) => Poll::Ready(Ok(slice)),
poll => panic!("`poll_fill_buf()` was ready but now it isn't: {:?}", poll),
},
Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
Poll::Pending => {
this.reader = Some(reader);
Poll::Pending
}
}
}
}
/// Future for the [`AsyncBufReadExt::read_until()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadUntilFuture<'a, R: Unpin + ?Sized> {
reader: &'a mut R,
byte: u8,
buf: &'a mut Vec<u8>,
read: usize,
}
impl<R: Unpin + ?Sized> Unpin for ReadUntilFuture<'_, R> {}
impl<R: AsyncBufRead + Unpin + ?Sized> Future for ReadUntilFuture<'_, R> {
type Output = Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self {
reader,
byte,
buf,
read,
} = &mut *self;
read_until_internal(Pin::new(reader), cx, *byte, buf, read)
}
}
fn read_until_internal<R: AsyncBufReadExt + ?Sized>(
mut reader: Pin<&mut R>,
cx: &mut Context<'_>,
byte: u8,
buf: &mut Vec<u8>,
read: &mut usize,
) -> Poll<Result<usize>> {
loop {
let (done, used) = {
let available = ready!(reader.as_mut().poll_fill_buf(cx))?;
if let Some(i) = memchr::memchr(byte, available) {
buf.extend_from_slice(&available[..=i]);
(true, i + 1)
} else {
buf.extend_from_slice(available);
(false, available.len())
}
};
reader.as_mut().consume(used);
*read += used;
if done || used == 0 {
return Poll::Ready(Ok(mem::replace(read, 0)));
}
}
}
/// Future for the [`AsyncBufReadExt::read_line()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadLineFuture<'a, R: Unpin + ?Sized> {
reader: &'a mut R,
buf: &'a mut String,
bytes: Vec<u8>,
read: usize,
}
impl<R: Unpin + ?Sized> Unpin for ReadLineFuture<'_, R> {}
impl<R: AsyncBufRead + Unpin + ?Sized> Future for ReadLineFuture<'_, R> {
type Output = Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self {
reader,
buf,
bytes,
read,
} = &mut *self;
read_line_internal(Pin::new(reader), cx, buf, bytes, read)
}
}
pin_project! {
/// Stream for the [`AsyncBufReadExt::lines()`] method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Lines<R> {
#[pin]
reader: R,
buf: String,
bytes: Vec<u8>,
read: usize,
}
}
impl<R: AsyncBufRead> Stream for Lines<R> {
type Item = Result<String>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
let n = ready!(read_line_internal(
this.reader,
cx,
this.buf,
this.bytes,
this.read
))?;
if n == 0 && this.buf.is_empty() {
return Poll::Ready(None);
}
if this.buf.ends_with('\n') {
this.buf.pop();
if this.buf.ends_with('\r') {
this.buf.pop();
}
}
Poll::Ready(Some(Ok(mem::replace(this.buf, String::new()))))
}
}
fn read_line_internal<R: AsyncBufRead + ?Sized>(
reader: Pin<&mut R>,
cx: &mut Context<'_>,
buf: &mut String,
bytes: &mut Vec<u8>,
read: &mut usize,
) -> Poll<Result<usize>> {
let ret = ready!(read_until_internal(reader, cx, b'\n', bytes, read));
match String::from_utf8(mem::replace(bytes, Vec::new())) {
Ok(s) => {
debug_assert!(buf.is_empty());
debug_assert_eq!(*read, 0);
*buf = s;
Poll::Ready(ret)
}
Err(_) => Poll::Ready(ret.and_then(|_| {
Err(Error::new(
ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
))
})),
}
}
pin_project! {
/// Stream for the [`AsyncBufReadExt::split()`] method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Split<R> {
#[pin]
reader: R,
buf: Vec<u8>,
read: usize,
delim: u8,
}
}
impl<R: AsyncBufRead> Stream for Split<R> {
type Item = Result<Vec<u8>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
let n = ready!(read_until_internal(
this.reader,
cx,
*this.delim,
this.buf,
this.read
))?;
if n == 0 && this.buf.is_empty() {
return Poll::Ready(None);
}
if this.buf[this.buf.len() - 1] == *this.delim {
this.buf.pop();
}
Poll::Ready(Some(Ok(mem::replace(this.buf, vec![]))))
}
}
/// Extension trait for [`AsyncRead`].
pub trait AsyncReadExt: AsyncRead {
/// Reads some bytes from the byte stream.
///
/// On success, returns the total number of bytes read.
///
/// If the return value is `Ok(n)`, then it must be guaranteed that
/// `0 <= n <= buf.len()`. A nonzero `n` value indicates that the buffer has been
/// filled with `n` bytes of data. If `n` is `0`, then it can indicate one of two
/// scenarios:
///
/// 1. This reader has reached its "end of file" and will likely no longer be able to
/// produce bytes. Note that this does not mean that the reader will always no
/// longer be able to produce bytes.
/// 2. The buffer specified was 0 bytes in length.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, BufReader};
///
/// # spin_on::spin_on(async {
/// let input: &[u8] = b"hello";
/// let mut reader = BufReader::new(input);
///
/// let mut buf = vec![0; 1024];
/// let n = reader.read(&mut buf).await?;
/// # std::io::Result::Ok(()) });
/// ```
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>
where
Self: Unpin,
{
ReadFuture { reader: self, buf }
}
/// Like [`read()`][`AsyncReadExt::read()`], except it reads into a slice of buffers.
///
/// Data is copied to fill each buffer in order, with the final buffer possibly being
/// only partially filled. This method must behave same as a single call to
/// [`read()`][`AsyncReadExt::read()`] with the buffers concatenated would.
fn read_vectored<'a>(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>],
) -> ReadVectoredFuture<'a, Self>
where
Self: Unpin,
{
ReadVectoredFuture { reader: self, bufs }
}
/// Reads the entire contents and appends them to a [`Vec`].
///
/// On success, returns the total number of bytes read.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// # spin_on::spin_on(async {
/// let mut reader = Cursor::new(vec![1, 2, 3]);
/// let mut contents = Vec::new();
///
/// let n = reader.read_to_end(&mut contents).await?;
/// assert_eq!(n, 3);
/// assert_eq!(contents, [1, 2, 3]);
/// # std::io::Result::Ok(()) });
/// ```
fn read_to_end<'a>(&'a mut self, buf: &'a mut Vec<u8>) -> ReadToEndFuture<'a, Self>
where
Self: Unpin,
{
let start_len = buf.len();
ReadToEndFuture {
reader: self,
buf,
start_len,
}
}
/// Reads the entire contents and appends them to a [`String`].
///
/// On success, returns the total number of bytes read.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// # spin_on::spin_on(async {
/// let mut reader = Cursor::new(&b"hello");
/// let mut contents = String::new();
///
/// let n = reader.read_to_string(&mut contents).await?;
/// assert_eq!(n, 5);
/// assert_eq!(contents, "hello");
/// # std::io::Result::Ok(()) });
/// ```
fn read_to_string<'a>(&'a mut self, buf: &'a mut String) -> ReadToStringFuture<'a, Self>
where
Self: Unpin,
{
ReadToStringFuture {
reader: self,
buf,
bytes: Vec::new(),
start_len: 0,
}
}
/// Reads the exact number of bytes required to fill `buf`.
///
/// On success, returns the total number of bytes read.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// # spin_on::spin_on(async {
/// let mut reader = Cursor::new(&b"hello");
/// let mut contents = vec![0; 3];
///
/// reader.read_exact(&mut contents).await?;
/// assert_eq!(contents, b"hel");
/// # std::io::Result::Ok(()) });
/// ```
fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>
where
Self: Unpin,
{
ReadExactFuture { reader: self, buf }
}
/// Creates an adapter which will read at most `limit` bytes from it.
///
/// This method returns a new instance of [`AsyncRead`] which will read at most
/// `limit` bytes, after which it will always return `Ok(0)` indicating EOF.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// # spin_on::spin_on(async {
/// let mut reader = Cursor::new(&b"hello");
/// let mut contents = String::new();
///
/// let n = reader.take(3).read_to_string(&mut contents).await?;
/// assert_eq!(n, 3);
/// assert_eq!(contents, "hel");
/// # std::io::Result::Ok(()) });
/// ```
fn take(self, limit: u64) -> Take<Self>
where
Self: Sized,
{
Take { inner: self, limit }
}
/// Converts this [`AsyncRead`] into a [`Stream`] of bytes.
///
/// The returned type implements [`Stream`] where `Item` is `io::Result<u8>`.
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
/// use futures_lite::stream::StreamExt;
///
/// # spin_on::spin_on(async {
/// let reader = Cursor::new(&b"hello");
/// let mut bytes = reader.bytes();
///
/// while let Some(byte) = bytes.next().await {
/// println!("byte: {}", byte?);
/// }
/// # std::io::Result::Ok(()) });
/// ```
fn bytes(self) -> Bytes<Self>
where
Self: Sized,
{
Bytes { inner: self }
}
/// Creates an adapter which will chain this stream with another.
///
/// The returned [`AsyncRead`] instance will first read all bytes from this reader
/// until EOF is found, and then continue with `next`.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// # spin_on::spin_on(async {
/// let r1 = Cursor::new(&b"hello");
/// let r2 = Cursor::new(&b"world");
/// let mut reader = r1.chain(r2);
///
/// let mut contents = String::new();
/// reader.read_to_string(&mut contents).await?;
/// assert_eq!(contents, "helloworld");
/// # std::io::Result::Ok(()) });
/// ```
fn chain<R: AsyncRead>(self, next: R) -> Chain<Self, R>
where
Self: Sized,
{
Chain {
first: self,
second: next,
done_first: false,
}
}
/// Boxes the reader and changes its type to `dyn AsyncRead + Send + 'a`.
///
/// # Examples
///
/// ```
/// use futures_lite::io::AsyncReadExt;
///
/// let reader = [1, 2, 3].boxed_reader();
/// ```
#[cfg(feature = "alloc")]
fn boxed_reader<'a>(self) -> Pin<Box<dyn AsyncRead + Send + 'a>>
where
Self: Sized + Send + 'a,
{
Box::pin(self)
}
}
impl<R: AsyncRead + ?Sized> AsyncReadExt for R {}
/// Future for the [`AsyncReadExt::read()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadFuture<'a, R: Unpin + ?Sized> {
reader: &'a mut R,
buf: &'a mut [u8],
}
impl<R: Unpin + ?Sized> Unpin for ReadFuture<'_, R> {}
impl<R: AsyncRead + Unpin + ?Sized> Future for ReadFuture<'_, R> {
type Output = Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self { reader, buf } = &mut *self;
Pin::new(reader).poll_read(cx, buf)
}
}
/// Future for the [`AsyncReadExt::read_vectored()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadVectoredFuture<'a, R: Unpin + ?Sized> {
reader: &'a mut R,
bufs: &'a mut [IoSliceMut<'a>],
}
impl<R: Unpin + ?Sized> Unpin for ReadVectoredFuture<'_, R> {}
impl<R: AsyncRead + Unpin + ?Sized> Future for ReadVectoredFuture<'_, R> {
type Output = Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self { reader, bufs } = &mut *self;
Pin::new(reader).poll_read_vectored(cx, bufs)
}
}
/// Future for the [`AsyncReadExt::read_to_end()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadToEndFuture<'a, R: Unpin + ?Sized> {
reader: &'a mut R,
buf: &'a mut Vec<u8>,
start_len: usize,
}
impl<R: Unpin + ?Sized> Unpin for ReadToEndFuture<'_, R> {}
impl<R: AsyncRead + Unpin + ?Sized> Future for ReadToEndFuture<'_, R> {
type Output = Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self {
reader,
buf,
start_len,
} = &mut *self;
read_to_end_internal(Pin::new(reader), cx, buf, *start_len)
}
}
/// Future for the [`AsyncReadExt::read_to_string()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadToStringFuture<'a, R: Unpin + ?Sized> {
reader: &'a mut R,
buf: &'a mut String,
bytes: Vec<u8>,
start_len: usize,
}
impl<R: Unpin + ?Sized> Unpin for ReadToStringFuture<'_, R> {}
impl<R: AsyncRead + Unpin + ?Sized> Future for ReadToStringFuture<'_, R> {
type Output = Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self {
reader,
buf,
bytes,
start_len,
} = &mut *self;
let reader = Pin::new(reader);
let ret = ready!(read_to_end_internal(reader, cx, bytes, *start_len));
match String::from_utf8(mem::replace(bytes, Vec::new())) {
Ok(s) => {
debug_assert!(buf.is_empty());
**buf = s;
Poll::Ready(ret)
}
Err(_) => Poll::Ready(ret.and_then(|_| {
Err(Error::new(
ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
))
})),
}
}
}
// This uses an adaptive system to extend the vector when it fills. We want to
// avoid paying to allocate and zero a huge chunk of memory if the reader only
// has 4 bytes while still making large reads if the reader does have a ton
// of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
// time is 4,500 times (!) slower than this if the reader has a very small
// amount of data to return.
//
// Because we're extending the buffer with uninitialized data for trusted
// readers, we need to make sure to truncate that if any of this panics.
fn read_to_end_internal<R: AsyncRead + ?Sized>(
mut rd: Pin<&mut R>,
cx: &mut Context<'_>,
buf: &mut Vec<u8>,
start_len: usize,
) -> Poll<Result<usize>> {
struct Guard<'a> {
buf: &'a mut Vec<u8>,
len: usize,
}
impl Drop for Guard<'_> {
fn drop(&mut self) {
self.buf.resize(self.len, 0);
}
}
let mut g = Guard {
len: buf.len(),
buf,
};
let ret;
loop {
if g.len == g.buf.len() {
g.buf.reserve(32);
let capacity = g.buf.capacity();
g.buf.resize(capacity, 0);
}
match ready!(rd.as_mut().poll_read(cx, &mut g.buf[g.len..])) {
Ok(0) => {
ret = Poll::Ready(Ok(g.len - start_len));
break;
}
Ok(n) => g.len += n,
Err(e) => {
ret = Poll::Ready(Err(e));
break;
}
}
}
ret
}
/// Future for the [`AsyncReadExt::read_exact()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadExactFuture<'a, R: Unpin + ?Sized> {
reader: &'a mut R,
buf: &'a mut [u8],
}
impl<R: Unpin + ?Sized> Unpin for ReadExactFuture<'_, R> {}
impl<R: AsyncRead + Unpin + ?Sized> Future for ReadExactFuture<'_, R> {
type Output = Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self { reader, buf } = &mut *self;
while !buf.is_empty() {
let n = ready!(Pin::new(&mut *reader).poll_read(cx, buf))?;
let (_, rest) = mem::replace(buf, &mut []).split_at_mut(n);
*buf = rest;
if n == 0 {
return Poll::Ready(Err(ErrorKind::UnexpectedEof.into()));
}
}
Poll::Ready(Ok(()))
}
}
pin_project! {
/// Reader for the [`AsyncReadExt::take()`] method.
#[derive(Debug)]
pub struct Take<R> {
#[pin]
inner: R,
limit: u64,
}
}
impl<R> Take<R> {
/// Returns the number of bytes before this adapter will return EOF.
///
/// Note that EOF may be reached sooner if the underlying reader is shorter than the limit.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// let reader = Cursor::new("hello");
///
/// let reader = reader.take(3);
/// assert_eq!(reader.limit(), 3);
/// ```
pub fn limit(&self) -> u64 {
self.limit
}
/// Puts a limit on the number of bytes.
///
/// Changing the limit is equivalent to creating a new adapter with [`AsyncReadExt::take()`].
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// let reader = Cursor::new("hello");
///
/// let mut reader = reader.take(10);
/// assert_eq!(reader.limit(), 10);
///
/// reader.set_limit(3);
/// assert_eq!(reader.limit(), 3);
/// ```
pub fn set_limit(&mut self, limit: u64) {
self.limit = limit;
}
/// Gets a reference to the underlying reader.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// let reader = Cursor::new("hello");
///
/// let reader = reader.take(3);
/// let r = reader.get_ref();
/// ```
pub fn get_ref(&self) -> &R {
&self.inner
}
/// Gets a mutable reference to the underlying reader.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// let reader = Cursor::new("hello");
///
/// let mut reader = reader.take(3);
/// let r = reader.get_mut();
/// ```
pub fn get_mut(&mut self) -> &mut R {
&mut self.inner
}
/// Unwraps the adapter, returning the underlying reader.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// let reader = Cursor::new("hello");
///
/// let reader = reader.take(3);
/// let reader = reader.into_inner();
/// ```
pub fn into_inner(self) -> R {
self.inner
}
}
impl<R: AsyncRead> AsyncRead for Take<R> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
let this = self.project();
take_read_internal(this.inner, cx, buf, this.limit)
}
}
fn take_read_internal<R: AsyncRead + ?Sized>(
mut rd: Pin<&mut R>,
cx: &mut Context<'_>,
buf: &mut [u8],
limit: &mut u64,
) -> Poll<Result<usize>> {
// Don't call into inner reader at all at EOF because it may still block
if *limit == 0 {
return Poll::Ready(Ok(0));
}
let max = cmp::min(buf.len() as u64, *limit) as usize;
match ready!(rd.as_mut().poll_read(cx, &mut buf[..max])) {
Ok(n) => {
*limit -= n as u64;
Poll::Ready(Ok(n))
}
Err(e) => Poll::Ready(Err(e)),
}
}
impl<R: AsyncBufRead> AsyncBufRead for Take<R> {
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
let this = self.project();
if *this.limit == 0 {
return Poll::Ready(Ok(&[]));
}
match ready!(this.inner.poll_fill_buf(cx)) {
Ok(buf) => {
let cap = cmp::min(buf.len() as u64, *this.limit) as usize;
Poll::Ready(Ok(&buf[..cap]))
}
Err(e) => Poll::Ready(Err(e)),
}
}
fn consume(self: Pin<&mut Self>, amt: usize) {
let this = self.project();
// Don't let callers reset the limit by passing an overlarge value
let amt = cmp::min(amt as u64, *this.limit) as usize;
*this.limit -= amt as u64;
this.inner.consume(amt);
}
}
pin_project! {
/// Reader for the [`AsyncReadExt::bytes()`] method.
#[derive(Debug)]
pub struct Bytes<R> {
#[pin]
inner: R,
}
}
impl<R: AsyncRead + Unpin> Stream for Bytes<R> {
type Item = Result<u8>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut byte = 0;
let rd = Pin::new(&mut self.inner);
match ready!(rd.poll_read(cx, std::slice::from_mut(&mut byte))) {
Ok(0) => Poll::Ready(None),
Ok(..) => Poll::Ready(Some(Ok(byte))),
Err(ref e) if e.kind() == ErrorKind::Interrupted => Poll::Pending,
Err(e) => Poll::Ready(Some(Err(e))),
}
}
}
impl<R: AsyncRead> AsyncRead for Bytes<R> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
self.project().inner.poll_read(cx, buf)
}
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<Result<usize>> {
self.project().inner.poll_read_vectored(cx, bufs)
}
}
pin_project! {
/// Reader for the [`AsyncReadExt::chain()`] method.
pub struct Chain<R1, R2> {
#[pin]
first: R1,
#[pin]
second: R2,
done_first: bool,
}
}
impl<R1, R2> Chain<R1, R2> {
/// Gets references to the underlying readers.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// let r1 = Cursor::new(b"hello");
/// let r2 = Cursor::new(b"world");
///
/// let reader = r1.chain(r2);
/// let (r1, r2) = reader.get_ref();
/// ```
pub fn get_ref(&self) -> (&R1, &R2) {
(&self.first, &self.second)
}
/// Gets mutable references to the underlying readers.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// let r1 = Cursor::new(b"hello");
/// let r2 = Cursor::new(b"world");
///
/// let mut reader = r1.chain(r2);
/// let (r1, r2) = reader.get_mut();
/// ```
pub fn get_mut(&mut self) -> (&mut R1, &mut R2) {
(&mut self.first, &mut self.second)
}
/// Unwraps the adapter, returning the underlying readers.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncReadExt, Cursor};
///
/// let r1 = Cursor::new(b"hello");
/// let r2 = Cursor::new(b"world");
///
/// let reader = r1.chain(r2);
/// let (r1, r2) = reader.into_inner();
/// ```
pub fn into_inner(self) -> (R1, R2) {
(self.first, self.second)
}
}
impl<R1: fmt::Debug, R2: fmt::Debug> fmt::Debug for Chain<R1, R2> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Chain")
.field("r1", &self.first)
.field("r2", &self.second)
.finish()
}
}
impl<R1: AsyncRead, R2: AsyncRead> AsyncRead for Chain<R1, R2> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
let this = self.project();
if !*this.done_first {
match ready!(this.first.poll_read(cx, buf)) {
Ok(0) if !buf.is_empty() => *this.done_first = true,
Ok(n) => return Poll::Ready(Ok(n)),
Err(err) => return Poll::Ready(Err(err)),
}
}
this.second.poll_read(cx, buf)
}
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<Result<usize>> {
let this = self.project();
if !*this.done_first {
match ready!(this.first.poll_read_vectored(cx, bufs)) {
Ok(0) if !bufs.is_empty() => *this.done_first = true,
Ok(n) => return Poll::Ready(Ok(n)),
Err(err) => return Poll::Ready(Err(err)),
}
}
this.second.poll_read_vectored(cx, bufs)
}
}
impl<R1: AsyncBufRead, R2: AsyncBufRead> AsyncBufRead for Chain<R1, R2> {
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
let this = self.project();
if !*this.done_first {
match ready!(this.first.poll_fill_buf(cx)) {
Ok(buf) if buf.is_empty() => {
*this.done_first = true;
}
Ok(buf) => return Poll::Ready(Ok(buf)),
Err(err) => return Poll::Ready(Err(err)),
}
}
this.second.poll_fill_buf(cx)
}
fn consume(self: Pin<&mut Self>, amt: usize) {
let this = self.project();
if !*this.done_first {
this.first.consume(amt)
} else {
this.second.consume(amt)
}
}
}
/// Extension trait for [`AsyncSeek`].
pub trait AsyncSeekExt: AsyncSeek {
/// Seeks to a new position in a byte stream.
///
/// Returns the new position in the byte stream.
///
/// A seek beyond the end of stream is allowed, but behavior is defined by the implementation.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncSeekExt, Cursor, SeekFrom};
///
/// # spin_on::spin_on(async {
/// let mut cursor = Cursor::new("hello");
///
/// // Move the cursor to the end.
/// cursor.seek(SeekFrom::End(0)).await?;
///
/// // Check the current position.
/// assert_eq!(cursor.seek(SeekFrom::Current(0)).await?, 5);
/// # std::io::Result::Ok(()) });
/// ```
fn seek(&mut self, pos: SeekFrom) -> SeekFuture<'_, Self>
where
Self: Unpin,
{
SeekFuture { seeker: self, pos }
}
}
impl<S: AsyncSeek + ?Sized> AsyncSeekExt for S {}
/// Future for the [`AsyncSeekExt::seek()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct SeekFuture<'a, S: Unpin + ?Sized> {
seeker: &'a mut S,
pos: SeekFrom,
}
impl<S: Unpin + ?Sized> Unpin for SeekFuture<'_, S> {}
impl<S: AsyncSeek + Unpin + ?Sized> Future for SeekFuture<'_, S> {
type Output = Result<u64>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let pos = self.pos;
Pin::new(&mut *self.seeker).poll_seek(cx, pos)
}
}
/// Extension trait for [`AsyncWrite`].
pub trait AsyncWriteExt: AsyncWrite {
/// Writes some bytes into the byte stream.
///
/// Returns the number of bytes written from the start of the buffer.
///
/// If the return value is `Ok(n)` then it must be guaranteed that
/// `0 <= n <= buf.len()`. A return value of `0` typically means that the underlying
/// object is no longer able to accept bytes and will likely not be able to in the
/// future as well, or that the provided buffer is empty.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncWriteExt, BufWriter};
///
/// # spin_on::spin_on(async {
/// let mut output = Vec::new();
/// let mut writer = BufWriter::new(&mut output);
///
/// let n = writer.write(b"hello").await?;
/// # std::io::Result::Ok(()) });
/// ```
fn write<'a>(&'a mut self, buf: &'a [u8]) -> WriteFuture<'a, Self>
where
Self: Unpin,
{
WriteFuture { writer: self, buf }
}
/// Like [`write()`][`AsyncWriteExt::write()`], except that it writes a slice of buffers.
///
/// Data is copied from each buffer in order, with the final buffer possibly being only
/// partially consumed. This method must behave same as a call to
/// [`write()`][`AsyncWriteExt::write()`] with the buffers concatenated would.
fn write_vectored<'a>(&'a mut self, bufs: &'a [IoSlice<'a>]) -> WriteVectoredFuture<'a, Self>
where
Self: Unpin,
{
WriteVectoredFuture { writer: self, bufs }
}
/// Writes an entire buffer into the byte stream.
///
/// This method will keep calling [`write()`][`AsyncWriteExt::write()`] until there is no more
/// data to be written or an error occurs. It will not return before the entire buffer is
/// successfully written or an error occurs.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncWriteExt, BufWriter};
///
/// # spin_on::spin_on(async {
/// let mut output = Vec::new();
/// let mut writer = BufWriter::new(&mut output);
///
/// let n = writer.write_all(b"hello").await?;
/// # std::io::Result::Ok(()) });
/// ```
fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> WriteAllFuture<'a, Self>
where
Self: Unpin,
{
WriteAllFuture { writer: self, buf }
}
/// Flushes the stream to ensure that all buffered contents reach their destination.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncWriteExt, BufWriter};
///
/// # spin_on::spin_on(async {
/// let mut output = Vec::new();
/// let mut writer = BufWriter::new(&mut output);
///
/// writer.write_all(b"hello").await?;
/// writer.flush().await?;
/// # std::io::Result::Ok(()) });
/// ```
fn flush(&mut self) -> FlushFuture<'_, Self>
where
Self: Unpin,
{
FlushFuture { writer: self }
}
/// Closes the writer.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{AsyncWriteExt, BufWriter};
///
/// # spin_on::spin_on(async {
/// let mut output = Vec::new();
/// let mut writer = BufWriter::new(&mut output);
///
/// writer.close().await?;
/// # std::io::Result::Ok(()) });
/// ```
fn close(&mut self) -> CloseFuture<'_, Self>
where
Self: Unpin,
{
CloseFuture { writer: self }
}
/// Boxes the writer and changes its type to `dyn AsyncWrite + Send + 'a`.
///
/// # Examples
///
/// ```
/// use futures_lite::io::AsyncWriteExt;
///
/// let writer = Vec::<u8>::new().boxed_writer();
/// ```
#[cfg(feature = "alloc")]
fn boxed_writer<'a>(self) -> Pin<Box<dyn AsyncWrite + Send + 'a>>
where
Self: Sized + Send + 'a,
{
Box::pin(self)
}
}
impl<W: AsyncWrite + ?Sized> AsyncWriteExt for W {}
/// Future for the [`AsyncWriteExt::write()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct WriteFuture<'a, W: Unpin + ?Sized> {
writer: &'a mut W,
buf: &'a [u8],
}
impl<W: Unpin + ?Sized> Unpin for WriteFuture<'_, W> {}
impl<W: AsyncWrite + Unpin + ?Sized> Future for WriteFuture<'_, W> {
type Output = Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let buf = self.buf;
Pin::new(&mut *self.writer).poll_write(cx, buf)
}
}
/// Future for the [`AsyncWriteExt::write_vectored()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct WriteVectoredFuture<'a, W: Unpin + ?Sized> {
writer: &'a mut W,
bufs: &'a [IoSlice<'a>],
}
impl<W: Unpin + ?Sized> Unpin for WriteVectoredFuture<'_, W> {}
impl<W: AsyncWrite + Unpin + ?Sized> Future for WriteVectoredFuture<'_, W> {
type Output = Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let bufs = self.bufs;
Pin::new(&mut *self.writer).poll_write_vectored(cx, bufs)
}
}
/// Future for the [`AsyncWriteExt::write_all()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct WriteAllFuture<'a, W: Unpin + ?Sized> {
writer: &'a mut W,
buf: &'a [u8],
}
impl<W: Unpin + ?Sized> Unpin for WriteAllFuture<'_, W> {}
impl<W: AsyncWrite + Unpin + ?Sized> Future for WriteAllFuture<'_, W> {
type Output = Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self { writer, buf } = &mut *self;
while !buf.is_empty() {
let n = ready!(Pin::new(&mut **writer).poll_write(cx, buf))?;
let (_, rest) = mem::replace(buf, &[]).split_at(n);
*buf = rest;
if n == 0 {
return Poll::Ready(Err(ErrorKind::WriteZero.into()));
}
}
Poll::Ready(Ok(()))
}
}
/// Future for the [`AsyncWriteExt::flush()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct FlushFuture<'a, W: Unpin + ?Sized> {
writer: &'a mut W,
}
impl<W: Unpin + ?Sized> Unpin for FlushFuture<'_, W> {}
impl<W: AsyncWrite + Unpin + ?Sized> Future for FlushFuture<'_, W> {
type Output = Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut *self.writer).poll_flush(cx)
}
}
/// Future for the [`AsyncWriteExt::close()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct CloseFuture<'a, W: Unpin + ?Sized> {
writer: &'a mut W,
}
impl<W: Unpin + ?Sized> Unpin for CloseFuture<'_, W> {}
impl<W: AsyncWrite + Unpin + ?Sized> Future for CloseFuture<'_, W> {
type Output = Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut *self.writer).poll_close(cx)
}
}
/// Type alias for `Pin<Box<dyn AsyncRead + Send + 'static>>`.
///
/// # Examples
///
/// ```
/// use futures_lite::io::AsyncReadExt;
///
/// let reader = [1, 2, 3].boxed_reader();
/// ```
#[cfg(feature = "alloc")]
pub type BoxedReader = Pin<Box<dyn AsyncRead + Send + 'static>>;
/// Type alias for `Pin<Box<dyn AsyncWrite + Send + 'static>>`.
///
/// # Examples
///
/// ```
/// use futures_lite::io::AsyncWriteExt;
///
/// let writer = Vec::<u8>::new().boxed_writer();
/// ```
#[cfg(feature = "alloc")]
pub type BoxedWriter = Pin<Box<dyn AsyncWrite + Send + 'static>>;
/// Splits a stream into [`AsyncRead`] and [`AsyncWrite`] halves.
///
/// # Examples
///
/// ```
/// use futures_lite::io::{self, Cursor};
///
/// # spin_on::spin_on(async {
/// let stream = Cursor::new(vec![]);
/// let (mut reader, mut writer) = io::split(stream);
/// # std::io::Result::Ok(()) });
/// ```
pub fn split<T>(stream: T) -> (ReadHalf<T>, WriteHalf<T>)
where
T: AsyncRead + AsyncWrite + Unpin,
{
let inner = Arc::new(Mutex::new(stream));
(ReadHalf(inner.clone()), WriteHalf(inner))
}
/// The read half returned by [`split()`].
#[derive(Debug)]
pub struct ReadHalf<T>(Arc<Mutex<T>>);
/// The write half returned by [`split()`].
#[derive(Debug)]
pub struct WriteHalf<T>(Arc<Mutex<T>>);
impl<T: AsyncRead + Unpin> AsyncRead for ReadHalf<T> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
let mut inner = self.0.lock().unwrap();
Pin::new(&mut *inner).poll_read(cx, buf)
}
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<Result<usize>> {
let mut inner = self.0.lock().unwrap();
Pin::new(&mut *inner).poll_read_vectored(cx, bufs)
}
}
impl<T: AsyncWrite + Unpin> AsyncWrite for WriteHalf<T> {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> {
let mut inner = self.0.lock().unwrap();
Pin::new(&mut *inner).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
let mut inner = self.0.lock().unwrap();
Pin::new(&mut *inner).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
let mut inner = self.0.lock().unwrap();
Pin::new(&mut *inner).poll_close(cx)
}
}