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
use crate::structs::utility::InplaceUpdatable; use crate::structs::{ Chain, Cloned, Copied, Dedup, Enumerate, Filter, FilterMap, Flatten, Inspect, IteratorAdaptor, Map, Skip, SkipWhile, StepBy, Take, TakeWhile, Zip, }; use crate::traits::{FromGenerator, Product, Sum}; use crate::{Generator, GeneratorResult, TryReduction, ValueResult}; use core::cmp::Ordering; pub trait Sealed {} impl<T> Sealed for T where T: Generator {} /// Provides extension-methods for all generators. /// /// This allows generators to be composed to new generators, or consumed. /// /// ## Example /// ``` /// use pushgen::{SliceGenerator, GeneratorExt}; /// let data = [1, 2, 3, 4]; /// let mut output: Vec<i32> = Vec::new(); /// SliceGenerator::new(&data).map(|x| x*3).for_each(|x| output.push(x)); /// assert_eq!(output, [3,6,9,12]); /// ``` pub trait GeneratorExt: Sealed + Generator { /// Tests if every value from the generator matches a predicate. /// /// `all()` takes a closure that returns `true` or `false`. It applies this closure to each /// value generated by the generator, and if they all return `true`, then so does `all()`. If /// any value returns `false`, `all()` returns `false`. /// /// `all()` is short-circuiting; it will stop processing as soon as it finds a `false`. /// /// An empty generator returns true. /// /// ## Examples /// /// Basic usage: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [1, 2, 3]; /// assert!(a.into_gen().all(|&x| x > 0)); /// assert!(!a.into_gen().all(|&x| x > 2)); /// ``` /// /// Stopping at first false: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [1, 2, 3]; /// let mut gen = a.into_gen(); /// assert!(!gen.all(|&x| x != 2)); /// assert_eq!(gen.iter().next(), Some(&3)); /// ``` #[inline] fn all<F>(&mut self, mut predicate: F) -> bool where F: FnMut(Self::Output) -> bool, { let mut retval = true; self.run(|x| { if !predicate(x) { retval = false; ValueResult::Stop } else { ValueResult::MoreValues } }); retval } /// Tests if any value matches a predicate. /// /// `any()` takes a closure that returns `true` or `false`. It applies /// this closure to each value from the generator, 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 generator returns `false`. /// /// /// # Examples /// /// Basic usage: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [1, 2, 3]; /// /// assert!(a.into_gen().any(|&x| x > 0)); /// /// assert!(!a.into_gen().any(|&x| x > 5)); /// ``` /// /// Stopping at the first `true`: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [1, 2, 3]; /// /// let mut gen = a.into_gen(); /// /// assert!(gen.any(|&x| x != 2)); /// /// // we can still use `gen`, as there are more elements. /// assert_eq!(gen.iter().next(), Some(&2)); /// ``` #[inline] fn any<F>(&mut self, mut predicate: F) -> bool where F: FnMut(Self::Output) -> bool, { let mut retval = false; self.run(|x| { if predicate(x) { retval = true; ValueResult::Stop } else { ValueResult::MoreValues } }); retval } /// Retrieve the next value from the generator /// /// If the generator is completed or stopped before a value is retrieved an `Err(GeneratorResult)` /// with the status of the generator is returned. Otherwise an `Ok()` value is returned. /// /// ## Examples /// /// Basic usage: /// /// ``` /// use pushgen::{SliceGenerator, GeneratorExt, GeneratorResult}; /// let data = [1, 2]; /// let mut gen = SliceGenerator::new(&data); /// assert_eq!(gen.next(), Ok(&1)); /// assert_eq!(gen.next(), Ok(&2)); /// assert_eq!(gen.next(), Err(GeneratorResult::Complete)); /// ``` #[inline] fn next(&mut self) -> Result<Self::Output, GeneratorResult> { let mut maybe_value = None; let res = self.run(|x| { maybe_value = Some(x); ValueResult::Stop }); match maybe_value { Some(x) => Ok(x), None => Err(res), } } /// Exhausts the generator, returning the last element. /// /// This method will evaluate the generator until it completes. While /// doing so, it keeps track of the current element. After it completes /// `last()` will then return the last element it saw. /// /// # Examples /// /// Basic usage: /// /// ``` /// use pushgen::IntoGenerator; /// use pushgen::GeneratorExt; /// /// let a = [1, 2, 3]; /// assert_eq!(a.into_gen().last(), Some(&3)); /// /// let a = [1, 2, 3, 4, 5]; /// assert_eq!(a.into_gen().last(), Some(&5)); /// ``` #[inline] fn last(mut self) -> Option<Self::Output> where Self: Sized, { let mut res = None; let res_mut = &mut res; self.run(move |value| { *res_mut = Some(value); ValueResult::MoreValues }); res } /// Creates a generator that clones all of its elements. /// /// This is useful when you have a generator that generates `&T` but you need a generate /// that generates `T`. /// /// ## Examples /// /// Basic usage /// /// ```rust /// use pushgen::{SliceGenerator, GeneratorExt}; /// let data = [1, 2, 3]; /// let mut output: Vec<i32> = Vec::new(); /// SliceGenerator::new(&data).cloned().for_each(|x| output.push(x)); /// assert_eq!(output, [1, 2, 3]) /// ``` #[inline] fn cloned<'a, T>(self) -> Cloned<Self> where Self: Generator<Output = &'a T> + Sized, T: 'a + Clone, { Cloned::new(self) } /// Creates a generator that copies all of its elements. /// /// This is useful when you have a generator of `&T` but need a generator of `T`. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use pushgen::{SliceGenerator, GeneratorExt}; /// let data = [1, 2, 3]; /// let mut v_copied: Vec<_> = Vec::new(); /// SliceGenerator::new(&data).copied().for_each(|x| v_copied.push(x)); /// /// assert_eq!(v_copied, [1, 2, 3]); /// ``` #[inline] fn copied<'a, T>(self) -> Copied<Self> where T: 'a + Copy, Self: Generator<Output = &'a T> + Sized, { Copied::new(self) } /// Creates a generator by chaining two generators, running them one after the other. /// /// ## Example /// ``` /// use pushgen::{SliceGenerator, GeneratorExt}; /// let data = [1, 2, 3]; /// let mut output: Vec<i32> = Vec::new(); /// SliceGenerator::new(&data).chain(SliceGenerator::new(&data)).for_each(|x| output.push(*x)); /// assert_eq!(output, [1, 2, 3, 1, 2, 3]); /// ``` #[inline] fn chain<Gen>(self, other: Gen) -> Chain<Self, Gen> where Self: Sized, Gen: Generator<Output = Self::Output>, { Chain::new(self, other) } /// Create a filtered generator. Only values for which the predicate returns true will be passed on. /// /// The predicate must implement `FnMut(&Gen::Output) -> bool`. /// /// ## Example /// ``` /// # use pushgen::*; /// let input = [1,2,3,4]; /// let mut output: Vec<i32> = Vec::new(); /// let run_result = SliceGenerator::new(&input).filter(|x| *x % 2 == 0).for_each(|x| output.push(*x)); /// assert_eq!(run_result, GeneratorResult::Complete); /// assert_eq!(output, [2,4]); /// ``` #[inline] fn filter<Pred>(self, predicate: Pred) -> Filter<Self, Pred> where Self: Sized, Pred: FnMut(&Self::Output) -> bool, { Filter::new(self, predicate) } /// Creates a generator that both filters and maps. /// /// The returned generator produces 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`]: GeneratorExt::filter /// [`map`]: GeneratorExt::map /// /// # Examples /// /// Basic usage: /// /// ``` /// use pushgen::{SliceGenerator, GeneratorExt}; /// /// let a = ["1", "two", "NaN", "four", "5"]; /// /// let mut output: Vec<i32> = Vec::new(); /// SliceGenerator::new(&a).filter_map(|s| s.parse().ok()).for_each(|x: i32| output.push(x)); /// assert_eq!(output, [1, 5]); /// ``` /// /// Here's the same example, but with [`filter`] and [`map`]: /// /// ``` /// use pushgen::{SliceGenerator, GeneratorExt}; /// /// let a = ["1", "two", "NaN", "four", "5"]; /// /// let mut output: Vec<i32> = Vec::new(); /// SliceGenerator::new(&a).map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap()).for_each(|x: i32| output.push(x)); /// assert_eq!(output, [1, 5]); /// ``` #[inline] fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where Self: Sized, F: FnMut(Self::Output) -> Option<B>, { FilterMap::new(self, f) } /// Takes a closure and creates a generator which calls the closure on each value. /// /// ## Example /// ``` /// use pushgen::{SliceGenerator, GeneratorExt}; /// let data = [1, 2, 3]; /// let mut output: Vec<String> = Vec::new(); /// SliceGenerator::new(&data).map(|x| x.to_string()).for_each(|x| output.push(x)); /// assert_eq!(output, ["1", "2", "3"]); /// ``` #[inline] fn map<Trans, Out>(self, transform_fn: Trans) -> Map<Self, Trans> where Self: Sized, Trans: FnMut(Self::Output) -> Out, { Map::new(self, transform_fn) } /// Skips over `n` values, consuming and ignoring them. /// /// ## Example ///``` /// # use pushgen::{GeneratorExt, SliceGenerator}; /// # use pushgen::structs::Skip; /// let input = [1,2,3,4]; /// let mut skipped_generator = SliceGenerator::new(&input).skip(2); /// let mut output: Vec<i32> = Vec::new(); /// skipped_generator.for_each(|x| output.push(*x)); /// assert_eq!(output, [3,4]); /// ``` #[inline] fn skip(self, n: usize) -> Skip<Self> where Self: Sized, { Skip::new(self, n) } /// Creates a generator that skips values based on a predicate. /// /// `skip_while()` takes a closure as argument. It will call this closure on each value, /// and ignore values until the closure returns `false`. /// /// After `false` is returned, `skip_while()` will push the rest of the values. /// /// ## Examples /// /// Basic usage /// /// ```rust /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [-1i32, 0, 1]; /// let mut output = Vec::new(); /// a.into_gen().skip_while(|x| x.is_negative()).for_each(|x| output.push(x)); /// assert_eq!(output, [&0, &1]); /// ``` #[inline] fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where Self: Sized, P: FnMut(&Self::Output) -> bool, { SkipWhile::new(self, predicate) } /// Takes `n` values and then completes the generator. /// /// ## Example /// ``` /// use pushgen::{SliceGenerator, GeneratorExt}; /// let data = [1, 2, 3, 4]; /// let mut output: Vec<i32> = Vec::new(); /// SliceGenerator::new(&data).take(2).for_each(|x| output.push(*x)); /// assert_eq!(output, [1, 2]); /// ``` #[inline] fn take(self, n: usize) -> Take<Self> where Self: Sized, { Take::new(self, n) } /// Creates a generator that pushes values based on a predicate. /// /// `take_while()` takes a closure as an argument. It will call this closure on each value /// received from the source generator, and push values while it returns true. After `false` is /// returned, `take_while()`'s job is over and it will always report `Complete`. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [-1i32, 0, 1]; /// /// let mut gen_as_iter = a.into_gen().take_while(|x| x.is_negative()).iter(); /// /// assert_eq!(gen_as_iter.next(), Some(&-1)); /// assert_eq!(gen_as_iter.next(), None); /// ``` #[inline] fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where Self: Sized, P: FnMut(&Self::Output) -> bool, { TakeWhile::new(self, predicate) } /// Creates a generator 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 a generator 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`]: GeneratorExt::map /// [`flatten`]: GeneratorExt::flatten /// /// # Examples /// /// Basic usage: /// /// ``` /// use pushgen::IntoGenerator; /// use crate::pushgen::GeneratorExt; /// /// let words = ["alpha", "beta", "gamma"]; /// /// let mut merged = String::new(); /// words.into_gen() /// .flat_map(|s| pushgen::from_iter(s.chars())) /// .for_each(|x| merged.push(x)); /// assert_eq!(merged, "alphabetagamma"); /// ``` #[inline] fn flat_map<U, F>(self, f: F) -> Flatten<Map<Self, F>> where Self: Sized, U: crate::IntoGenerator, F: FnMut(Self::Output) -> U, { self.map(f).flatten() } /// Creates a generator that flattens nested structure. /// /// This is useful when you have a generator of generators or a generator of /// things that can be turned into generators and you want to remove one /// level of indirection. /// /// # Examples /// /// Basic usage: /// /// ``` /// use pushgen::IntoGenerator; /// use crate::pushgen::GeneratorExt; /// /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]]; /// let mut output: Vec<i32> = Vec::new(); /// let flattened = data.into_gen().flatten().for_each(|x| output.push(x)); /// assert_eq!(output, [1, 2, 3, 4, 5, 6]); /// ``` /// /// Mapping and then flattening: /// /// ``` /// use pushgen::IntoGenerator; /// use crate::pushgen::GeneratorExt; /// /// let words = &["alpha", "beta", "gamma"]; /// /// let mut merged = String::new(); /// words.into_gen() /// .map(|s| pushgen::from_iter(s.chars())) /// .flatten() /// .for_each(|x| merged.push(x)); /// assert_eq!(merged, "alphabetagamma"); /// ``` #[inline] fn flatten(self) -> Flatten<Self> where Self: Sized, Self::Output: crate::IntoGenerator, { Flatten::new(self) } /// Run a generator to completion, or until it is stopped, and call a closure for each value /// produced by the generator. /// /// The closure will be called for as long as the generator produces values, it is not possible /// to abort processing early. If early abort is needed, use [`Generator::run`](crate::Generator::run) /// ## Example /// ``` /// # use pushgen::{GeneratorExt, GeneratorResult, SliceGenerator}; /// let mut sum = 0i32; /// let data = [1,2,3]; /// let result = SliceGenerator::new(&data).for_each(|x| sum += x); /// assert_eq!(sum, 6); /// assert_eq!(result, GeneratorResult::Complete); /// ``` #[inline] fn for_each<Func>(&mut self, mut func: Func) -> GeneratorResult where Self: Sized, Func: FnMut(Self::Output), { self.run(move |value| { func(value); ValueResult::MoreValues }) } /// A generator method that applies a fallible function to each item /// produced, stopping at the first error and returning that error. /// /// This can also be thought of as the fallible form of [`for_each()`] /// or as the stateless version of [`try_fold()`]. /// /// [`for_each()`]: GeneratorExt::for_each /// [`try_fold()`]: GeneratorExt::try_fold /// /// # Examples /// /// ``` /// use std::fs::rename; /// use std::io::{stdout, Write}; /// use std::path::Path; /// use pushgen::{SliceGenerator, GeneratorExt}; /// /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"]; /// /// let res = SliceGenerator::new(&data).try_for_each(|x| writeln!(stdout(), "{}", x)); /// assert!(res.is_ok()); /// /// let mut gen = SliceGenerator::new(&data); /// let res = gen.try_for_each(|x| rename(x, Path::new(x).with_extension("old"))); /// assert!(res.is_err()); /// // It short-circuited, so the remaining items are still in the generator: /// let mut output: Vec<&'static str> = Vec::new(); /// gen.for_each(|x| output.push(*x)); /// assert_eq!(output, ["stale_bread.json", "torrential_rain.png"]); /// ``` #[inline] fn try_for_each<F, E>(&mut self, mut f: F) -> Result<(), E> where Self: Sized, F: FnMut(Self::Output) -> Result<(), E>, { let mut res = Ok(()); let res_mut = &mut res; self.run(move |value| match f(value) { Ok(()) => ValueResult::MoreValues, Err(e) => { *res_mut = Err(e); ValueResult::Stop } }); res } /// Zips the output of two generators into a single generator of pairs. /// /// `zip()` returns a new generator that will use values from two generators, outputting /// a tuple where the first element comes from the first generator, and the second element comes /// from the second generator. /// /// The zip generator will complete when either generator completes. /// /// ## Example /// ``` /// use pushgen::{SliceGenerator, GeneratorExt}; /// let left = [1, 2, 3]; /// let right = [4, 5, 6]; /// let mut output: Vec<(i32, i32)> = Vec::new(); /// SliceGenerator::new(&left).zip(SliceGenerator::new(&right)).for_each(|(a, b)| output.push((*a, *b))); /// assert_eq!(output, [(1,4), (2, 5), (3, 6)]); /// ``` #[inline] fn zip<Right>(self, right: Right) -> Zip<Self, Right> where Self: Sized, Right: Generator, { Zip::new(self, right) } /// Create a de-duplicating generator, removing consecutive duplicate values. /// /// Values will be made available when a non-duplicate is detected. If the up-stream generator generates /// the following sequence: `[1, 2, 3, 3, 4]` then the value `1` will be generated from the /// `Dedup` generator once the value `2` has been generated by the upstream generator and so /// on. /// /// | Upstream value | Dedup-generated value | /// |----------------|-----------------------| /// | 1 | *None* | /// | 2 | 1 | /// | 3 | 2 | /// | 3 | *Ignored* | /// | 4 | 3 | /// | *Complete* | 4 | /// | *Complete* | *Complete* | /// /// ## Example /// ``` /// # use pushgen::{SliceGenerator, GeneratorExt}; /// let data = [1, 2, 3, 3, 3, 3, 4, 3]; /// let mut output: Vec<i32> = Vec::new(); /// SliceGenerator::new(&data).dedup().for_each(|x| output.push(*x)); /// assert_eq!(output, [1, 2, 3, 4, 3]); /// ``` #[inline] fn dedup(self) -> Dedup<Self> where Self: Sized, Self::Output: PartialEq, { Dedup::new(self) } /// Create an iterator from a generator. /// /// This allows generators to be used in basic for-loops. /// /// ## Example /// ``` /// use pushgen::{SliceGenerator, GeneratorExt}; /// let data = [1, 2, 3, 4, 5, 6]; /// let mut sum = 0; /// for x in SliceGenerator::new(&data).iter() { /// sum += x; /// } /// assert_eq!(sum, data.iter().sum()); /// ``` #[inline] fn iter(self) -> IteratorAdaptor<Self> where Self: Sized, { IteratorAdaptor::new(self) } /// Create a generator that starts at the same point but steps by the given amount. /// /// Note 1: The first value will always be generated, regardless of the step given /// /// ## Panics /// /// The method will panic if given a step size of `0` /// /// ## Examples /// /// Basic usage: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt, GeneratorResult}; /// let a = [0, 1, 2, 3, 4, 5]; /// let mut gen = a.into_gen().step_by(2); /// /// assert_eq!(gen.next(), Ok(&0)); /// assert_eq!(gen.next(), Ok(&2)); /// assert_eq!(gen.next(), Ok(&4)); /// assert_eq!(gen.next(), Err(GeneratorResult::Complete)); /// ``` #[inline] fn step_by(self, step_size: usize) -> StepBy<Self> where Self: Sized, { StepBy::new(self, step_size) } /// Box a generator, making it possible to use as return value in for instance traits. /// /// ## Performance /// This causes at least one layer of redirection, which is very likely to impact performance. /// One should always prefer to use `impl Generator<Output=X>` instead. /// /// ## Example /// ```rust /// use pushgen::{generators::BoxedGenerator, IntoGenerator, GeneratorExt}; /// fn make_generator() -> BoxedGenerator<i32> { /// vec![1, 2, 3, 4].into_gen().map(|x| x*2).boxed() /// } /// let mut output = Vec::new(); /// make_generator().for_each(|x| output.push(x)); /// assert_eq!(output, [2, 4, 6, 8]); /// ``` #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] #[inline] fn boxed(self) -> crate::generators::BoxedGenerator<Self::Output> where Self: Sized + 'static, { crate::generators::BoxedGenerator::new(self) } /// Sums the values of a generator. Takes each value and adds them together and returns /// the result. /// /// An empty generator returns the zero value of the type. /// /// ## Spuriously stopping generators /// /// `sum()` only sums the values up until the source generator is first stopped. If the source /// generator is not completed, but stops mid-generation for some reason, only the values up /// until the first stop are summed. /// /// ## Panics /// /// When calling `sum()` and a primitive integer type is being returned, /// this method will panic if the computation overflows and debug assertions are enabled. /// /// ## Examples /// /// Basic usage: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [1, 2, 3]; /// let sum: i32 = a.into_gen().sum(); /// /// assert_eq!(sum, 6); /// ``` /// #[inline] fn sum<S>(self) -> S where Self: Sized, S: Sum<Self::Output>, { S::sum(self) } /// Multiplies the values of a generator. Takes each value and adds them together and returns /// the result. /// /// An empty generator returns the one value of the type. /// /// ## Spuriously stopping generators /// /// `product()` only multiplies the values up until the source generator is first stopped. If the source /// generator is not completed, but stops mid-generation for some reason, only the values up /// until the first stop are multiplied. /// /// ## Panics /// /// When calling `product()` and a primitive integer type is being returned, /// this method will panic if the computation overflows and debug assertions are enabled. /// /// ## Examples /// /// Basic usage: /// /// ``` /// use pushgen::{GeneratorExt, from_iter}; /// fn factorial(n: u32) -> u32 { /// // Create a generator from an iterable /// from_iter((1..=n)).product() /// } /// /// assert_eq!(factorial(0), 1); /// assert_eq!(factorial(1), 1); /// assert_eq!(factorial(5), 120); /// ``` /// #[inline] fn product<P>(self) -> P where Self: Sized, P: Product<Self::Output>, { P::product(self) } /// Returns the minimum value of a generator. /// /// If several elements are equally minimum, the first element is /// returned. If the generator is empty, [`None`] is returned. /// /// ## Spuriously stopping generators /// /// `min()` will return the result after the source generator has stopped. It doesn't matter /// if the source generator is stopped or completed. /// /// Use [`try_min_by()`] to handle spuriously stopping generators. /// /// [`try_min_by()`]: GeneratorExt::try_min_by /// /// # Examples /// /// Basic usage: /// /// ``` /// use pushgen::{GeneratorExt, IntoGenerator}; /// let a = [1, 2, 3]; /// let b: Vec<u32> = Vec::new(); /// /// assert_eq!(a.into_gen().min(), Some(&1)); /// assert_eq!(b.into_gen().min(), None); /// ``` #[inline] fn min(self) -> Option<Self::Output> where Self: Sized, Self::Output: Ord, { self.min_by(Ord::cmp) } /// Returns the value that gives the minimum value when compared with the /// specified comparison function. /// /// If several elements are equally minimum, the first element is /// returned. If the generator is empty, [`None`] is returned. /// /// ## Spuriously stopping generators /// /// `min_by()` will return the result after the source generator has stopped. It doesn't matter /// if the source generator is stopped or completed. /// /// Use [`try_min_by()`] to handle spuriously stopping generators. /// /// [`try_min_by()`]: GeneratorExt::try_min_by /// /// # Examples /// /// ``` /// use pushgen::{GeneratorExt, IntoGenerator}; /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(*a.into_gen().min_by(|x, y| x.cmp(y)).unwrap(), -10); /// ``` #[inline] fn min_by<F>(self, mut compare: F) -> Option<Self::Output> where Self: Sized, F: FnMut(&Self::Output, &Self::Output) -> Ordering, { self.reduce(|a, b| core::cmp::min_by(a, b, &mut compare)) } /// Returns the value that gives the minimum value when compared with the /// specified comparison function. /// /// If several elements are equally minimum, the first element is /// returned. If the generator is empty, `None` is returned. /// /// This method can be used with spuriously stopping generators. /// /// # Examples /// /// Basic usage /// /// ``` /// use pushgen::{GeneratorExt, IntoGenerator}; /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(a.into_gen().try_min_by(None, |x, y| x.cmp(y)).unwrap(), Some(&-10)); /// ``` /// /// Stopping generator: /// /// ``` /// use pushgen::{Generator, ValueResult, GeneratorResult, GeneratorExt}; /// use pushgen::test::StoppingGen; /// let data = [1, 2, 0, 4]; /// let mut gen = StoppingGen::new(1, &data); /// let partial = gen.try_min_by(None, Ord::cmp); /// // generator was stopped - indicated by a Partial reduction. /// assert!(partial.is_partial()); /// let partial = partial.unwrap(); /// assert_eq!(partial, Some(&1)); /// // Feed partial value to continue reduction from the partial value /// let res = gen.try_min_by(partial, Ord::cmp); /// assert!(res.is_complete()); /// assert_eq!(res.unwrap(), Some(&0)); /// ``` #[inline] fn try_min_by<F>( &mut self, partial: Option<Self::Output>, mut compare: F, ) -> TryReduction<Option<Self::Output>> where Self: Sized, F: FnMut(&Self::Output, &Self::Output) -> Ordering, { self.try_reduce(partial, |a, b| core::cmp::min_by(a, b, &mut compare)) } /// Returns the value that gives the minimum value from the specified function. /// /// If several elements are equally minimum, the first element is /// returned. If the generator is empty, `None` is returned. /// /// ## Spuriously stopping generators /// /// `min_by_key()` will return the result after the source generator has stopped. It doesn't matter /// if the source generator is stopped or completed. /// /// Manually use [`try_min_by()`] to handle spuriously stopping generators. /// /// [`try_min_by()`]: GeneratorExt::try_min_by /// /// # Examples /// /// ``` /// use pushgen::{GeneratorExt, IntoGenerator}; /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(*a.into_gen().min_by_key(|x| x.abs()).unwrap(), 0); /// ``` #[inline] fn min_by_key<F, B>(self, f: F) -> Option<Self::Output> where Self: Sized, F: FnMut(&Self::Output) -> B, B: Ord, { #[inline] fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) { move |x| (f(&x), x) } #[inline] fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering { x_p.cmp(y_p) } let (_, x) = self.map(key(f)).min_by(compare)?; Some(x) } /// Returns the maximum value of a generator. /// /// If several elements are equally maximum, the last element is /// returned. If the generator is empty, [`None`] is returned. /// /// ## Spuriously stopping generators /// /// `max()` will return the result after the source generator has stopped. It doesn't matter /// if the source generator is stopped or completed. /// /// Use [`try_max_by()`] to handle spuriously stopping generators. /// /// [`try_max_by()`]: GeneratorExt::try_max_by /// /// # Examples /// /// Basic usage: /// /// ``` /// use pushgen::{GeneratorExt, IntoGenerator}; /// let a = [1, 2, 3]; /// let b: Vec<u32> = Vec::new(); /// /// assert_eq!(a.into_gen().max(), Some(&3)); /// assert_eq!(b.into_gen().max(), None); /// ``` #[inline] fn max(self) -> Option<Self::Output> where Self: Sized, Self::Output: Ord, { self.max_by(Ord::cmp) } /// Returns the value that gives the maximum value when compared with the /// specified comparison function. /// /// If several elements are equally maximum, the last element is /// returned. If the generator is empty, `None` is returned. /// /// ## Spuriously stopping generators /// /// `max_by()` will return the result after the source generator has stopped. It doesn't matter /// if the source generator is stopped or completed. /// /// Manually use [`try_max_by()`] to handle spuriously stopping generators. /// /// [`try_max_by()`]: GeneratorExt::try_max_by /// /// # Examples /// /// ``` /// use pushgen::{GeneratorExt, IntoGenerator}; /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(*a.into_gen().max_by(|x, y| x.cmp(y)).unwrap(), 5); /// ``` #[inline] fn max_by<F>(self, mut compare: F) -> Option<Self::Output> where Self: Sized, F: FnMut(&Self::Output, &Self::Output) -> Ordering, { self.reduce(|a, b| core::cmp::max_by(a, b, &mut compare)) } /// Returns the value that gives the maximum value when compared with the /// specified comparison function. /// /// If several elements are equally maximum, the last element is /// returned. If the generator is empty, [`None`] is returned. /// /// This method can be used with spuriously stopping generators. /// /// # Examples /// /// Basic usage /// /// ``` /// use pushgen::{GeneratorExt, IntoGenerator}; /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(a.into_gen().try_min_by(None, |x, y| x.cmp(y)).unwrap(), Some(&-10)); /// ``` /// /// Stopping generator: /// /// ``` /// use pushgen::{Generator, ValueResult, GeneratorResult, GeneratorExt}; /// use pushgen::test::StoppingGen; /// let data = [1, 2, 0, 4]; /// let mut gen = StoppingGen::new(1, &data); /// let partial = gen.try_max_by(None, Ord::cmp); /// // generator was stopped - indicated by a Partial reduction. /// assert!(partial.is_partial()); /// let partial = partial.unwrap(); /// assert_eq!(partial, Some(&1)); /// // Feed partial value to continue from the partial value /// let res = gen.try_max_by(partial, Ord::cmp); /// assert!(res.is_complete()); /// assert_eq!(res.unwrap(), Some(&4)); /// ``` #[inline] fn try_max_by<F>( &mut self, partial: Option<Self::Output>, mut compare: F, ) -> TryReduction<Option<Self::Output>> where Self: Sized, F: FnMut(&Self::Output, &Self::Output) -> Ordering, { self.try_reduce(partial, |a, b| core::cmp::max_by(a, b, &mut compare)) } /// Returns the value that gives the maximum value from the specified function. /// /// If several elements are equally maximum, the last element is /// returned. If the generator is empty, [`None`] is returned. /// /// ## Spuriously stopping generators /// /// `max_by_key()` will return the result after the source generator has stopped. It doesn't matter /// if the source generator is stopped or completed. /// /// Manually use [`try_max_by()`] to handle spuriously stopping generators. /// /// [`try_max_by()`]: GeneratorExt::try_max_by() /// /// # Examples /// /// ``` /// use pushgen::{GeneratorExt, IntoGenerator}; /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(*a.into_gen().max_by_key(|x| x.abs()).unwrap(), -10); /// ``` #[inline] fn max_by_key<F, B>(self, f: F) -> Option<Self::Output> where Self: Sized, F: FnMut(&Self::Output) -> B, B: Ord, { #[inline] fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) { move |x| (f(&x), x) } #[inline] fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering { x_p.cmp(y_p) } let (_, x) = self.map(key(f)).max_by(compare)?; Some(x) } /// Folds every element into an accumulator by applying an operation, returning the final result. /// /// Folding is useful whenever you have a collection of something, and want to produce a single /// value from it. /// /// Note: [`reduce()`] can be used to use the first value as the initial value, if the accumulator /// type and the output type is the same. /// /// [`reduce()`]: GeneratorExt::reduce /// /// ## Spuriously stopping generators /// /// `fold()` will stop and return the result after the first stop of the generator. It doesn't /// matter if the generator stopped or completed. /// /// Use [`try_fold()`] to correctly handle spuriously stopping generators. /// /// [`try_fold()`]: GeneratorExt::try_fold /// /// ## Arguments /// /// `init` The initial accumulator value /// /// `folder` A closure that takes an accumulator value and a generated value and returns a new /// accumulator value. /// /// ## Examples /// /// Basic usage: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [1, 2, 3]; /// /// // the sum of all of the elements of the array /// let sum = a.into_gen().fold(0, |acc, x| acc + x); /// /// assert_eq!(sum, 6); /// ``` #[inline] fn fold<B, F>(mut self, init: B, mut folder: F) -> B where Self: Sized, F: FnMut(B, Self::Output) -> B, { let mut value = InplaceUpdatable::new(init); self.for_each(|x| { value.update(|acc| folder(acc, x)); }); value.get_inner() } /// Apply a function as long as the return value is successful, producing a single final value. /// /// `try_fold()` takes two arguments: an initial value, and a closure with two arguments: /// an ‘accumulator’, and a value. /// The closure either returns successfully, with the value that the accumulator should have for /// the next iteration, or it returns failure, with an error value that is propagated back to /// the caller immediately (short-circuiting). /// /// The return value from `try_fold()` can distinguish between 3 different return-conditions: /// /// * `Ok(Reduction::Complete(B))` -> the generator has completed and produced a final value. /// * `Ok(Reduction::Partial(B))` -> the generator spuriously stopped early. /// Later `try_fold` calls should use the partial value as `init`. /// * `Err(E)` -> The provided closure returned an error. /// /// ## Examples /// /// Basic usage: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt, TryReduction}; /// let a = [1, 2, 3]; /// /// // the checked sum of all of the elements of the array /// let sum = a.into_gen().try_fold(0i8, |acc, &x| acc.checked_add(x).ok_or(())); /// /// assert_eq!(sum, Ok(TryReduction::Complete(6))); /// ``` /// /// Short circuiting: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt, TryReduction, GeneratorResult}; /// let a = [10, 20, 30, 100, 40, 50]; /// let mut gen = a.into_gen(); /// /// // This sum overflows when adding the 100 element /// let sum = gen.try_fold(0i8, |acc, &x| acc.checked_add(x).ok_or(())); /// assert_eq!(sum, Err(())); /// /// // Because it short-circuited, the remaining elements are still /// // available through the iterator. /// assert_eq!(gen.next(), Ok(&40)); /// assert_eq!(gen.next(), Ok(&50)); /// assert_eq!(gen.next(), Err(GeneratorResult::Complete)); /// ``` /// #[inline] fn try_fold<B, F, E>(&mut self, init: B, mut folder: F) -> Result<TryReduction<B>, E> where Self: Sized, F: FnMut(B, Self::Output) -> Result<B, E>, { let mut acc = InplaceUpdatable::new(Ok(init)); let run_result = self.run(|x| { acc.update_with_result(|prev_acc| match prev_acc { Ok(prev_acc) => match folder(prev_acc, x) { Ok(x) => (Ok(x), ValueResult::MoreValues), err => (err, ValueResult::Stop), }, err => (err, ValueResult::Stop), }) }); match acc.get_inner() { Ok(value) => { if run_result == GeneratorResult::Complete { Ok(TryReduction::Complete(value)) } else { Ok(TryReduction::Partial(value)) } } Err(err) => Err(err), } } /// Reduces the elements to a single one by repeatedly applying a reducing operation. /// /// ## Returns /// /// `None` if the generator is empty, otherwise the result of the reduction. /// /// ## Spuriously stopping generators /// /// Reduce will return the result after the source generator has stopped. It doesn't matter /// if the source generator is stopped or completed. /// /// Use [`try_reduce`] to reduce spuriously stopping generators. /// /// [`try_reduce`]: GeneratorExt::try_reduce /// /// ## Example /// /// Find the maximum value: /// /// ``` /// use pushgen::{Generator, GeneratorExt, IntoGenerator}; /// fn find_max<G>(gen: G) -> Option<G::Output> /// where G: Generator, /// G::Output: Ord, /// { /// gen.reduce(|a, b| { /// if a >= b { a } else { b } /// }) /// } /// let a = [10, 20, 5, -23, 0]; /// let b: [u32; 0] = []; /// /// assert_eq!(find_max(a.into_gen()), Some(&20)); /// assert_eq!(find_max(b.into_gen()), None); /// ``` /// #[inline] fn reduce<F>(mut self, mut reducer: F) -> Option<Self::Output> where Self: Sized, F: FnMut(Self::Output, Self::Output) -> Self::Output, { let mut left_value = crate::structs::utility::InplaceUpdatable::new(self.next().ok()?); self.run(|x| { left_value.inplace_reduce(x, &mut reducer); ValueResult::MoreValues }); Some(left_value.get_inner()) } /// Reduces the values to a single value by repeatedly applying a reducing operation. /// /// Use this reduction if the generator is known to spuriously stop mid-stream. Otherwise /// it is better to use [`reduce()`]. /// /// [`reduce()`]: GeneratorExt::reduce /// /// ## Arguments /// /// `prev_reduction` The result of an earlier incomplete reduction. Set to `None` if this is the /// first reduction pass. /// /// `reducer` The reducing closure to use. /// /// ## Returns /// /// `Ok(x)` if the generator was run to completion. `x` is `None` if the generator is empty, /// otherwise it is the result of the complete reduction. /// /// `Err(y)` if the generator was stopped mid-reduction. `y` is the value that the generator was /// reduced to when it stopped. This value should be used in any subsequent calls to `try_reduce` /// until an `Ok()` value is returned. /// /// ## Example /// /// Find the maximum value: /// /// ``` /// use pushgen::{Generator, GeneratorExt, IntoGenerator, TryReduction}; /// fn find_max<G>(gen: &mut G) -> TryReduction<Option<G::Output>> /// where G: Generator, /// G::Output: Ord, /// { /// gen.try_reduce(None, |a, b| { /// if a >= b { a } else { b } /// }) /// } /// let a = [10, 20, 5, -23, 0]; /// let b: [u32; 0] = []; /// /// assert_eq!(find_max(&mut a.into_gen()).unwrap(), Some(&20)); /// assert_eq!(find_max(&mut b.into_gen()).unwrap(), None); /// ``` /// /// With a stopping generator: /// /// ``` /// use pushgen::{Generator, ValueResult, GeneratorResult, GeneratorExt}; /// use pushgen::test::StoppingGen; // Available with feature `test` /// let data = [1, 2, 3, 0, 4, 5]; /// let mut gen = StoppingGen::new(1, &data).copied(); /// let partial = gen.try_reduce(None, |a, b| a + b); /// assert!(partial.is_partial()); /// let partial = partial.unwrap(); /// assert_eq!(partial, Some(1)); /// let res = gen.try_reduce(partial, |a, b| a + b); /// assert!(res.is_complete()); /// assert_eq!(res.unwrap(), Some(1+2+3+4+5)); /// ``` /// #[inline] fn try_reduce<F>( &mut self, prev_reduction: Option<Self::Output>, mut reducer: F, ) -> TryReduction<Option<Self::Output>> where Self: Sized, F: FnMut(Self::Output, Self::Output) -> Self::Output, { let left_value = { if let Some(prev) = prev_reduction { prev } else { // Grab the first item into an optional let first = self.next(); match first { Ok(first) => first, Err(GeneratorResult::Stopped) => return TryReduction::Partial(None), Err(GeneratorResult::Complete) => return TryReduction::Complete(None), } } }; let mut left_value = crate::structs::utility::InplaceUpdatable::new(left_value); let run_result = self.run(|x| { left_value.inplace_reduce(x, &mut reducer); ValueResult::MoreValues }); let result = Some(left_value.get_inner()); match run_result { GeneratorResult::Stopped => TryReduction::Partial(result), GeneratorResult::Complete => TryReduction::Complete(result), } } /// Transforms a generator into a collection. /// /// `collect()` can take any generator and turn it into a relevant collection. /// /// ## Spuriously stopping generators /// /// Collect will stop collecting values as soon as the generator is stopped. It doesn't matter /// if the generator was completed or not. /// /// To handle spuriously stopping generators one should manually do the collecting with for instance /// [`for_each()`](GeneratorExt::for_each). /// /// ## Examples /// /// Basic usage: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [1, 2, 3]; /// /// let doubled: Vec<i32> = a.into_gen() /// .map(|&x| x * 2) /// .collect(); /// /// assert_eq!(vec![2, 4, 6], doubled); /// ``` /// #[inline] fn collect<B>(self) -> B where Self: Sized, B: FromGenerator<Self::Output>, { B::from_gen(self) } /// Creates a generator which gives the current generation count as well as the value. /// /// The generator generates `(i, val)` values, where `i` is the current index of the value and /// `val` is the current value. /// /// ## Overflow behaviour /// /// The method does not guard against overflows, so enumerating more than `usize::MAX` values /// will either produce the wrong result or panic. /// /// ## Panics /// /// The generator might panic if the index overflows a `usize`. /// /// ## Examples /// /// Basic usage: /// /// ``` /// use pushgen::{SliceGenerator, GeneratorExt, GeneratorResult}; /// let data = ['a', 'b', 'c']; /// /// let mut gen = SliceGenerator::new(&data).enumerate(); /// assert_eq!(gen.next(), Ok((0, &'a'))); /// assert_eq!(gen.next(), Ok((1, &'b'))); /// assert_eq!(gen.next(), Ok((2, &'c'))); /// assert_eq!(gen.next(), Err(GeneratorResult::Complete)); /// ``` #[inline] fn enumerate(self) -> Enumerate<Self> where Self: Sized, { Enumerate::new(self) } /// Does something with each value from the generator, passing the value on. /// /// This is useful if you want to inspect a value in the middle of a pipeline, for instance to /// add debug output. /// /// ## Example /// /// Basic usage: /// /// ``` /// use pushgen::{IntoGenerator, GeneratorExt}; /// let a = [1, 4, 2, 3]; /// /// // this iterator sequence is complex. /// let sum = a.into_gen() /// .cloned() /// .filter(|x| x % 2 == 0) /// .fold(0, |sum, i| sum + i); /// /// println!("{}", sum); /// /// // let's add some inspect() calls to investigate what's happening /// let sum = a.into_gen() /// .cloned() /// .inspect(|x| println!("about to filter: {}", x)) /// .filter(|x| x % 2 == 0) /// .inspect(|x| println!("made it through filter: {}", x)) /// .fold(0, |sum, i| sum + i); /// /// println!("{}", sum); /// ``` /// /// This will print /// /// ```text /// 6 /// about to filter: 1 /// about to filter: 4 /// made it through filter: 4 /// about to filter: 2 /// made it through filter: 2 /// about to filter: 3 /// 6 /// ``` #[inline] fn inspect<F>(self, inspector: F) -> Inspect<Self, F> where Self: Sized, F: FnMut(&Self::Output), { Inspect::new(self, inspector) } } impl<T: Generator> GeneratorExt for T {} #[cfg(test)] mod tests { use crate::test::StoppingGen; use crate::{ Generator, GeneratorExt, GeneratorResult, IntoGenerator, TryReduction, ValueResult, }; #[test] fn for_each_stopped() { struct StoppingGen; impl Generator for StoppingGen { type Output = i32; fn run(&mut self, _output: impl FnMut(Self::Output) -> ValueResult) -> GeneratorResult { GeneratorResult::Stopped } } let mut gen = StoppingGen; assert_eq!(gen.for_each(|_| ()), GeneratorResult::Stopped); } #[test] fn empty_all() { let data: [i32; 0] = []; assert!(data.into_gen().all(|_| false)); } #[test] fn basic_all() { let data = [1, 2, 2]; assert!(data.into_gen().all(|&x| x > 0)); assert!(!data.into_gen().all(|&x| x > 2)); } #[test] fn shortcircuit_all() { let data = [1, 2, 3]; let mut gen = data.into_gen(); assert!(!gen.all(|&x| x != 2)); assert_eq!(gen.iter().next(), Some(&3)); } #[test] fn empty_any() { let data: [i32; 0] = []; assert!(!data.into_gen().any(|_| true)); } #[test] fn empty_reduce() { let x: [i32; 0] = []; fn reducer(a: i32, b: i32) -> i32 { a + b } assert_eq!( x.iter().copied().reduce(reducer), x.into_gen().copied().reduce(reducer) ); } #[test] fn single_element_reduce() { let x = [1i32]; fn reducer(a: i32, b: i32) -> i32 { a + b } assert_eq!( x.iter().copied().reduce(reducer), x.into_gen().copied().reduce(reducer) ); } #[test] fn two_element_reduce() { let x = [1i32, 2]; fn reducer(a: i32, b: i32) -> i32 { a + b } assert_eq!( x.iter().copied().reduce(reducer), x.into_gen().copied().reduce(reducer) ); } #[test] fn empty_try_reduce() { let x: [i32; 0] = []; fn reducer(a: i32, b: i32) -> i32 { a + b } assert_eq!( x.into_gen().copied().try_reduce(None, reducer), TryReduction::Complete(None) ); } #[test] fn single_element_try_reduce() { let x = [1i32]; fn reducer(a: i32, b: i32) -> i32 { a + b } assert_eq!( x.into_gen().copied().try_reduce(None, reducer), TryReduction::Complete(Some(1)) ); } #[test] fn two_element_try_reduce() { let x = [1i32, 2]; fn reducer(a: i32, b: i32) -> i32 { a + b } assert_eq!( x.into_gen().copied().try_reduce(None, reducer), TryReduction::Complete(Some(3)) ); } #[test] fn stop_at_start_try_reduce() { for i in 0..4 { let x = [1, 2, 3, 4, 5]; let mut gen = StoppingGen::new(i, &x); let res = gen.try_reduce(None, |a, b| match a < b { true => a, false => b, }); assert!(res.is_partial()); let partial = res.unwrap(); if i == 0 { assert_eq!(partial, None); } else { assert_eq!(partial, Some(&1)); } match gen.try_reduce(partial, |a, b| if a < b { a } else { b }) { TryReduction::Complete(x) => assert_eq!(x, Some(&1)), TryReduction::Partial(_) => { assert!(false); } } } } #[test] fn double_stop_try_reduce() { struct Gen { index: usize, num_stops: u32, } impl Generator for Gen { type Output = i32; fn run( &mut self, mut output: impl FnMut(Self::Output) -> ValueResult, ) -> GeneratorResult { static DATA: [i32; 4] = [0, 1, 2, 3]; while self.index < DATA.len() { if self.index == 2 { if self.num_stops < 2 { self.num_stops += 1; return GeneratorResult::Stopped; } } let old = self.index; self.index += 1; if output(DATA[old]) == ValueResult::Stop { return GeneratorResult::Stopped; } } GeneratorResult::Complete } } let mut gen = Gen { index: 0, num_stops: 0, }; let result = gen.try_reduce(None, |a, b| a + b); assert!(result.is_partial()); let partial = result.unwrap(); assert_eq!(partial, Some(0 + 1)); let result = gen.try_reduce(partial, |a, b| a + b); assert!(result.is_partial()); let partial = result.unwrap(); assert_eq!(partial, Some(0 + 1)); let result = gen.try_reduce(partial, |a, b| a + b); assert!(result.is_complete()); assert_eq!(result.unwrap(), Some(0 + 1 + 2 + 3)); } #[test] fn spuriously_stopping_try_fold() { let data = [0i32, 1, 2, 3]; for x in 0..4 { let mut gen = StoppingGen::new(x, &data); let partial = gen .try_fold(0i32, |acc, x| x.checked_add(acc).ok_or(())) .unwrap(); assert!(partial.is_partial()); let final_value = gen .try_fold(partial.unwrap(), |acc, x| x.checked_add(acc).ok_or(())) .unwrap(); assert_eq!(final_value, TryReduction::Complete(6)); } } #[test] fn collect_vec() { let data = [0, 1, 2, 3, 4]; let out: Vec<i32> = data.into_gen().filter(|x| *x % 2 == 0).copied().collect(); assert_eq!(out, [0, 2, 4]); } #[test] fn collect_string() { let data = ['a', 'B', 'c', 'D']; let out: String = data .into_gen() .filter(|x| x.is_uppercase()) .copied() .collect(); assert_eq!(out, "BD"); let data = ['f', 'G', 'H', 'i']; let out: String = data.into_gen().filter(|x| x.is_uppercase()).collect(); assert_eq!(out, "GH"); } }