rune/modules/iter.rs
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
//! Iterators.
use crate as rune;
use crate::alloc;
use crate::alloc::prelude::*;
use crate::modules::collections::VecDeque;
#[cfg(feature = "alloc")]
use crate::modules::collections::{HashMap, HashSet};
use crate::runtime::range::RangeIter;
use crate::runtime::{
FromValue, Function, Inline, InstAddress, Object, Output, OwnedTuple, Protocol, Repr, TypeHash,
Value, Vec, VmErrorKind, VmResult,
};
use crate::shared::Caller;
use crate::{Any, ContextError, Module, Params};
/// Rune support for iterators.
///
/// This module contains types and methods for working with iterators in Rune.
#[rune::module(::std::iter)]
pub fn module() -> Result<Module, ContextError> {
let mut m = Module::from_meta(self::module_meta)?;
m.ty::<Rev>()?;
m.function_meta(Rev::next__meta)?;
m.function_meta(Rev::next_back__meta)?;
m.function_meta(Rev::size_hint__meta)?;
m.function_meta(Rev::len__meta)?;
m.implement_trait::<Rev>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Rev>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.implement_trait::<Rev>(rune::item!(::std::iter::ExactSizeIterator))?;
m.ty::<Chain>()?;
m.function_meta(Chain::next__meta)?;
m.function_meta(Chain::next_back__meta)?;
m.function_meta(Chain::size_hint__meta)?;
m.function_meta(Chain::len__meta)?;
m.implement_trait::<Chain>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Chain>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.implement_trait::<Chain>(rune::item!(::std::iter::ExactSizeIterator))?;
m.ty::<Enumerate>()?;
m.function_meta(Enumerate::next__meta)?;
m.function_meta(Enumerate::next_back__meta)?;
m.function_meta(Enumerate::size_hint__meta)?;
m.function_meta(Enumerate::len__meta)?;
m.implement_trait::<Enumerate>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Enumerate>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.implement_trait::<Enumerate>(rune::item!(::std::iter::ExactSizeIterator))?;
m.ty::<Filter>()?;
m.function_meta(Filter::next__meta)?;
m.function_meta(Filter::next_back__meta)?;
m.function_meta(Filter::size_hint__meta)?;
m.implement_trait::<Filter>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Filter>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.ty::<Map>()?;
m.function_meta(Map::next__meta)?;
m.function_meta(Map::next_back__meta)?;
m.function_meta(Map::size_hint__meta)?;
m.function_meta(Map::len__meta)?;
m.implement_trait::<Map>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Map>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.implement_trait::<Map>(rune::item!(::std::iter::ExactSizeIterator))?;
m.ty::<FilterMap>()?;
m.function_meta(FilterMap::next__meta)?;
m.function_meta(FilterMap::next_back__meta)?;
m.implement_trait::<FilterMap>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<FilterMap>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.ty::<FlatMap>()?;
m.function_meta(FlatMap::next__meta)?;
m.function_meta(FlatMap::next_back__meta)?;
m.function_meta(FlatMap::size_hint__meta)?;
m.implement_trait::<FlatMap>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<FlatMap>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.ty::<Peekable>()?;
m.function_meta(Peekable::next__meta)?;
m.function_meta(Peekable::next_back__meta)?;
m.function_meta(Peekable::size_hint__meta)?;
m.function_meta(Peekable::len__meta)?;
m.implement_trait::<Peekable>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Peekable>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.implement_trait::<Peekable>(rune::item!(::std::iter::ExactSizeIterator))?;
m.function_meta(Peekable::peek__meta)?;
m.ty::<Skip>()?;
m.function_meta(Skip::next__meta)?;
m.function_meta(Skip::next_back__meta)?;
m.function_meta(Skip::size_hint__meta)?;
m.function_meta(Skip::len__meta)?;
m.implement_trait::<Skip>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Skip>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.implement_trait::<Skip>(rune::item!(::std::iter::ExactSizeIterator))?;
m.ty::<Take>()?;
m.function_meta(Take::next__meta)?;
m.function_meta(Take::next_back__meta)?;
m.function_meta(Take::size_hint__meta)?;
m.function_meta(Take::len__meta)?;
m.implement_trait::<Take>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Take>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.implement_trait::<Take>(rune::item!(::std::iter::ExactSizeIterator))?;
{
let mut t = m.define_trait(["ExactSizeIterator"])?;
t.docs(docstring! {
/// An iterator that knows its exact length.
///
/// Many [`Iterator`]s don't know how many times they will iterate, but some do.
/// If an iterator knows how many times it can iterate, providing access to
/// that information can be useful. For example, if you want to iterate
/// backwards, a good start is to know where the end is.
///
/// When implementing an `ExactSizeIterator`, you must also implement
/// [`Iterator`]. When doing so, the implementation of [`Iterator::size_hint`]
/// *must* return the exact size of the iterator.
///
/// The [`len`] method has a default implementation, so you usually shouldn't
/// implement it. However, you may be able to provide a more performant
/// implementation than the default, so overriding it in this case makes sense.
///
/// Note that this trait is a safe trait and as such does *not* and *cannot*
/// guarantee that the returned length is correct. This means that `unsafe`
/// code **must not** rely on the correctness of [`Iterator::size_hint`]. The
/// unstable and unsafe [`TrustedLen`](super::marker::TrustedLen) trait gives
/// this additional guarantee.
///
/// [`len`]: ExactSizeIterator::len
///
/// # When *shouldn't* an adapter be `ExactSizeIterator`?
///
/// If an adapter makes an iterator *longer*, then it's usually incorrect for
/// that adapter to implement `ExactSizeIterator`. The inner exact-sized
/// iterator might already be `usize::MAX`-long, and thus the length of the
/// longer adapted iterator would no longer be exactly representable in `usize`.
///
/// This is why [`Chain<A, B>`](crate::iter::Chain) isn't `ExactSizeIterator`,
/// even when `A` and `B` are both `ExactSizeIterator`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// // a finite range knows exactly how many times it will iterate
/// let five = (0..5).iter();
///
/// assert_eq!(five.len(), 5);
/// ```
})?;
t.handler(|cx| {
_ = cx.find(&Protocol::LEN)?;
Ok(())
})?;
t.function("len")?
.argument_types::<(Value,)>()?
.return_type::<usize>()?
.docs(docstring! {
/// Returns the exact remaining length of the iterator.
///
/// The implementation ensures that the iterator will return
/// exactly `len()` more times a [`Some(T)`] value, before
/// returning [`None`]. This method has a default
/// implementation, so you usually should not implement it
/// directly. However, if you can provide a more efficient
/// implementation, you can do so. See the [trait-level] docs
/// for an example.
///
/// This function has the same safety guarantees as the
/// [`Iterator::size_hint`] function.
///
/// [trait-level]: ExactSizeIterator
/// [`Some(T)`]: Some
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// // a finite range knows exactly how many times it will iterate
/// let range = (0..5).iter();
///
/// assert_eq!(range.len(), 5);
/// let _ = range.next();
/// assert_eq!(range.len(), 4);
/// ```
})?;
}
{
let mut t = m.define_trait(["Iterator"])?;
t.docs(docstring! {
/// A trait for dealing with iterators.
})?;
t.handler(|cx| {
let next = cx.find(&Protocol::NEXT)?;
let next = Caller::<(Value,), 1, Option<Value>>::new(next);
let size_hint =
cx.find_or_define(&Protocol::SIZE_HINT, |_: Value| (0usize, None::<usize>))?;
let size_hint = Caller::<(&Value,), 1, (usize, Option<usize>)>::new(size_hint);
cx.find_or_define(&Protocol::NTH, {
let next = next.clone();
move |iter: Value, mut n: usize| loop {
let Some(value) = vm_try!(next.call((iter.clone(),))) else {
break VmResult::Ok(None);
};
if n == 0 {
break VmResult::Ok(Some(value));
}
n -= 1;
}
})?;
cx.function(&Protocol::INTO_ITER, |value: Value| value)?;
cx.function("into_iter", |value: Value| value)?;
{
let next = next.clone();
cx.function("count", move |iter: Value| {
let mut n = 0usize;
loop {
if vm_try!(next.call((iter.clone(),))).is_none() {
break VmResult::Ok(n);
};
n += 1;
}
})?;
}
{
let next = next.clone();
cx.function("fold", move |iter: Value, mut acc: Value, f: Function| {
loop {
let Some(value) = vm_try!(next.call((iter.clone(),))) else {
break VmResult::Ok(acc);
};
acc = vm_try!(f.call((acc, value)));
}
})?;
}
{
let next = next.clone();
cx.function("reduce", move |iter: Value, f: Function| {
let Some(mut acc) = vm_try!(next.call((iter.clone(),))) else {
return VmResult::Ok(None);
};
while let Some(value) = vm_try!(next.call((iter.clone(),))) {
acc = vm_try!(f.call((acc, value)));
}
VmResult::Ok(Some(acc))
})?;
}
{
let next = next.clone();
cx.function("find", move |iter: Value, f: Function| loop {
let Some(value) = vm_try!(next.call((iter.clone(),))) else {
break VmResult::Ok(None);
};
if vm_try!(f.call::<bool>((value.clone(),))) {
break VmResult::Ok(Some(value));
}
})?;
}
{
let next = next.clone();
cx.function("any", move |iter: Value, f: Function| loop {
let Some(value) = vm_try!(next.call((iter.clone(),))) else {
break VmResult::Ok(false);
};
if vm_try!(f.call::<bool>((value.clone(),))) {
break VmResult::Ok(true);
}
})?;
}
{
let next = next.clone();
cx.function("all", move |iter: Value, f: Function| loop {
let Some(value) = vm_try!(next.call((iter.clone(),))) else {
break VmResult::Ok(true);
};
if !vm_try!(f.call::<bool>((value.clone(),))) {
break VmResult::Ok(false);
}
})?;
}
{
cx.function("chain", |a: Value, b: Value| {
let b = vm_try!(b.protocol_into_iter());
VmResult::Ok(Chain {
a: Some(a.clone()),
b: Some(b.clone()),
})
})?;
cx.function("enumerate", move |iter: Value| Enumerate { iter, count: 0 })?;
cx.function("filter", move |iter: Value, f: Function| Filter { iter, f })?;
cx.function("map", move |iter: Value, f: Function| Map {
iter: Some(iter),
f,
})?;
cx.function("filter_map", move |iter: Value, f: Function| FilterMap {
iter: Some(iter),
f,
})?;
cx.function("flat_map", move |iter: Value, f: Function| FlatMap {
map: Map {
iter: Some(iter),
f,
},
frontiter: None,
backiter: None,
})?;
cx.function("peekable", move |iter: Value| Peekable {
iter,
peeked: None,
})?;
cx.function("skip", move |iter: Value, n: usize| Skip { iter, n })?;
cx.function("take", move |iter: Value, n: usize| Take { iter, n })?;
}
{
let next = next.clone();
let size_hint = size_hint.clone();
cx.function(Params::new("collect", [Vec::HASH]), move |iter: Value| {
let (cap, _) = vm_try!(size_hint.call((&iter,)));
let mut vec = vm_try!(Vec::with_capacity(cap));
while let Some(value) = vm_try!(next.call((iter.clone(),))) {
vm_try!(vec.push(value));
}
VmResult::Ok(vec)
})?;
}
{
let next = next.clone();
let size_hint = size_hint.clone();
cx.function(
Params::new("collect", [VecDeque::HASH]),
move |iter: Value| {
let (cap, _) = vm_try!(size_hint.call((&iter,)));
let mut vec = vm_try!(Vec::with_capacity(cap));
while let Some(value) = vm_try!(next.call((iter.clone(),))) {
vm_try!(vec.push(value));
}
VmResult::Ok(VecDeque::from(vec))
},
)?;
}
{
let next = next.clone();
let size_hint = size_hint.clone();
cx.function(
Params::new("collect", [HashSet::HASH]),
move |iter: Value| {
let (cap, _) = vm_try!(size_hint.call((&iter,)));
let mut set = vm_try!(HashSet::with_capacity(cap));
while let Some(value) = vm_try!(next.call((iter.clone(),))) {
vm_try!(set.insert(value));
}
VmResult::Ok(set)
},
)?;
}
{
let next = next.with_return::<Option<(Value, Value)>>();
let size_hint = size_hint.clone();
cx.function(
Params::new("collect", [HashMap::HASH]),
move |iter: Value| {
let (cap, _) = vm_try!(size_hint.call((&iter,)));
let mut map = vm_try!(HashMap::with_capacity(cap));
while let Some((key, value)) = vm_try!(next.call((iter.clone(),))) {
vm_try!(map.insert(key, value));
}
VmResult::Ok(map)
},
)?;
}
{
let next = next.with_return::<Option<(String, Value)>>();
let size_hint = size_hint.clone();
cx.function(
Params::new("collect", [Object::HASH]),
move |iter: Value| {
let (cap, _) = vm_try!(size_hint.call((&iter,)));
let mut map = vm_try!(Object::with_capacity(cap));
while let Some((key, value)) = vm_try!(next.call((iter.clone(),))) {
vm_try!(map.insert(key, value));
}
VmResult::Ok(map)
},
)?;
}
{
let next = next.clone();
let size_hint = size_hint.clone();
cx.function(
Params::new("collect", [OwnedTuple::HASH]),
move |iter: Value| {
let (cap, _) = vm_try!(size_hint.call((&iter,)));
let mut vec = vm_try!(alloc::Vec::try_with_capacity(cap));
while let Some(value) = vm_try!(next.call((iter.clone(),))) {
vm_try!(vec.try_push(value));
}
VmResult::Ok(vm_try!(OwnedTuple::try_from(vec)))
},
)?;
}
{
let next = next.clone();
cx.function(
Params::new("collect", [String::HASH]),
move |iter: Value| {
let mut string = String::new();
while let Some(value) = vm_try!(next.call((iter.clone(),))) {
match value.as_ref() {
Repr::Inline(Inline::Char(c)) => {
vm_try!(string.try_push(*c));
}
Repr::Inline(value) => {
return VmResult::expected::<String>(value.type_info());
}
Repr::Dynamic(value) => {
return VmResult::expected::<String>(value.type_info());
}
Repr::Any(value) => match value.type_hash() {
String::HASH => {
let s = vm_try!(value.borrow_ref::<String>());
vm_try!(string.try_push_str(&s));
}
_ => {
return VmResult::expected::<String>(value.type_info());
}
},
}
}
VmResult::Ok(string)
},
)?;
}
macro_rules! ops {
($ty:ty) => {{
cx.function(Params::new("product", [<$ty>::HASH]), |iter: Value| {
let mut product = match vm_try!(iter.protocol_next()) {
Some(init) => vm_try!(<$ty>::from_value(init)),
None => <$ty>::ONE,
};
while let Some(v) = vm_try!(iter.protocol_next()) {
let v = vm_try!(<$ty>::from_value(v));
let Some(out) = product.checked_mul(v) else {
return VmResult::err(VmErrorKind::Overflow);
};
product = out;
}
VmResult::Ok(product)
})?;
}
{
cx.function(Params::new("sum", [<$ty>::HASH]), |iter: Value| {
let mut sum = match vm_try!(iter.protocol_next()) {
Some(init) => vm_try!(<$ty>::from_value(init)),
None => <$ty>::ZERO,
};
while let Some(v) = vm_try!(iter.protocol_next()) {
let v = vm_try!(<$ty>::from_value(v));
let Some(out) = sum.checked_add(v) else {
return VmResult::err(VmErrorKind::Overflow);
};
sum = out;
}
VmResult::Ok(sum)
})?;
}};
}
ops!(u64);
ops!(i64);
ops!(f64);
Ok(())
})?;
t.function("next")?
.argument_types::<(Value,)>()?
.return_type::<Option<Value>>()?
.docs(docstring! {
/// Advances the iterator and returns the next value.
///
/// Returns [`None`] when iteration is finished. Individual iterator
/// implementations may choose to resume iteration, and so calling `next()`
/// again may or may not eventually start returning [`Some(Item)`] again at some
/// point.
///
/// [`Some(Item)`]: Some
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter();
///
/// // A call to next() returns the next value...
/// assert_eq!(Some(1), iter.next());
/// assert_eq!(Some(2), iter.next());
/// assert_eq!(Some(3), iter.next());
///
/// // ... and then None once it's over.
/// assert_eq!(None, iter.next());
///
/// // More calls may or may not return `None`. Here, they always will.
/// assert_eq!(None, iter.next());
/// assert_eq!(None, iter.next());
/// ```
})?;
t.function("nth")?
.argument_types::<(Value, usize)>()?
.return_type::<Option<Value>>()?
.docs(docstring! {
/// Returns the `n`th element of the iterator.
///
/// Like most indexing operations, the count starts from zero, so `nth(0)`
/// returns the first value, `nth(1)` the second, and so on.
///
/// Note that all preceding elements, as well as the returned element, will be
/// consumed from the iterator. That means that the preceding elements will be
/// discarded, and also that calling `nth(0)` multiple times on the same iterator
/// will return different elements.
///
/// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
/// iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth(1), Some(2));
/// ```
///
/// Calling `nth()` multiple times doesn't rewind the iterator:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter();
///
/// assert_eq!(iter.nth(1), Some(2));
/// assert_eq!(iter.nth(1), None);
/// ```
///
/// Returning `None` if there are less than `n + 1` elements:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth(10), None);
/// ```
})?;
t.function("size_hint")?
.argument_types::<(Value,)>()?
.return_type::<(usize, Option<usize>)>()?
.docs(docstring! {
/// Returns the bounds on the remaining length of the iterator.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an
/// <code>[Option]<[i64]></code>. A [`None`] here means that either there is no
/// known upper bound, or the upper bound is larger than [`i64`].
///
/// # Implementation notes
///
/// It is not enforced that an iterator implementation yields the declared
/// number of elements. A buggy iterator may yield less than the lower bound or
/// more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the iterator, but must not be trusted to
/// e.g., omit bounds checks in unsafe code. An incorrect implementation of
/// `size_hint()` should not lead to memory safety violations.
///
/// That said, the implementation should provide a correct estimation, because
/// otherwise it would be a violation of the trait's protocol.
///
/// The default implementation returns <code>(0, [None])</code> which is correct
/// for any iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
/// let iter = a.iter();
///
/// assert_eq!(iter.size_hint(), (3u64, Some(3)));
/// let _ = iter.next();
/// assert_eq!(iter.size_hint(), (2u64, Some(2)));
/// ```
///
/// A more complex example:
///
/// ```rune
/// // The even numbers in the range of zero to nine.
/// let iter = (0..10).iter().filter(|x| x % 2 == 0);
///
/// // We might iterate from zero to ten times. Knowing that it's five
/// // exactly wouldn't be possible without executing filter().
/// assert_eq!(iter.size_hint(), (0, Some(10)));
///
/// // Let's add five more numbers with chain()
/// let iter = (0..10).iter().filter(|x| x % 2 == 0).chain(15..20);
///
/// // now both bounds are increased by five
/// assert_eq!(iter.size_hint(), (5, Some(15)));
/// ```
///
/// Returning `None` for an upper bound:
///
/// ```rune
/// // an infinite iterator has no upper bound
/// // and the maximum possible lower bound
/// let iter = (0..).iter();
///
/// assert_eq!(iter.size_hint(), (u64::MAX, None));
/// ```
})?;
t.function("count")?
.argument_types::<(Value,)>()?
.return_type::<usize>()?
.docs(docstring! {
/// Consumes the iterator, counting the number of iterations and returning it.
///
/// This method will call [`next`] repeatedly until [`None`] is encountered,
/// returning the number of times it saw [`Some`]. Note that [`next`] has to be
/// called at least once even if the iterator does not have any elements.
///
/// [`next`]: Iterator::next
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so counting elements of an
/// iterator with more than [`i64::MAX`] elements panics.
///
/// # Panics
///
/// This function might panic if the iterator has more than [`i64::MAX`]
/// elements.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().count(), 3);
///
/// let a = [1, 2, 3, 4, 5];
/// assert_eq!(a.iter().count(), 5);
/// ```
})?;
t.function("fold")?
.argument_types::<(Value, Value, Function)>()?
.return_type::<Value>()?
.docs(docstring! {
/// Folds every element into an accumulator by applying an operation, returning
/// the final result.
///
/// `fold()` takes two arguments: an initial value, and a closure with two
/// arguments: an 'accumulator', and an element. The closure returns the value
/// that the accumulator should have for the next iteration.
///
/// The initial value is the value the accumulator will have on the first call.
///
/// After applying this closure to every element of the iterator, `fold()`
/// returns the accumulator.
///
/// This operation is sometimes called 'reduce' or 'inject'.
///
/// Folding is useful whenever you have a collection of something, and want to
/// produce a single value from it.
///
/// Note: `fold()`, and similar methods that traverse the entire iterator, might
/// not terminate for infinite iterators, even on traits for which a result is
/// determinable in finite time.
///
/// Note: [`reduce()`] can be used to use the first element as the initial
/// value, if the accumulator type and item type is the same.
///
/// Note: `fold()` combines elements in a *left-associative* fashion. For
/// associative operators like `+`, the order the elements are combined in is
/// not important, but for non-associative operators like `-` the order will
/// affect the final result. For a *right-associative* version of `fold()`, see
/// [`DoubleEndedIterator::rfold()`].
///
/// # Note to Implementors
///
/// Several of the other (forward) methods have default implementations in
/// terms of this one, so try to implement this explicitly if it can
/// do something better than the default `for` loop implementation.
///
/// In particular, try to have this call `fold()` on the internal parts
/// from which this iterator is composed.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// // the sum of all of the elements of the array
/// let sum = a.iter().fold(0, |acc, x| acc + x);
///
/// assert_eq!(sum, 6);
/// ```
///
/// Let's walk through each step of the iteration here:
///
/// | element | acc | x | result |
/// |---------|-----|---|--------|
/// | | 0 | | |
/// | 1 | 0 | 1 | 1 |
/// | 2 | 1 | 2 | 3 |
/// | 3 | 3 | 3 | 6 |
///
/// And so, our final result, `6`.
///
/// This example demonstrates the left-associative nature of `fold()`:
/// it builds a string, starting with an initial value
/// and continuing with each element from the front until the back:
///
/// ```rune
/// let numbers = [1, 2, 3, 4, 5];
///
/// let zero = "0";
///
/// let result = numbers.iter().fold(zero, |acc, x| {
/// format!("({} + {})", acc, x)
/// });
///
/// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
/// ```
///
/// It's common for people who haven't used iterators a lot to
/// use a `for` loop with a list of things to build up a result. Those
/// can be turned into `fold()`s:
///
/// ```rune
/// let numbers = [1, 2, 3, 4, 5];
///
/// let result = 0;
///
/// // for loop:
/// for i in numbers {
/// result = result + i;
/// }
///
/// // fold:
/// let result2 = numbers.iter().fold(0, |acc, x| acc + x);
///
/// // they're the same
/// assert_eq!(result, result2);
/// ```
///
/// [`reduce()`]: Iterator::reduce
})?;
t.function("reduce")?
.argument_types::<(Value, Function)>()?
.return_type::<Option<Value>>()?
.docs(docstring! {
/// Reduces the elements to a single one, by repeatedly applying a reducing
/// operation.
///
/// If the iterator is empty, returns [`None`]; otherwise, returns the result of
/// the reduction.
///
/// The reducing function is a closure with two arguments: an 'accumulator', and
/// an element. For iterators with at least one element, this is the same as
/// [`fold()`] with the first element of the iterator as the initial accumulator
/// value, folding every subsequent element into it.
///
/// [`fold()`]: Iterator::fold
///
/// # Example
///
/// ```rune
/// let reduced = (1..10).iter().reduce(|acc, e| acc + e).unwrap();
/// assert_eq!(reduced, 45);
///
/// // Which is equivalent to doing it with `fold`:
/// let folded = (1..10).iter().fold(0, |acc, e| acc + e);
/// assert_eq!(reduced, folded);
/// ```
})?;
t.function("find")?
.argument_types::<(Value, Function)>()?
.return_type::<Option<Value>>()?
.docs(docstring! {
/// Searches for an element of an iterator that satisfies a predicate.
///
/// `find()` takes a closure that returns `true` or `false`. It applies this
/// closure to each element of the iterator, and if any of them return `true`,
/// then `find()` returns [`Some(element)`]. If they all return `false`, it
/// returns [`None`].
///
/// `find()` is short-circuiting; in other words, it will stop processing as
/// soon as the closure returns `true`.
///
/// If you need the index of the element, see [`position()`].
///
/// [`Some(element)`]: Some
/// [`position()`]: Iterator::position
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// assert_eq!(a.iter().find(|x| x == 2), Some(2));
///
/// assert_eq!(a.iter().find(|x| x == 5), None);
/// ```
///
/// Stopping at the first `true`:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter();
///
/// assert_eq!(iter.find(|x| x == 2), Some(2));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(3));
/// ```
///
/// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
})?;
t.function("any")?
.argument_types::<(Value, Function)>()?
.return_type::<bool>()?
.docs(docstring! {
/// Tests if any element of the iterator matches a predicate.
///
/// `any()` takes a closure that returns `true` or `false`. It applies this
/// closure to each element of the iterator, and if any of them return `true`,
/// then so does `any()`. If they all return `false`, it returns `false`.
///
/// `any()` is short-circuiting; in other words, it will stop processing as soon
/// as it finds a `true`, given that no matter what else happens, the result
/// will also be `true`.
///
/// An empty iterator returns `false`.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// assert!(a.iter().any(|x| x > 0));
///
/// assert!(!a.iter().any(|x| x > 5));
/// ```
///
/// Stopping at the first `true`:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter();
///
/// assert!(iter.any(|x| x != 2));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(2));
/// ```
})?;
t.function("all")?
.argument_types::<(Value, Function)>()?
.return_type::<bool>()?
.docs(docstring! {
/// Tests if every element of the iterator matches a predicate.
///
/// `all()` takes a closure that returns `true` or `false`. It applies this
/// closure to each element of the iterator, and if they all return `true`, then
/// so does `all()`. If any of them return `false`, it returns `false`.
///
/// `all()` is short-circuiting; in other words, it will stop processing as soon
/// as it finds a `false`, given that no matter what else happens, the result
/// will also be `false`.
///
/// An empty iterator returns `true`.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// assert!(a.iter().all(|x| x > 0));
///
/// assert!(!a.iter().all(|x| x > 2));
/// ```
///
/// Stopping at the first `false`:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter();
///
/// assert!(!iter.all(|x| x != 2));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(3));
/// ```
})?;
t.function("chain")?
.argument_types::<(Value, Value)>()?
.return_type::<Chain>()?
.docs(docstring! {
/// Takes two iterators and creates a new iterator over both in sequence.
///
/// `chain()` will return a new iterator which will first iterate over
/// values from the first iterator and then over values from the second
/// iterator.
///
/// In other words, it links two iterators together, in a chain. 🔗
///
/// [`once`] is commonly used to adapt a single value into a chain of other
/// kinds of iteration.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a1 = [1, 2, 3];
/// let a2 = [4, 5, 6];
///
/// let iter = a1.iter().chain(a2.iter());
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), Some(3));
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), Some(6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Since the argument to `chain()` uses [`INTO_ITER`], we can pass anything
/// that can be converted into an [`Iterator`], not just an [`Iterator`] itself.
/// For example, slices (`[T]`) implement [`INTO_ITER`], and so can be passed to
/// `chain()` directly:
///
/// ```rune
/// let s1 = [1, 2, 3];
/// let s2 = [4, 5, 6];
///
/// let iter = s1.iter().chain(s2);
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), Some(3));
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), Some(6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// [`INTO_ITER`]: protocol@INTO_ITER
})?;
t.function("enumerate")?
.argument_types::<(Value,)>()?
.return_type::<Enumerate>()?
.docs(docstring! {
/// Creates an iterator which gives the current iteration count as well as
/// the next value.
///
/// The iterator returned yields pairs `(i, val)`, where `i` is the current
/// index of iteration and `val` is the value returned by the iterator.
///
/// `enumerate()` keeps its count as a usize. If you want to count by a
/// different sized integer, the zip function provides similar
/// functionality.
///
/// # Examples
///
/// ```rune
/// let a = ['a', 'b', 'c'];
///
/// let iter = a.iter().enumerate();
///
/// assert_eq!(iter.next(), Some((0u64, 'a')));
/// assert_eq!(iter.next(), Some((1u64, 'b')));
/// assert_eq!(iter.next(), Some((2u64, 'c')));
/// assert_eq!(iter.next(), None);
/// ```
})?;
t.function("filter")?
.argument_types::<(Value, Function)>()?
.return_type::<Filter>()?
.docs(docstring! {
/// Creates an iterator which uses a closure to determine if an element
/// should be yielded.
///
/// Given an element the closure must return `true` or `false`. The returned
/// iterator will yield only the elements for which the closure returns
/// `true`.
///
/// ```rune
/// let a = [0, 1, 2];
///
/// let iter = a.iter().filter(|x| x.is_positive());
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
})?;
t.function("map")?
.argument_types::<(Value, Function)>()?
.return_type::<Map>()?
.docs(docstring! {
/// Takes a closure and creates an iterator which calls that closure on each
/// element.
///
/// `map()` transforms one iterator into another. It produces a new iterator
/// which calls this closure on each element of the original iterator.
///
/// If you are good at thinking in types, you can think of `map()` like
/// this: If you have an iterator that gives you elements of some type `A`,
/// and you want an iterator of some other type `B`, you can use `map()`,
/// passing a closure that takes an `A` and returns a `B`.
///
/// `map()` is conceptually similar to a `for` loop. However, as `map()` is
/// lazy, it is best used when you're already working with other iterators.
/// If you're doing some sort of looping for a side effect, it's considered
/// more idiomatic to use `for` than `map()`.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter().map(|x| 2 * x);
///
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), Some(6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// If you're doing some sort of side effect, prefer `for` to `map()`:
///
/// ```rune
/// // don't do this:
/// (0..5).iter().map(|x| println!("{}", x));
///
/// // it won't even execute, as it is lazy. Rust will warn you about this.
///
/// // Instead, use for:
/// for x in 0..5 {
/// println!("{}", x);
/// }
/// ```
})?;
t.function("filter_map")?
.argument_types::<(Value, Function)>()?
.return_type::<FilterMap>()?
.docs(docstring! {
/// Creates an iterator that both filters and maps.
///
/// The returned iterator yields only the `value`s for which the supplied
/// closure returns `Some(value)`.
///
/// `filter_map` can be used to make chains of [`filter`] and [`map`] more
/// concise. The example below shows how a `map().filter().map()` can be
/// shortened to a single call to `filter_map`.
///
/// [`filter`]: Iterator::filter
/// [`map`]: Iterator::map
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = ["1", "two", "NaN", "four", "5"];
///
/// let iter = a.iter().filter_map(|s| s.parse::<i64>().ok());
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Here's the same example, but with [`filter`] and [`map`]:
///
/// ```rune
/// let a = ["1", "two", "NaN", "four", "5"];
/// let iter = a.iter().map(|s| s.parse::<i64>()).filter(|s| s.is_ok()).map(|s| s.unwrap());
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// ```
})?;
t.function("flat_map")?
.argument_types::<(Value, Function)>()?
.return_type::<FlatMap>()?
.docs(docstring! {
/// Creates an iterator that works like map, but flattens nested
/// structure.
///
/// The [`map`] adapter is very useful, but only when the
/// closure argument produces values. If it produces an iterator
/// instead, there's an extra layer of indirection. `flat_map()`
/// will remove this extra layer on its own.
///
/// You can think of `flat_map(f)` as the semantic equivalent of
/// [`map`]ping, and then [`flatten`]ing as in
/// `map(f).flatten()`.
///
/// Another way of thinking about `flat_map()`: [`map`]'s
/// closure returns one item for each element, and
/// `flat_map()`'s closure returns an iterator for each element.
///
/// [`map`]: Iterator::map
/// [`flatten`]: Iterator::flatten
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let words = ["alpha", "beta", "gamma"];
///
/// // chars() returns an iterator
/// let merged = words.iter().flat_map(|s| s.chars()).collect::<String>();
/// assert_eq!(merged, "alphabetagamma");
/// ```
})?;
t.function("peekable")?
.argument_types::<(Value,)>()?
.return_type::<Peekable>()?
.docs(docstring! {
/// Creates an iterator which can use the [`peek`] method to
/// look at the next element of the iterator without consuming
/// it. See their documentation for more information.
///
/// Note that the underlying iterator is still advanced when
/// [`peek`] are called for the first time: In order to retrieve
/// the next element, [`next`] is called on the underlying
/// iterator, hence any side effects (i.e. anything other than
/// fetching the next value) of the [`next`] method will occur.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let xs = [1, 2, 3];
///
/// let iter = xs.iter().peekable();
///
/// // peek() lets us see into the future
/// assert_eq!(iter.peek(), Some(1));
/// assert_eq!(iter.next(), Some(1));
///
/// assert_eq!(iter.next(), Some(2));
///
/// // we can peek() multiple times, the iterator won't advance
/// assert_eq!(iter.peek(), Some(3));
/// assert_eq!(iter.peek(), Some(3));
///
/// assert_eq!(iter.next(), Some(3));
///
/// // after the iterator is finished, so is peek()
/// assert_eq!(iter.peek(), None);
/// assert_eq!(iter.next(), None);
/// ```
///
/// [`peek`]: Peekable::peek
/// [`next`]: Iterator::next
})?;
t.function("skip")?
.argument_types::<(Value, usize)>()?
.return_type::<Skip>()?
.docs(docstring! {
/// Creates an iterator that skips the first `n` elements.
///
/// `skip(n)` skips elements until `n` elements are skipped or
/// the end of the iterator is reached (whichever happens
/// first). After that, all the remaining elements are yielded.
/// In particular, if the original iterator is too short, then
/// the returned iterator is empty.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter().skip(2);
///
/// assert_eq!(iter.next(), Some(3));
/// assert_eq!(iter.next(), None);
/// ```
})?;
t.function("take")?
.argument_types::<(Value, usize)>()?
.return_type::<Take>()?
.docs(docstring! {
/// Creates an iterator that yields the first `n` elements, or
/// fewer if the underlying iterator ends sooner.
///
/// `take(n)` yields elements until `n` elements are yielded or
/// the end of the iterator is reached (whichever happens
/// first). The returned iterator is a prefix of length `n` if
/// the original iterator contains at least `n` elements,
/// otherwise it contains all of the (fewer than `n`) elements
/// of the original iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter().take(2);
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// `take()` is often used with an infinite iterator, to make it
/// finite:
///
/// ```rune
/// let iter = (0..).iter().take(3);
///
/// assert_eq!(iter.next(), Some(0));
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// If less than `n` elements are available, `take` will limit
/// itself to the size of the underlying iterator:
///
/// ```rune
/// let v = [1, 2];
/// let iter = v.iter().take(5);
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
})?;
macro_rules! sum_ops {
($ty:ty) => {
t.function(Params::new("sum", [<$ty>::HASH]))?
.argument_types::<(Value,)>()?
.return_type::<$ty>()?
.docs(docstring! {
/// Sums the elements of an iterator.
///
/// Takes each element, adds them together, and returns
/// the result.
///
/// An empty iterator returns the zero value of the
/// type.
///
/// `sum()` can be used to sum numerical built-in types,
/// such as `i64`, `float` and `u64`. The first element
/// returned by the iterator determines the type being
/// summed.
///
/// # Panics
///
/// When calling `sum()` and a primitive integer type is
/// being returned, this method will panic if the
/// computation overflows.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
#[doc = concat!(" let a = [1", stringify!($ty), ", 2", stringify!($ty), ", 3", stringify!($ty), "];")]
#[doc = concat!(" let sum = a.iter().sum::<", stringify!($ty), ">();")]
///
#[doc = concat!(" assert_eq!(sum, 6", stringify!($ty), ");")]
/// ```
})?;
};
}
sum_ops!(u64);
sum_ops!(i64);
sum_ops!(f64);
macro_rules! integer_product_ops {
($ty:ty) => {
t.function(Params::new("product", [<$ty>::HASH]))?
.argument_types::<(Value,)>()?
.return_type::<$ty>()?
.docs(docstring! {
/// Iterates over the entire iterator, multiplying all
/// the elements
///
/// An empty iterator returns the one value of the type.
///
/// `sum()` can be used to sum numerical built-in types,
/// such as `i64`, `f64` and `u64`. The first element
/// returned by the iterator determines the type being
/// multiplied.
///
/// # Panics
///
/// When calling `product()` and a primitive integer
/// type is being returned, method will panic if the
/// computation overflows.
///
/// # Examples
///
/// ```rune
/// fn factorial(n) {
#[doc = concat!(" (1", stringify!($ty), "..=n).iter().product::<", stringify!($ty), ">()")]
/// }
///
#[doc = concat!(" assert_eq!(factorial(0", stringify!($ty), "), 1", stringify!($ty), ");")]
#[doc = concat!(" assert_eq!(factorial(1", stringify!($ty), "), 1", stringify!($ty), ");")]
#[doc = concat!(" assert_eq!(factorial(5", stringify!($ty), "), 120", stringify!($ty), ");")]
/// ```
})?;
};
}
t.function(Params::new("collect", [Vec::HASH]))?
.return_type::<Vec>()?
.docs(docstring! {
/// Collect the iterator as a [`Vec`].
///
/// # Examples
///
/// ```rune
/// use std::iter::range;
///
/// assert_eq!((0..3).iter().collect::<Vec>(), [0, 1, 2]);
/// ```
})?;
t.function(Params::new("collect", [VecDeque::HASH]))?
.return_type::<VecDeque>()?
.docs(docstring! {
/// Collect the iterator as a [`VecDeque`].
///
/// # Examples
///
/// ```rune
/// use std::collections::VecDeque;
///
/// assert_eq!((0..3).iter().collect::<VecDeque>(), VecDeque::from::<Vec>([0, 1, 2]));
/// ```
})?;
t.function(Params::new("collect", [HashSet::HASH]))?
.return_type::<HashSet>()?
.docs(docstring! {
/// Collect the iterator as a [`HashSet`].
///
/// # Examples
///
/// ```rune
/// use std::collections::HashSet;
///
/// let a = (0..3).iter().collect::<HashSet>();
/// let b = HashSet::from_iter([0, 1, 2]);
///
/// assert_eq!(a, b);
/// ```
})?;
t.function(Params::new("collect", [HashMap::HASH]))?
.return_type::<HashMap>()?
.docs(docstring! {
/// Collect the iterator as a [`HashMap`].
///
/// # Examples
///
/// ```rune
/// use std::collections::HashMap;
///
/// let actual = (0..3).iter().map(|n| (n, n.to_string())).collect::<HashMap>();
///
/// let expected = HashMap::from_iter([
/// (0, "0"),
/// (1, "1"),
/// (2, "2"),
/// ]);
///
/// assert_eq!(actual, expected);
/// ```
})?;
t.function(Params::new("collect", [Object::HASH]))?
.return_type::<HashMap>()?
.docs(docstring! {
/// Collect the iterator as an [`Object`].
///
/// # Examples
///
/// ```rune
/// assert_eq!([("first", 1), ("second", 2)].iter().collect::<Object>(), #{first: 1, second: 2});
/// ```
})?;
t.function(Params::new("collect", [OwnedTuple::HASH]))?
.return_type::<OwnedTuple>()?
.docs(docstring! {
/// Collect the iterator as a [`Tuple`].
///
/// # Examples
///
/// ```rune
/// assert_eq!((0..3).iter().collect::<Tuple>(), (0, 1, 2));
/// ```
})?;
t.function(Params::new("collect", [String::HASH]))?
.return_type::<String>()?
.docs(docstring! {
/// Collect the iterator as a [`String`].
///
/// # Examples
///
/// ```rune
/// assert_eq!(["first", "second"].iter().collect::<String>(), "firstsecond");
/// ```
})?;
macro_rules! float_product_ops {
($ty:ty) => {
t.function(Params::new("product", [<$ty>::HASH]))?
.argument_types::<(Value,)>()?
.return_type::<$ty>()?
.docs(docstring! {
/// Iterates over the entire iterator, multiplying all
/// the elements
///
/// An empty iterator returns the one value of the type.
///
/// `sum()` can be used to sum numerical built-in types,
/// such as `i64`, `f64` and `u64`. The first element
/// returned by the iterator determines the type being
/// multiplied.
///
/// # Panics
///
/// When calling `product()` and a primitive integer
/// type is being returned, method will panic if the
/// computation overflows.
///
/// # Examples
///
/// ```rune
/// fn factorial(n) {
#[doc = concat!(" (1..=n).iter().map(|n| n as ", stringify!($ty), ").product::<", stringify!($ty), ">()")]
/// }
///
#[doc = concat!(" assert_eq!(factorial(0), 1", stringify!($ty), ");")]
#[doc = concat!(" assert_eq!(factorial(1), 1", stringify!($ty), ");")]
#[doc = concat!(" assert_eq!(factorial(5), 120", stringify!($ty), ");")]
/// ```
})?;
};
}
integer_product_ops!(u64);
integer_product_ops!(i64);
float_product_ops!(f64);
}
{
let mut t = m.define_trait(["DoubleEndedIterator"])?;
t.docs(docstring! {
/// An iterator able to yield elements from both ends.
///
/// Something that implements `DoubleEndedIterator` has one extra
/// capability over something that implements [`Iterator`]: the
/// ability to also take `Item`s from the back, as well as the
/// front.
///
/// It is important to note that both back and forth work on the
/// same range, and do not cross: iteration is over when they meet
/// in the middle.
///
/// In a similar fashion to the [`Iterator`] protocol, once a
/// `DoubleEndedIterator` returns [`None`] from a [`next_back()`],
/// calling it again may or may not ever return [`Some`] again.
/// [`next()`] and [`next_back()`] are interchangeable for this
/// purpose.
///
/// [`next_back()`]: DoubleEndedIterator::next_back
/// [`next()`]: Iterator::next
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let numbers = [1, 2, 3, 4, 5, 6];
///
/// let iter = numbers.iter();
///
/// assert_eq!(Some(1), iter.next());
/// assert_eq!(Some(6), iter.next_back());
/// assert_eq!(Some(5), iter.next_back());
/// assert_eq!(Some(2), iter.next());
/// assert_eq!(Some(3), iter.next());
/// assert_eq!(Some(4), iter.next());
/// assert_eq!(None, iter.next());
/// assert_eq!(None, iter.next_back());
/// ```
})?;
t.handler(|cx| {
let next_back = cx.find(&Protocol::NEXT_BACK)?;
cx.find_or_define(&Protocol::NTH_BACK, {
let next_back = next_back.clone();
move |iterator: Value, mut n: usize| loop {
let mut memory = [iterator.clone()];
vm_try!(next_back(
&mut memory,
InstAddress::ZERO,
1,
Output::keep(0)
));
let [value] = memory;
let Some(value) = vm_try!(Option::<Value>::from_value(value)) else {
break VmResult::Ok(None);
};
if n == 0 {
break VmResult::Ok(Some(value));
}
n -= 1;
}
})?;
cx.raw_function("rev", |stack, addr, len, out| {
let [value] = vm_try!(stack.slice_at(addr, len)) else {
return VmResult::err(VmErrorKind::BadArgumentCount {
actual: len,
expected: 1,
});
};
let rev = Rev {
value: value.clone(),
};
vm_try!(out.store(stack, || rune::to_value(rev)));
VmResult::Ok(())
})?;
Ok(())
})?;
t.function("next_back")?
.argument_types::<(Value,)>()?
.return_type::<Option<Value>>()?
.docs(docstring! {
/// Removes and returns an element from the end of the iterator.
///
/// Returns `None` when there are no more elements.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let numbers = [1, 2, 3, 4, 5, 6];
///
/// let iter = numbers.iter();
///
/// assert_eq!(Some(1), iter.next());
/// assert_eq!(Some(6), iter.next_back());
/// assert_eq!(Some(5), iter.next_back());
/// assert_eq!(Some(2), iter.next());
/// assert_eq!(Some(3), iter.next());
/// assert_eq!(Some(4), iter.next());
/// assert_eq!(None, iter.next());
/// assert_eq!(None, iter.next_back());
/// ```
})?;
t.function("nth_back")?
.argument_types::<(Value, usize)>()?
.return_type::<Option<Value>>()?
.docs(docstring! {
/// Returns the `n`th element from the end of the iterator.
///
/// This is essentially the reversed version of
/// [`Iterator::nth()`]. Although like most indexing operations,
/// the count starts from zero, so `nth_back(0)` returns the
/// first value from the end, `nth_back(1)` the second, and so
/// on.
///
/// Note that all elements between the end and the returned
/// element will be consumed, including the returned element.
/// This also means that calling `nth_back(0)` multiple times on
/// the same iterator will return different elements.
///
/// `nth_back()` will return [`None`] if `n` is greater than or
/// equal to the length of the iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth_back(2), Some(1));
/// ```
///
/// Calling `nth_back()` multiple times doesn't rewind the
/// iterator:
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter();
///
/// assert_eq!(iter.nth_back(1), Some(2));
/// assert_eq!(iter.nth_back(1), None);
/// ```
///
/// Returning `None` if there are less than `n + 1` elements:
///
/// ```rune
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth_back(10), None);
/// ```
})?;
t.function("rev")?
.argument_types::<(Value,)>()?
.return_type::<Rev>()?
.docs(docstring! {
/// Reverses an iterator's direction.
///
/// Usually, iterators iterate from left to right. After using `rev()`, an
/// iterator will instead iterate from right to left.
///
/// This is only possible if the iterator has an end, so `rev()` only works on
/// double-ended iterators.
///
/// # Examples
///
/// ```rune
/// let a = [1, 2, 3];
///
/// let iter = a.iter().rev();
///
/// assert_eq!(iter.next(), Some(3));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), Some(1));
///
/// assert_eq!(iter.next(), None);
/// ```
})?;
}
m.function_meta(range)?;
m.ty::<Empty>()?;
m.function_meta(Empty::next__meta)?;
m.function_meta(Empty::next_back__meta)?;
m.function_meta(Empty::size_hint__meta)?;
m.implement_trait::<Empty>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Empty>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.function_meta(empty)?;
m.ty::<Once>()?;
m.function_meta(Once::next__meta)?;
m.function_meta(Once::next_back__meta)?;
m.function_meta(Once::size_hint__meta)?;
m.implement_trait::<Once>(rune::item!(::std::iter::Iterator))?;
m.implement_trait::<Once>(rune::item!(::std::iter::DoubleEndedIterator))?;
m.function_meta(once)?;
Ok(m)
}
/// Construct an iterator which produces no values.
///
/// # Examples
///
/// ```rune
/// use std::iter::empty;
///
/// assert!(empty().next().is_none());
/// assert_eq!(empty().collect::<Vec>(), []);
/// ```
#[rune::function]
fn empty() -> Empty {
Empty
}
#[derive(Any)]
#[rune(item = ::std::iter)]
struct Empty;
impl Empty {
#[rune::function(keep, protocol = NEXT)]
fn next(&mut self) -> Option<Value> {
None
}
#[rune::function(keep, protocol = NEXT_BACK)]
fn next_back(&mut self) -> Option<Value> {
None
}
#[rune::function(keep, protocol = SIZE_HINT)]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(0))
}
}
/// Construct an iterator which produces a single `value` once.
///
/// # Examples
///
/// ```rune
/// use std::iter::once;
///
/// assert!(once(42).next().is_some());
/// assert_eq!(once(42).collect::<Vec>(), [42]);
/// ```
#[rune::function]
fn once(value: Value) -> Once {
Once { value: Some(value) }
}
#[derive(Any)]
#[rune(item = ::std::iter)]
struct Once {
value: Option<Value>,
}
impl Once {
#[rune::function(keep, protocol = NEXT)]
fn next(&mut self) -> Option<Value> {
self.value.take()
}
#[rune::function(keep, protocol = NEXT_BACK)]
fn next_back(&mut self) -> Option<Value> {
self.value.take()
}
#[rune::function(keep, protocol = SIZE_HINT)]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = usize::from(self.value.is_some());
(len, Some(len))
}
}
/// Produce an iterator which starts at the range `start` and ends at the value
/// `end` (exclusive).
///
/// # Examples
///
/// ```rune
/// use std::iter::range;
///
/// assert!(range(0, 3).next().is_some());
/// assert_eq!(range(0, 3).collect::<Vec>(), [0, 1, 2]);
/// ```
#[rune::function(deprecated = "Use the `<from>..<to>` operator instead")]
fn range(start: i64, end: i64) -> RangeIter<i64> {
RangeIter::new(start..end)
}
/// Fuse the iterator if the expression is `None`.
macro_rules! fuse {
($self:ident . $iter:ident . $($call:tt)+) => {
match $self.$iter {
Some(ref mut iter) => match vm_try!(iter.$($call)+) {
None => {
$self.$iter = None;
None
}
item => item,
},
None => None,
}
};
}
/// Try an iterator method without fusing,
/// like an inline `.as_mut().and_then(...)`
macro_rules! maybe {
($self:ident . $iter:ident . $($call:tt)+) => {
match $self.$iter {
Some(ref mut iter) => vm_try!(iter.$($call)+),
None => None,
}
};
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct Chain {
a: Option<Value>,
b: Option<Value>,
}
impl Chain {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<Value>> {
VmResult::Ok(match fuse!(self.a.protocol_next()) {
None => maybe!(self.b.protocol_next()),
item => item,
})
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<Value>> {
VmResult::Ok(match fuse!(self.b.protocol_next_back()) {
None => maybe!(self.a.protocol_next_back()),
item => item,
})
}
#[rune::function(keep, protocol = SIZE_HINT)]
#[inline]
fn size_hint(&self) -> VmResult<(usize, Option<usize>)> {
match self {
Self {
a: Some(a),
b: Some(b),
} => {
let (a_lower, a_upper) = vm_try!(a.protocol_size_hint());
let (b_lower, b_upper) = vm_try!(b.protocol_size_hint());
let lower = a_lower.saturating_add(b_lower);
let upper = match (a_upper, b_upper) {
(Some(x), Some(y)) => x.checked_add(y),
_ => None,
};
VmResult::Ok((lower, upper))
}
Self {
a: Some(a),
b: None,
} => a.protocol_size_hint(),
Self {
a: None,
b: Some(b),
} => b.protocol_size_hint(),
Self { a: None, b: None } => VmResult::Ok((0, Some(0))),
}
}
#[rune::function(keep, protocol = LEN)]
#[inline]
fn len(&self) -> VmResult<usize> {
match self {
Self {
a: Some(a),
b: Some(b),
} => {
let a_len = vm_try!(a.protocol_len());
let b_len = vm_try!(b.protocol_len());
VmResult::Ok(a_len.saturating_add(b_len))
}
Self {
a: Some(a),
b: None,
} => a.protocol_len(),
Self {
a: None,
b: Some(b),
} => b.protocol_len(),
Self { a: None, b: None } => VmResult::Ok(0),
}
}
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct Enumerate {
iter: Value,
count: usize,
}
impl Enumerate {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<(usize, Value)>> {
if let Some(value) = vm_try!(self.iter.protocol_next()) {
let i = self.count;
self.count += 1;
return VmResult::Ok(Some((i, value)));
}
VmResult::Ok(None)
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<(usize, Value)>> {
if let Some(value) = vm_try!(self.iter.protocol_next_back()) {
let len = vm_try!(self.iter.protocol_len());
return VmResult::Ok(Some((self.count + len, value)));
}
VmResult::Ok(None)
}
#[rune::function(keep, protocol = SIZE_HINT)]
#[inline]
fn size_hint(&self) -> VmResult<(usize, Option<usize>)> {
self.iter.protocol_size_hint()
}
#[rune::function(keep, protocol = LEN)]
#[inline]
fn len(&self) -> VmResult<usize> {
self.iter.protocol_len()
}
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct Filter {
iter: Value,
f: Function,
}
impl Filter {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<Value>> {
while let Some(value) = vm_try!(self.iter.protocol_next()) {
if vm_try!(self.f.call::<bool>((value.clone(),))) {
return VmResult::Ok(Some(value));
}
}
VmResult::Ok(None)
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<Value>> {
while let Some(value) = vm_try!(self.iter.protocol_next_back()) {
if vm_try!(self.f.call::<bool>((value.clone(),))) {
return VmResult::Ok(Some(value));
}
}
VmResult::Ok(None)
}
#[rune::function(keep, protocol = SIZE_HINT)]
#[inline]
fn size_hint(&self) -> VmResult<(usize, Option<usize>)> {
let (_, hi) = vm_try!(self.iter.protocol_size_hint());
VmResult::Ok((0, hi))
}
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct Map {
iter: Option<Value>,
f: Function,
}
impl Map {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<Value>> {
if let Some(value) = fuse!(self.iter.protocol_next()) {
return VmResult::Ok(Some(vm_try!(self.f.call::<Value>((value.clone(),)))));
}
VmResult::Ok(None)
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<Value>> {
if let Some(value) = fuse!(self.iter.protocol_next_back()) {
return VmResult::Ok(Some(vm_try!(self.f.call::<Value>((value.clone(),)))));
}
VmResult::Ok(None)
}
#[rune::function(keep, protocol = SIZE_HINT)]
#[inline]
fn size_hint(&self) -> VmResult<(usize, Option<usize>)> {
let Some(iter) = &self.iter else {
return VmResult::Ok((0, Some(0)));
};
iter.protocol_size_hint()
}
#[rune::function(keep, protocol = LEN)]
#[inline]
fn len(&self) -> VmResult<usize> {
let Some(iter) = &self.iter else {
return VmResult::Ok(0);
};
iter.protocol_len()
}
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct FilterMap {
iter: Option<Value>,
f: Function,
}
impl FilterMap {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<Value>> {
while let Some(value) = fuse!(self.iter.protocol_next()) {
if let Some(value) = vm_try!(self.f.call::<Option<Value>>((value.clone(),))) {
return VmResult::Ok(Some(value));
}
}
VmResult::Ok(None)
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<Value>> {
while let Some(value) = fuse!(self.iter.protocol_next_back()) {
if let Some(value) = vm_try!(self.f.call::<Option<Value>>((value.clone(),))) {
return VmResult::Ok(Some(value));
}
}
VmResult::Ok(None)
}
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct FlatMap {
map: Map,
frontiter: Option<Value>,
backiter: Option<Value>,
}
impl FlatMap {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<Value>> {
loop {
if let Some(iter) = &mut self.frontiter {
match vm_try!(iter.protocol_next()) {
None => self.frontiter = None,
item @ Some(_) => return VmResult::Ok(item),
}
}
let Some(value) = vm_try!(self.map.next()) else {
return VmResult::Ok(match &mut self.backiter {
Some(backiter) => vm_try!(backiter.protocol_next()),
None => None,
});
};
self.frontiter = Some(vm_try!(value.protocol_into_iter()))
}
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<Value>> {
loop {
if let Some(ref mut iter) = self.backiter {
match vm_try!(iter.protocol_next_back()) {
None => self.backiter = None,
item @ Some(_) => return VmResult::Ok(item),
}
}
let Some(value) = vm_try!(self.map.next_back()) else {
return VmResult::Ok(match &mut self.frontiter {
Some(frontiter) => vm_try!(frontiter.protocol_next_back()),
None => None,
});
};
self.backiter = Some(vm_try!(value.protocol_into_iter()));
}
}
#[rune::function(keep, protocol = SIZE_HINT)]
#[inline]
fn size_hint(&self) -> VmResult<(usize, Option<usize>)> {
let (flo, fhi) = match &self.frontiter {
Some(iter) => vm_try!(iter.protocol_size_hint()),
None => (0, Some(0)),
};
let (blo, bhi) = match &self.backiter {
Some(iter) => vm_try!(iter.protocol_size_hint()),
None => (0, Some(0)),
};
let lo = flo.saturating_add(blo);
VmResult::Ok(match (vm_try!(self.map.size_hint()), fhi, bhi) {
((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
_ => (lo, None),
})
}
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct Peekable {
iter: Value,
peeked: Option<Option<Value>>,
}
impl Peekable {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<Value>> {
VmResult::Ok(match self.peeked.take() {
Some(v) => v,
None => vm_try!(self.iter.protocol_next()),
})
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<Value>> {
VmResult::Ok(match self.peeked.as_mut() {
Some(v @ Some(_)) => vm_try!(self.iter.protocol_next_back()).or_else(|| v.take()),
Some(None) => None,
None => vm_try!(self.iter.protocol_next_back()),
})
}
#[rune::function(keep, protocol = SIZE_HINT)]
#[inline]
fn size_hint(&self) -> VmResult<(usize, Option<usize>)> {
let peek_len = match &self.peeked {
Some(None) => return VmResult::Ok((0, Some(0))),
Some(Some(_)) => 1,
None => 0,
};
let (lo, hi) = vm_try!(self.iter.protocol_size_hint());
let lo = lo.saturating_add(peek_len);
let hi = match hi {
Some(x) => x.checked_add(peek_len),
None => None,
};
VmResult::Ok((lo, hi))
}
#[rune::function(keep, protocol = LEN)]
#[inline]
fn len(&self) -> VmResult<usize> {
let peek_len = match &self.peeked {
Some(None) => return VmResult::Ok(0),
Some(Some(_)) => 1,
None => 0,
};
let len = vm_try!(self.iter.protocol_len());
VmResult::Ok(len.saturating_add(peek_len))
}
/// Returns a reference to the `next()` value without advancing the iterator.
///
/// Like [`next`], if there is a value, it is wrapped in a `Some(T)`. But if the
/// iteration is over, `None` is returned.
///
/// [`next`]: Iterator::next
///
/// Because `peek()` returns a reference, and many iterators iterate over
/// references, there can be a possibly confusing situation where the return
/// value is a double reference. You can see this effect in the examples below.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let xs = [1, 2, 3];
///
/// let iter = xs.iter().peekable();
///
/// // peek() lets us see into the future
/// assert_eq!(iter.peek(), Some(1));
/// assert_eq!(iter.next(), Some(1));
///
/// assert_eq!(iter.next(), Some(2));
///
/// // The iterator does not advance even if we `peek` multiple times
/// assert_eq!(iter.peek(), Some(3));
/// assert_eq!(iter.peek(), Some(3));
///
/// assert_eq!(iter.next(), Some(3));
///
/// // After the iterator is finished, so is `peek()`
/// assert_eq!(iter.peek(), None);
/// assert_eq!(iter.next(), None);
/// ```
#[rune::function(keep)]
#[inline]
fn peek(&mut self) -> VmResult<Option<Value>> {
if let Some(v) = &self.peeked {
return VmResult::Ok(v.clone());
}
let value = vm_try!(self.iter.protocol_next());
self.peeked = Some(value.clone());
VmResult::Ok(value)
}
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct Skip {
iter: Value,
n: usize,
}
impl Skip {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<Value>> {
if self.n > 0 {
let old_n = self.n;
self.n = 0;
for _ in 0..old_n {
match vm_try!(self.iter.protocol_next()) {
Some(..) => (),
None => return VmResult::Ok(None),
}
}
}
self.iter.protocol_next()
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<Value>> {
VmResult::Ok(if vm_try!(self.len()) > 0 {
vm_try!(self.iter.protocol_next_back())
} else {
None
})
}
#[rune::function(keep, protocol = SIZE_HINT)]
#[inline]
fn size_hint(&self) -> VmResult<(usize, Option<usize>)> {
let (lower, upper) = vm_try!(self.iter.protocol_size_hint());
let lower = lower.saturating_sub(self.n);
let upper = upper.map(|x| x.saturating_sub(self.n));
VmResult::Ok((lower, upper))
}
#[rune::function(keep, protocol = LEN)]
#[inline]
fn len(&self) -> VmResult<usize> {
let len = vm_try!(self.iter.protocol_len());
VmResult::Ok(len.saturating_sub(self.n))
}
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct Take {
iter: Value,
n: usize,
}
impl Take {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<Value>> {
if self.n == 0 {
return VmResult::Ok(None);
}
self.n -= 1;
self.iter.protocol_next()
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<Value>> {
if self.n == 0 {
VmResult::Ok(None)
} else {
let n = self.n;
self.n -= 1;
let len = vm_try!(self.iter.protocol_len());
self.iter.protocol_nth_back(len.saturating_sub(n))
}
}
#[rune::function(keep, protocol = SIZE_HINT)]
#[inline]
fn size_hint(&self) -> VmResult<(usize, Option<usize>)> {
if self.n == 0 {
return VmResult::Ok((0, Some(0)));
}
let (lower, upper) = vm_try!(self.iter.protocol_size_hint());
let lower = lower.min(self.n);
let upper = match upper {
Some(x) if x < self.n => Some(x),
_ => Some(self.n),
};
VmResult::Ok((lower, upper))
}
#[rune::function(keep, protocol = LEN)]
#[inline]
fn len(&self) -> VmResult<usize> {
if self.n == 0 {
return VmResult::Ok(0);
}
let len = vm_try!(self.iter.protocol_len());
VmResult::Ok(len.min(self.n))
}
}
#[derive(Any, Debug)]
#[rune(item = ::std::iter)]
struct Rev {
value: Value,
}
impl Rev {
#[rune::function(keep, protocol = NEXT)]
#[inline]
fn next(&mut self) -> VmResult<Option<Value>> {
self.value.protocol_next_back()
}
#[rune::function(keep, protocol = NEXT_BACK)]
#[inline]
fn next_back(&mut self) -> VmResult<Option<Value>> {
self.value.protocol_next()
}
#[rune::function(keep, protocol = SIZE_HINT)]
#[inline]
fn size_hint(&self) -> VmResult<(usize, Option<usize>)> {
self.value.protocol_size_hint()
}
#[rune::function(keep, protocol = LEN)]
#[inline]
fn len(&self) -> VmResult<usize> {
self.value.protocol_len()
}
}
pub(crate) trait CheckedOps: Sized {
const ONE: Self;
const ZERO: Self;
fn checked_add(self, value: Self) -> Option<Self>;
fn checked_mul(self, value: Self) -> Option<Self>;
}
impl CheckedOps for i64 {
const ONE: Self = 1;
const ZERO: Self = 0;
#[inline]
fn checked_add(self, value: Self) -> Option<Self> {
i64::checked_add(self, value)
}
#[inline]
fn checked_mul(self, value: Self) -> Option<Self> {
i64::checked_mul(self, value)
}
}
impl CheckedOps for u64 {
const ONE: Self = 1;
const ZERO: Self = 0;
#[inline]
fn checked_add(self, value: Self) -> Option<Self> {
u64::checked_add(self, value)
}
#[inline]
fn checked_mul(self, value: Self) -> Option<Self> {
u64::checked_mul(self, value)
}
}
impl CheckedOps for f64 {
const ONE: Self = 1.0;
const ZERO: Self = 0.0;
#[inline]
fn checked_add(self, value: Self) -> Option<Self> {
Some(self + value)
}
#[inline]
fn checked_mul(self, value: Self) -> Option<Self> {
Some(self * value)
}
}