cantrip 0.5.0

Practical extension methods for standard Rust collections
Documentation
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
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
use std::hash::Hash;
use std::iter;

use crate::core::unfold::unfold;

pub(crate) const MAX_SIZE: usize = usize::MAX / 2 - 1;

/// Sequence operations.
///
/// Methods have the following properties:
///
/// - Requires the collection to represent a sequence
/// - May consume the sequence and its elements
/// - May create a new sequence
pub trait SequenceTo<Item>
where
  for<'i> &'i Self: IntoIterator<Item = &'i Item>,
{
  /// This sequence type constructor
  type This<I>;

  /// Creates a new sequence by inserting an element into the specified index
  /// in this sequence.
  ///
  /// If the specified index exceeds this sequence size, no elements are inserted.
  ///
  /// # Panics
  ///
  /// Panics if `index` is out of bounds.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.add_at(0, 4), vec![4, 1, 2, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.add_at(1, 4), vec![1, 4, 2, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.add_at(3, 4), vec![1, 2, 3, 4]);
  ///
  /// assert_eq!(e.add_at(0, 1), vec![1]);
  /// ```
  #[must_use]
  fn add_at(self, index: usize, element: Item) -> Self;

  /// Creates a new sequence by inserting all elements of another collection
  /// into the specified index in this sequence.
  ///
  /// If the specified index exceeds this sequence size, no elements are inserted.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.add_at_multi(0, vec![4, 5]), vec![4, 5, 1, 2, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.add_at_multi(1, vec![4, 5]), vec![1, 4, 5, 2, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.add_at_multi(3, vec![4, 5]), vec![1, 2, 3, 4, 5]);
  ///
  /// assert_eq!(e.add_at_multi(0, vec![1, 2]), vec![1, 2]);
  /// ```
  #[must_use]
  fn add_at_multi(self, index: usize, elements: impl IntoIterator<Item = Item>) -> Self;

  /// Creates a new sequence containing tuples for k-fold cartesian product of specified size
  /// from the elements of this sequence.
  ///
  /// Members are generated based on element positions, not values.
  /// Therefore, if this sequence contains duplicate elements, the resulting tuples will too.
  /// To obtain cartesian product of unique elements, use [`unique()`]`.cartesian_product()`.
  ///
  /// The order or tuple values is preserved.
  ///
  /// [`unique()`]: SequenceTo::unique
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.cartesian_product(0), vec![vec![]]);
  /// assert_eq!(a.cartesian_product(1), vec![vec![1], vec![2], vec![3]]);
  /// assert_eq!(a.cartesian_product(2), vec![
  ///   vec![1, 1],
  ///   vec![1, 2],
  ///   vec![1, 3],
  ///   vec![2, 1],
  ///   vec![2, 2],
  ///   vec![2, 3],
  ///   vec![3, 1],
  ///   vec![3, 2],
  ///   vec![3, 3],
  /// ]);
  ///
  /// assert_eq!(e.cartesian_product(2), Vec::<Vec<i32>>::new());
  /// ```
  #[allow(clippy::cast_possible_wrap)]
  #[must_use]
  fn cartesian_product(&self, k: usize) -> Vec<Self>
  where
    Self: FromIterator<Item> + Sized,
    Item: Clone,
  {
    assert!(k <= MAX_SIZE, "k (is {k:?}) should be <= {MAX_SIZE:?})");
    let values = self.into_iter().collect::<Vec<_>>();
    let size = values.len();
    let mut product = iter::once(i64::MIN).chain(iter::repeat_n(0, k)).collect::<Vec<_>>();
    let mut current_slot = (size + 1).saturating_sub(k);
    unfold(|| {
      if current_slot == 0 {
        return None;
      }
      current_slot = k;
      let tuple = Some(collect_by_index(&values, &product[1..]));
      while product[current_slot] >= (size - 1) as i64 {
        current_slot -= 1;
      }
      product[current_slot] += 1;
      for index in &mut product[(current_slot + 1)..=k] {
        *index = 0;
      }
      tuple
    })
    .collect()
  }

  /// Creates a new sequence by splitting elements of this sequence
  /// into non-overlapping subsequences of specified `size`.
  ///
  /// The chunks are sequences and do not overlap. If `size` does not divide
  /// the length of the slice, then the last chunk will not have length `size`.
  ///
  /// See [`chunked_exact()`] for a variant of this function that returns chunks of
  /// always exactly `chunk_size` elements.
  ///
  /// [`chunked_exact()`]: SequenceTo::chunked_exact
  ///
  /// # Panics
  ///
  /// Panics if chunk `size` is 0.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.chunked(2), vec![vec![1, 2], vec![3]]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.chunked(3), vec![vec![1, 2, 3]]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.chunked(1), vec![vec![1], vec![2], vec![3]]);
  /// ```
  #[inline]
  #[must_use]
  fn chunked(self, size: usize) -> Vec<Self>
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    chunked(self, size, false)
  }

  /// Creates a new sequence by splitting this sequence into non-overlapping
  /// subsequences according to the specified separator predicate.
  ///
  /// The `split` predicate is called for every pair of consecutive elements,
  /// meaning that it is called on `slice[0]` and `slice[1]`,
  /// followed by `slice[1]` and `slice[2]`, and so on.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// let chunked_by = a.chunked_by(|&p, &n| p > 0 && n > 2);
  /// assert_eq!(chunked_by, vec![vec![1, 2], vec![3]]);
  /// let a = a_source.clone();
  /// assert_eq!(a.chunked_by(|_, _| false), vec![vec![1, 2, 3]]);
  /// let a = a_source.clone();
  /// assert_eq!(a.chunked_by(|_, _| true), vec![vec![1], vec![2], vec![3]]);
  ///
  /// assert_eq!(e.chunked_by(|_, _| true), Vec::<Vec<i32>>::new());
  /// ```
  #[must_use]
  fn chunked_by(self, mut split: impl FnMut(&Item, &Item) -> bool) -> Vec<Self>
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut iterator = self.into_iter();
    let mut chunk_empty = true;
    let mut last = iterator.next();
    unfold(|| {
      let mut chunk_done = false;
      let chunk = unfold(|| {
        if !chunk_done && let Some(previous) = last.take() {
          if let Some(current) = iterator.next() {
            chunk_done = split(&previous, &current);
            last = Some(current);
          }
          chunk_empty = false;
          return Some(previous);
        }
        None
      })
      .collect();
      if chunk_empty {
        None
      } else {
        chunk_empty = true;
        Some(chunk)
      }
    })
    .collect()
  }

  /// Creates a new sequence by splitting elements of this sequence
  /// into non-overlapping subsequences of specified `size`.
  ///
  /// The chunks are sequences and do not overlap. If `size` does not divide
  /// the length of the slice, then the last up to `size-1` elements will be omitted.
  ///
  /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
  /// resulting code better than in the case of [`chunked()`].
  ///
  /// See [`chunked()`] for a variant of this function that also returns the remainder as a smaller chunk.
  ///
  /// [`chunked()`]: SequenceTo::chunked
  ///
  /// # Panics
  ///
  /// Panics if chunk `size` is 0.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.chunked_exact(2), vec![vec![1, 2]]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.chunked_exact(3), vec![vec![1, 2, 3]]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.chunked_exact(1), vec![vec![1], vec![2], vec![3]]);
  /// ```
  #[inline]
  #[must_use]
  fn chunked_exact(self, size: usize) -> Vec<Self>
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    chunked(self, size, true)
  }

  /// Creates a new sequence by using the compression closure to
  /// optionally merge consecutive elements of this sequence.
  ///
  /// The closure `merge` is passed two elements, `previous` and `current` and may
  /// return either (1) `Ok(merged)` to merge the two values or
  /// (2) `Err((previous, current)` to indicate they can't be merged.
  /// In (2), the value `previous` is included in the new sequence.
  /// Either (1) `merged` or (2) `current` becomes the previous value
  /// when coalesce continues with the next pair of elements to merge. The
  /// value that remains at the end is also included in the new sequence.
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 1, 2, 1, 2, 2, 3];
  ///
  /// let coalesced = a.coalesce(|p, n| if p % 2 == n % 2 { Ok(p + n) } else { Err((p, n)) });
  ///
  /// assert_eq!(coalesced, vec![4, 1, 4, 3]);
  /// ```
  #[must_use]
  fn coalesce(self, mut function: impl FnMut(Item, Item) -> Result<Item, (Item, Item)>) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut iterator = self.into_iter();
    let mut last = iterator.next();
    unfold(|| {
      loop {
        if let Some(previous) = last.take() {
          if let Some(current) = iterator.next() {
            match function(previous, current) {
              Ok(merged) => last = Some(merged),
              Err((new_previous, new_current)) => {
                last = Some(new_current);
                return Some(new_previous);
              }
            }
          } else {
            return Some(previous);
          }
        } else {
          return None;
        }
      }
    })
    .collect()
  }

  /// Creates a new sequence containing combinations with repetition of specified size
  /// from the elements of this sequence.
  ///
  /// Combinations are generated based on element positions, not values.
  /// Therefore, if this sequence contains duplicate elements, the resulting combinations will too.
  /// To obtain a combination with repetition of unique elements, use [`unique()`]`.multicombinations()`.
  ///
  /// The order or combination values is preserved.
  ///
  /// [`unique()`]: SequenceTo::unique
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.combinations_multi(0), vec![vec![]]);
  /// assert_eq!(a.combinations_multi(1), vec![vec![1], vec![2], vec![3]]);
  /// assert_eq!(a.combinations_multi(2), vec![
  ///   vec![1, 1],
  ///   vec![1, 2],
  ///   vec![1, 3],
  ///   vec![2, 2],
  ///   vec![2, 3],
  ///   vec![3, 3]
  /// ]);
  /// assert_eq!(a.combinations_multi(3), vec![
  ///   vec![1, 1, 1],
  ///   vec![1, 1, 2],
  ///   vec![1, 1, 3],
  ///   vec![1, 2, 2],
  ///   vec![1, 2, 3],
  ///   vec![1, 3, 3],
  ///   vec![2, 2, 2],
  ///   vec![2, 2, 3],
  ///   vec![2, 3, 3],
  ///   vec![3, 3, 3],
  /// ]);
  ///
  /// assert_eq!(e.combinations_multi(1), Vec::<Vec<i32>>::new());
  /// ```
  #[allow(clippy::cast_possible_wrap)]
  #[must_use]
  fn combinations_multi(&self, k: usize) -> Vec<Self>
  where
    Self: FromIterator<Item> + Sized,
    Item: Clone,
  {
    assert!(k <= MAX_SIZE, "k (is {k:?}) should be <= {MAX_SIZE:?})");
    let values = self.into_iter().collect::<Vec<_>>();
    let size = values.len();
    let mut multi_combination = iter::once(i64::MIN).chain(iter::repeat_n(0, k)).collect::<Vec<_>>();
    let mut current_slot = (size + 1).saturating_sub(k);
    unfold(|| {
      if current_slot == 0 {
        return None;
      }
      current_slot = k;
      let tuple = Some(collect_by_index(&values, &multi_combination[1..]));
      while multi_combination[current_slot] >= (size - 1) as i64 {
        current_slot -= 1;
      }
      let new_index = multi_combination[current_slot] + 1;
      for index in &mut multi_combination[current_slot..=k] {
        *index = new_index;
      }
      tuple
    })
    .collect()
  }

  /// Creates a new sequence by omitting an element at the specified index
  /// in this sequence.
  ///
  /// If the specified index exceeds this sequence size, no elements are deleted.
  ///
  /// # Panics
  ///
  /// Panics if `index` is out of bounds.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.delete_at(0), vec![2, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.delete_at(1), vec![1, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.delete_at(2), vec![1, 2]);
  /// ```
  #[must_use]
  fn delete_at(self, index: usize) -> Self;

  /// Creates a new sequence by omitting elements at specified indices
  /// in this sequence.
  ///
  /// If the specified index exceeds this sequence size, no elements are inserted.
  ///
  /// # Panics
  ///
  /// Panics if any of the `indices` is out of bounds.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.delete_at_multi(vec![0, 2]), vec![2]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.delete_at_multi(vec![0, 1, 2]), vec![]);
  /// ```
  #[inline]
  #[must_use]
  fn delete_at_multi(self, indices: impl IntoIterator<Item = usize>) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let positions = BTreeSet::from_iter(indices);
    self.into_iter().enumerate().filter_map(|(i, x)| if positions.contains(&i) { None } else { Some(x) }).collect()
  }

  /// Creates a new sequence by splitting this sequence into subsequences separated
  /// by elements equal to the specified `separator` value.
  /// Matched elements are not contained in the subsequences.
  ///
  /// # Examples
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.divide(&2), vec![vec![1], vec![3]]);
  ///
  /// # let a = a_source.clone();
  /// assert_eq!(a.divide(&0), vec![vec![1, 2, 3]]);
  /// ```
  ///
  /// If the first element is matched, an empty sequence will be the first
  /// element of the result. Similarly, if the last element in the sequence
  /// is matched, an empty sequence will be the last element of the result:
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.divide(&1), vec![vec![], vec![2, 3]]);
  /// ```
  ///
  /// If two matched elements are directly adjacent, an empty sequence will be
  /// present between them:
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 2, 3];
  ///
  /// assert_eq!(a.divide(&2), vec![vec![1], vec![], vec![3]]);
  /// ```
  #[inline]
  #[must_use]
  fn divide(self, separator: &Item) -> Vec<Self>
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    Item: PartialEq,
  {
    self.divide_by(|x| x == separator)
  }

  /// Creates a new sequence by splitting this sequence into subsequences separated
  /// by elements that match the `separator` predicate.
  /// Matched elements are not contained in the subsequences.
  ///
  /// # Examples
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.divide_by(|x| x % 2 == 0), vec![vec![1], vec![3]]);
  /// ```
  ///
  /// If the first element is matched, an empty sequence will be the first
  /// element of the result. Similarly, if the last element in the sequence
  /// is matched, an empty sequence will be the last element of the result:
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3, 4, 5];
  ///
  /// assert_eq!(a.divide_by(|x| x % 2 == 1), vec![vec![], vec![2], vec![4], vec![]]);
  /// ```
  ///
  /// If two matched elements are directly adjacent, an empty sequence will be
  /// present between them:
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 2, 3];
  ///
  /// assert_eq!(a.divide_by(|x| x % 2 == 0), vec![vec![1], vec![], vec![3]]);
  /// ```
  #[inline]
  #[must_use]
  fn divide_by(self, mut separator: impl FnMut(&Item) -> bool) -> Vec<Self>
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut iterator = self.into_iter();
    let mut empty = false;
    unfold(|| {
      if empty {
        return None;
      }
      let chunk = unfold(|| {
        if let Some(item) = iterator.next() {
          if !separator(&item) {
            return Some(item);
          }
        } else {
          empty = true;
        }
        None
      })
      .collect();
      Some(chunk)
    })
    .collect()
  }

  /// Creates a new collection by including only the elements of this collection
  /// that appear more than once.
  ///
  /// Duplicates are detected using hash and equality, and each duplicate is included exactly once.
  ///
  /// The order or duplicate values is preserved.
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 2, 3];
  ///
  /// assert_eq!(a.duplicates(), vec![2]);
  /// ```
  #[must_use]
  fn duplicates(self) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    Item: Eq + Hash,
  {
    let iterator = self.into_iter();
    let mut occurred = HashSet::with_capacity(iterator.size_hint().0);
    let mut duplicated = HashSet::with_capacity(iterator.size_hint().0);
    iterator
      .filter_map(|item| {
        if !duplicated.contains(&item) {
          if let Some(result) = occurred.take(&item) {
            let _ = duplicated.insert(item);
            return Some(result);
          }
          let _ = occurred.insert(item);
        }
        None
      })
      .collect()
  }

  /// Creates a new collection by including only the elements of this collection
  /// that appear more than once.
  ///
  /// Duplicates are detected by comparing the key they map to with the keying function
  /// `to_key` using hash and equality, and each duplicate is included exactly once.
  ///
  /// The order or duplicate values is preserved.
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.duplicates_by(|x| x % 2), vec![1, 3]);
  /// ```
  #[must_use]
  fn duplicates_by<K>(self, mut to_key: impl FnMut(&Item) -> K) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    K: Eq + Hash,
  {
    let mut iterator = self.into_iter();
    let mut occurred = HashMap::<K, Option<Item>>::with_capacity(iterator.size_hint().0);
    let mut stored: Option<Item> = None;
    unfold(|| {
      stored.take().or_else(|| {
        loop {
          if let Some(item) = iterator.next() {
            let key = to_key(&item);
            if let Some(value) = occurred.get_mut(&key) {
              stored = Some(item);
              return value.take();
            }
            let _unused = occurred.insert(key, Some(item));
          } else {
            return None;
          }
        }
      })
    })
    .collect()
  }

  /// Creates a new sequence which contains elements of this sequence
  /// and their indices.
  ///
  /// The new sequence contains pairs of `(i, val)`, where `i` is the
  /// current index of iteration and `val` is an element of this sequence.
  ///
  /// `enumerate()` keeps its count as an [`usize`]. If you want to count by a
  /// different sized integer, the [`zip()`] function provides similar
  /// functionality.
  ///
  /// # Overflow Behavior
  ///
  /// The method does no guarding against overflows, so traversing more than
  /// [`usize::MAX`] elements either produces the wrong result or panics. If
  /// debug assertions are enabled, a panic is guaranteed.
  ///
  /// [`zip()`]: SequenceTo::zip
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.enumerate(), vec![(0, 1), (1, 2), (2, 3)]);
  /// ```
  #[inline]
  #[must_use]
  fn enumerate(self) -> Self::This<(usize, Item)>
  where
    Self: IntoIterator<Item = Item> + Sized,
    Self::This<(usize, Item)>: FromIterator<(usize, Item)>,
  {
    self.into_iter().enumerate().collect()
  }

  /// Creates a new sequence containing an element
  /// specified number of times.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// assert_eq!(Vec::fill(1, 2), vec![1, 1]);
  /// assert_eq!(Vec::fill(1, 0), vec![]);
  /// ```
  #[inline]
  #[must_use]
  fn fill(element: Item, size: usize) -> Self
  where
    Self: FromIterator<Item>,
    Item: Clone,
  {
    iter::repeat_n(element, size).collect()
  }

  /// Creates a new sequence from this sequence without
  /// the last element.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.init(), vec![1, 2]);
  ///
  /// assert_eq!(e.init(), vec![]);
  /// ```
  #[must_use]
  fn init(self) -> Self;

  /// Create a new sequence by interleaving the elements of this sequence with
  /// the elements of another collection.
  ///
  /// If one sequence is longer than another, the remaining elements of the
  /// longer sequence are added to the end of the new collection.
  ///
  /// Elements are added to the new collection in an alternating fashion.
  /// The first element comes from this sequence, the second element
  /// comes from the other collection and so on.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.interleave(vec![4, 5, 6]), vec![1, 4, 2, 5, 3, 6]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.interleave(vec![4, 5]), vec![1, 4, 2, 5, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.interleave(vec![]), vec![1, 2, 3]);
  /// ```
  #[must_use]
  fn interleave(self, elements: impl IntoIterator<Item = Item>) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut iterator_left = self.into_iter();
    let mut iterator_right = elements.into_iter();
    let mut left = true;
    unfold(|| {
      let new_item = if left {
        iterator_left.next().or_else(|| iterator_right.next())
      } else {
        iterator_right.next().or_else(|| iterator_left.next())
      };
      left = !left;
      new_item
    })
    .collect()
  }

  /// Create a new sequence by interleaving the elements of this sequence with
  /// the elements of another collection.
  ///
  /// If one sequence is longer than another, the remaining elements of the
  /// longer sequence are omitted.
  ///
  /// Elements are added to the new collection in an alternating fashion.
  /// The first element comes from this sequence, the second element
  /// comes from the other collection and so on.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.interleave_exact(vec![4, 5, 6]), vec![1, 4, 2, 5, 3, 6]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.interleave_exact(vec![4, 5]), vec![1, 4, 2, 5]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.interleave_exact(vec![]), vec![]);
  /// ```
  #[inline]
  #[must_use]
  fn interleave_exact(self, elements: impl IntoIterator<Item = Item>) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    self.into_iter().zip(elements).flat_map(|(item1, item2)| iter::once(item1).chain(iter::once(item2))).collect()
  }

  /// Creates a new sequence which places a copy of `separator` between
  /// elements of the original sequence with the distance between the inserted
  /// values determined by the specified `interval`.
  ///
  /// In case `separator` does not implement [`Clone`] or needs to be
  /// computed every time, use [`intersperse_with`].
  ///
  /// [`intersperse_with`]: SequenceTo::intersperse_with
  ///
  /// # Examples
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.intersperse(1, 0), vec![1, 0, 2, 0, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.intersperse(2, 0), vec![1, 2, 0, 3]);
  ///
  /// # let a = a_source.clone();
  /// assert_eq!(a.intersperse(3, 0), vec![1, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn intersperse(self, interval: usize, element: Item) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    Item: Clone,
  {
    self.intersperse_with(interval, || element.clone())
  }

  /// Creates a new sequence which places a value generated by `to_element`
  /// between elements of the original sequence with the distance between the
  /// inserted values determined by the specified `interval`.
  ///
  /// The specified closure will be called exactly once each time an item is
  /// placed between two adjacent items from the underlying sequence.
  /// The closure is not called if the underlying sequence yields less than
  /// two items and after the last item is yielded.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.intersperse_with(1, || 0), vec![1, 0, 2, 0, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.intersperse_with(2, || 0), vec![1, 2, 0, 3]);
  ///
  /// # let a = a_source.clone();
  /// assert_eq!(a.intersperse_with(3, || 0), vec![1, 2, 3]);
  /// ```
  #[must_use]
  fn intersperse_with(self, interval: usize, mut to_value: impl FnMut() -> Item) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    Item: Clone,
  {
    assert_ne!(interval, 0, "interval must be non-zero");
    let mut iterator = self.into_iter();
    let mut index = 0_usize;
    let mut stored: Option<Item> = None;
    unfold(|| {
      stored.take().or_else(|| {
        iterator.next().map(|item| {
          let new_item = if index != 0 && index.is_multiple_of(interval) {
            stored = Some(item);
            to_value()
          } else {
            item
          };
          index += 1;
          new_item
        })
      })
    })
    .collect()
  }

  /// Creates a new sequence without trailing elements based on a predicate
  /// and a map the retained elements function.
  ///
  /// `map_while()` takes a closure as an argument. It will call this
  /// closure on each element of the sequence and include elements
  /// while it returns [`Some(_)`][`Some`].
  ///
  /// # Examples
  ///
  /// Basic usage:
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.map_while(|&x| if x < 3 { Some(x + 1) } else { None }), vec![2, 3]);
  /// ```
  ///
  /// Here's the same example, but with [`take_while`] and [`map`]:
  ///
  /// [`take_while`]: Iterator::take_while
  /// [`map`]: Iterator::map
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(
  ///   a.map_ref(|&x| if x < 3 { Some(x + 1) } else { None })
  ///     .take_while(|x| x.is_some())
  ///     .map_ref(|x| x.unwrap()),
  ///   vec![2, 3]
  /// );
  /// ```
  #[inline]
  #[must_use]
  fn map_while<B>(&self, predicate: impl FnMut(&Item) -> Option<B>) -> Self::This<B>
  where
    Self::This<B>: FromIterator<B>,
  {
    self.into_iter().map_while(predicate).collect()
  }

  /// Create a new sequence by merging it with another sequence in ascending order.
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.merge(vec![0, 4, 5]), vec![0, 1, 2, 3, 4, 5]);
  /// ```
  #[inline]
  #[must_use]
  fn merge(self, elements: impl IntoIterator<Item = Item>) -> Self
  where
    Item: Ord,
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    self.merge_by(elements, Ord::cmp)
  }

  /// Create a new sequence by merging it with another sequence in ascending order
  /// with respect to the specified comparison function.
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.merge_by(vec![0, 4, 5], |l, r| l.cmp(r)), vec![0, 1, 2, 3, 4, 5]);
  /// ```
  #[must_use]
  fn merge_by(self, elements: impl IntoIterator<Item = Item>, mut compare: impl FnMut(&Item, &Item) -> Ordering) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut iterator = self.into_iter();
    let mut elements_iterator = elements.into_iter();
    let mut last_left = iterator.next();
    let mut last_right = elements_iterator.next();
    unfold(|| match (last_left.take(), last_right.take()) {
      (Some(left), Some(right)) => {
        if compare(&left, &right) == Ordering::Less {
          last_left = iterator.next();
          last_right = Some(right);
          Some(left)
        } else {
          last_left = Some(left);
          last_right = elements_iterator.next();
          Some(right)
        }
      }
      (Some(left), None) => {
        last_left = iterator.next();
        Some(left)
      }
      (None, Some(right)) => {
        last_right = elements_iterator.next();
        Some(right)
      }
      (None, None) => None,
    })
    .collect()
  }

  /// Creates a new sequence by moving an element at an index into the specified index
  /// in this sequence.
  ///
  /// If the target index exceeds this sequence size, the element is only removed.
  /// If the source index exceeds this sequence size, no elements are moved.
  ///
  /// # Panics
  ///
  /// Panics if `source_index` or `target_index` are out of bounds.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.move_at(0, 2), vec![2, 3, 1]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.move_at(2, 1), vec![1, 3, 2]);
  ///
  /// # let a = a_source.clone();
  /// assert_eq!(a.move_at(1, 1), vec![1, 2, 3]);
  /// ```
  #[must_use]
  fn move_at(self, source_index: usize, target_index: usize) -> Self;

  /// Creates a new sequence by padding this sequence to a minimum length of `size`
  /// and filling missing elements with specified value, starting from the back.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.pad_left(5, 4), vec![4, 4, 1, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn pad_left(self, size: usize, element: Item) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    <Self as IntoIterator>::IntoIter: ExactSizeIterator<Item = Item>,
    Item: Clone,
  {
    self.pad_left_with(size, |_| element.clone())
  }

  /// Creates a new sequence by padding this sequence to a minimum length of `size`
  /// and filling missing elements using a closure `to_element`, starting from the back.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.pad_left_with(5, |i| 2 * i), vec![0, 2, 1, 2, 3]);
  /// ```
  #[must_use]
  fn pad_left_with(self, size: usize, mut to_element: impl FnMut(usize) -> Item) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    <Self as IntoIterator>::IntoIter: ExactSizeIterator<Item = Item>,
    Item: Clone,
  {
    let mut iterator = self.into_iter();
    let original_start = size - iterator.len();
    let mut index = 0_usize;
    unfold(|| {
      let new_item = if index < original_start { Some(to_element(index)) } else { iterator.next() };
      index += 1;
      new_item
    })
    .collect()
  }

  /// Creates a new sequence by padding this sequence to a minimum length of
  /// `size` and filling missing elements with specified value.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.pad_right(5, 4), vec![1, 2, 3, 4, 4]);
  /// ```
  #[inline]
  #[must_use]
  fn pad_right(self, size: usize, element: Item) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    Item: Clone,
  {
    self.pad_right_with(size, |_| element.clone())
  }

  /// Creates a new sequence by padding this sequence to a minimum length of
  /// `size` and filling missing elements using a closure `to_element`.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.pad_right_with(5, |x| 2 * x), vec![1, 2, 3, 6, 8]);
  /// ```
  #[must_use]
  fn pad_right_with(self, size: usize, mut to_element: impl FnMut(usize) -> Item) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    Item: Clone,
  {
    let mut iterator = self.into_iter();
    let mut index = 0_usize;
    unfold(|| {
      let new_item = iterator.next().or_else(|| if index < size { Some(to_element(index)) } else { None });
      index += 1;
      new_item
    })
    .collect()
  }

  /// Creates a new sequence by reversing this sequence's direction.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.rev(), vec![3, 2, 1]);
  /// ```
  #[inline]
  #[must_use]
  fn rev(self) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    <Self as IntoIterator>::IntoIter: DoubleEndedIterator<Item = Item>,
  {
    self.into_iter().rev().collect()
  }

  /// Reduces this sequence's elements to a single, final value, starting from the back.
  ///
  /// This is the reverse version of [`Iterator::fold()`]: it takes elements
  /// starting from the back of this sequence.
  ///
  /// `rfold()` 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 this sequence, `rfold()`
  /// 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.
  ///
  /// This is a consuming variant of [`rfold_ref()`].
  ///
  /// Note: `rfold()` combines elements in a *right-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 *left-associative* version of `rfold()`, see [`fold()`].
  ///
  /// [`rfold_ref()`]: crate::Sequence::rfold_ref
  /// [`fold()`]: crate::CollectionTo::fold
  ///
  /// # Examples
  ///
  /// Basic usage:
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// // the sum of all the elements in a
  /// assert_eq!(a.rfold_ref(0, |acc, &x| acc + x), 6);
  /// ```
  ///
  /// This example demonstrates the right-associative nature of `rfold_to()`:
  /// it builds a string, starting with an initial value
  /// and continuing with each element from the back until the front:
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3, 4, 5];
  ///
  /// let zero = "0".to_string();
  ///
  /// assert_eq!(
  ///   a.rfold(zero, |acc, x| { format!("({x} + {acc})") }),
  ///   "(1 + (2 + (3 + (4 + (5 + 0)))))"
  /// );
  /// ```
  #[inline]
  #[must_use]
  fn rfold<B, I>(self, initial_value: B, function: impl FnMut(B, Item) -> B) -> B
  where
    Self: IntoIterator<Item = Item, IntoIter = I> + Sized,
    I: DoubleEndedIterator<Item = Item>,
  {
    self.into_iter().rfold(initial_value, function)
  }

  /// A sequence adapter which, like [`fold()`], holds an internal state, but
  /// unlike [`fold()`], produces a new sequence.
  ///
  /// `scan()` takes two arguments: an initial value which seeds the internal
  /// state, and a closure with two arguments, the first being a mutable
  /// reference to the internal state and the second element of this sequence.
  /// The closure can assign to the internal state to share state between
  /// iterations.
  ///
  /// On iteration, the closure will be applied to each element of this
  /// sequence, and the return value from the closure, an [`Option`], is
  /// returned by the `next` method. The closure can return
  /// `Some(value)` to yield `value`, or `None` to end the iteration.
  ///
  /// This is a consuming variant of [`scan()`].
  ///
  /// [`fold()`]: crate::CollectionTo::fold
  /// [`scan()`]: SequenceTo::scan_ref
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// let mut scan = a.scan(1, |state, x| {
  ///   // in each iteration, we'll multiply the state by the element ...
  ///   *state = *state * x;
  ///
  ///   // ... and terminate if the state exceeds 6
  ///   if *state > 2 {
  ///     return None;
  ///   }
  ///   // ... else yield the negation of the state
  ///   Some(-*state)
  /// });
  ///
  /// assert_eq!(scan, vec![-1, -2]);
  /// ```
  #[inline]
  #[must_use]
  fn scan<S, B>(self, initial_state: S, function: impl FnMut(&mut S, Item) -> Option<B>) -> Self::This<B>
  where
    Self: IntoIterator<Item = Item> + Sized,
    Self::This<B>: FromIterator<B>,
  {
    self.into_iter().scan(initial_state, function).collect()
  }

  /// A sequence adapter which, like [`fold_ref()`], holds an internal state, but
  /// unlike [`fold_ref()`], produces a new sequence.
  ///
  /// `scan_ref()` takes two arguments: an initial value which seeds the internal
  /// state, and a closure with two arguments, the first being a mutable
  /// reference to the internal state and the second element of this sequence.
  /// The closure can assign to the internal state to share state between
  /// iterations.
  ///
  /// On iteration, the closure will be applied to each element of this
  /// sequence, and the return value from the closure, an [`Option`], is
  /// returned by the `next` method. The closure can return
  /// `Some(value)` to yield `value`, or `None` to end the iteration.
  ///
  /// This is a non-consuming variant of [`scan()`].
  ///
  /// [`fold_ref()`]: crate::Collection::fold_ref
  /// [`scan()`]: SequenceTo::scan
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// let mut scan = a.scan(1, |state, x| {
  ///   // in each iteration, we'll multiply the state by the element ...
  ///   *state = *state * x;
  ///
  ///   // ... and terminate if the state exceeds 6
  ///   if *state > 2 {
  ///     return None;
  ///   }
  ///   // ... else yield the negation of the state
  ///   Some(-*state)
  /// });
  ///
  /// assert_eq!(scan, vec![-1, -2]);
  /// ```
  #[inline]
  #[must_use]
  fn scan_ref<S, B>(&self, initial_state: S, function: impl FnMut(&mut S, &Item) -> Option<B>) -> Self::This<B>
  where
    Self::This<B>: FromIterator<B>,
  {
    self.into_iter().scan(initial_state, function).collect()
  }

  /// Creates a new sequence that skips the first `n` elements from this sequence.
  ///
  /// `skip(n)` skips elements until `n` elements are skipped or the end of this
  /// sequence is reached (whichever happens first). After that, all the remaining
  /// elements are yielded. In particular, if this sequence is too short,
  /// then the returned sequence is empty.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.skip(2), vec![3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.skip(5), vec![]);
  /// ```
  #[inline]
  #[must_use]
  fn skip(self, n: usize) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    self.into_iter().skip(n).collect()
  }

  /// Creates a new sequence without initial elements based on a predicate.
  ///
  /// [`skip`]: Collectible::skip
  ///
  /// `skip_while()` takes a closure as an argument. It will call this
  /// closure on each element of this sequence and ignore elements
  /// until it returns `false`.
  ///
  /// After `false` is returned, `skip_while()`'s job is over, and the
  /// rest of the elements are yielded.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.skip_while(|&x| x < 3), vec![3]);
  /// ```
  #[inline]
  #[must_use]
  fn skip_while(self, predicate: impl FnMut(&Item) -> bool) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    self.into_iter().skip_while(predicate).collect()
  }

  /// Creates a new sequence by only including elements in the specified range.
  ///
  /// If the specified index exceeds this sequence size, no elements are inserted.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.slice(0, 2), vec![1, 2]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.slice(1, 3), vec![2, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.slice(1, 1), vec![]);
  /// ```
  #[must_use]
  fn slice(self, start_index: usize, end_index: usize) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
    <Self as IntoIterator>::IntoIter: ExactSizeIterator<Item = Item>,
  {
    let iterator = self.into_iter();
    let size = iterator.len();
    assert!(start_index <= size, "start index (is {start_index:?}) should be <= len (is {size:?})");
    assert!(end_index <= size, "end index (is {end_index:?}) should be <= len (is {size:?})");
    iterator.enumerate().filter(|(index, _)| *index >= start_index && *index < end_index).map(|(_, x)| x).collect()
  }

  /// Creates a new sequence by sorting this sequence.
  ///
  /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.
  ///
  /// When applicable, unstable sorting is preferred because it is generally faster than stable
  /// sorting, and it doesn't allocate auxiliary memory.
  /// See [`sorted_unstable()`](SequenceTo::sorted_unstable).
  ///
  /// # Current implementation
  ///
  /// The current algorithm is an adaptive, iterative merge sort inspired by
  /// [timsort](https://en.wikipedia.org/wiki/Timsort).
  /// It is designed to be very fast in cases where this sequence is nearly sorted, or consists of
  /// two or more sorted sequences concatenated one after another.
  ///
  /// Also, it allocates temporary storage half the size of `self`, but for short sequences a
  /// non-allocating insertion sort is used instead.
  ///
  /// # Examples
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![2, 3, 1];
  ///
  /// assert_eq!(a.sorted(), vec![1, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn sorted(self) -> Self
  where
    Item: Ord,
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut result = self.into_iter().collect::<Vec<Item>>();
    result.sort();
    result.into_iter().collect()
  }

  /// Creates a new sequence by sorting this sequence with a comparator function.
  ///
  /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.
  ///
  /// The comparator function must define a total ordering for the elements in this sequence. If
  /// the ordering is not total, the order of the elements is unspecified. An order is a
  /// total order if it is (for all `a`, `b` and `c`):
  ///
  /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
  /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
  ///
  /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
  /// `partial_cmp` as our sort function when we know this sequence doesn't contain a `NaN`.
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![2, 3, 1];
  ///
  /// assert_eq!(a.sorted_by(|a, b| a.partial_cmp(b).unwrap()), vec![1, 2, 3]);
  /// ```
  ///
  /// When applicable, unstable sorting is preferred because it is generally faster than stable
  /// sorting, and it doesn't allocate auxiliary memory.
  /// See [`sorted_unstable_by()`](SequenceTo::sorted_unstable_by).
  ///
  /// # Current implementation
  ///
  /// The current algorithm is an adaptive, iterative merge sort inspired by
  /// [timsort](https://en.wikipedia.org/wiki/Timsort).
  /// It is designed to be very fast in cases where this sequence is nearly sorted, or consists of
  /// two or more sorted sequences concatenated one after another.
  ///
  /// Also, it allocates temporary storage half the size of `self`, but for short sequences a
  /// non-allocating insertion sort is used instead.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![2, 3, 1];
  ///
  /// assert_eq!(a.sorted_by(|a, b| a.cmp(b)), vec![1, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn sorted_by(self, compare: impl FnMut(&Item, &Item) -> Ordering) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut result = self.into_iter().collect::<Vec<Item>>();
    result.sort_by(compare);
    result.into_iter().collect()
  }

  /// Creates a new sequence by sorting this sequence with a key extraction function.
  ///
  /// During sorting, the key function is called at most once per element, by using
  /// temporary storage to remember the results of key evaluation.
  /// The order of calls to the key function is unspecified and may change in future versions
  /// of the standard library.
  ///
  /// This sort is stable (i.e., does not reorder equal elements), and *O*(*m* \* *n* + *n* \* log(*n*))
  /// worst-case, where the key function is *O*(*m*).
  ///
  /// For simple key functions (e.g., functions that are property accesses or
  /// basic operations), [`sorted_by_key()`](SequenceTo::sorted_by_key) is likely to be
  /// faster.
  ///
  /// # Current implementation
  ///
  /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
  /// which combines the fast average case of randomized quicksort with the fast worst case of
  /// heapsort, while achieving linear time on sequences with certain patterns. It uses some
  /// randomization to avoid degenerate cases, but with a fixed seed to always provide
  /// deterministic behavior.
  ///
  /// In the worst case, the algorithm allocates temporary storage in a `Vec<(K, usize)>` the
  /// length of this sequence.
  ///
  /// [pdqsort]: https://github.com/orlp/pdqsort
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![2, 3, 1];
  ///
  /// assert_eq!(a.sorted_by_cached_key(|k| k.to_string()), vec![1, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn sorted_by_cached_key<K: Ord>(self, to_key: impl FnMut(&Item) -> K) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut result = self.into_iter().collect::<Vec<Item>>();
    result.sort_by_cached_key(to_key);
    result.into_iter().collect()
  }

  /// Creates a new sequence by sorting this sequence with a key extraction function.
  ///
  /// This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* \* log(*n*))
  /// worst-case, where the key function is *O*(*m*).
  ///
  /// For expensive key functions (e.g., functions that are not simple property accesses or
  /// basic operations), [`sorted_by_cached_key()`](SequenceTo::sorted_by_cached_key) is likely to be
  /// significantly faster, as it does not recompute element keys.
  ///
  /// When applicable, unstable sorting is preferred because it is generally faster than stable
  /// sorting, and it doesn't allocate auxiliary memory.
  /// See [`sorted_unstable_by_key()`](SequenceTo::sorted_unstable_by_key).
  ///
  /// # Current implementation
  ///
  /// The current algorithm is an adaptive, iterative merge sort inspired by
  /// [timsort](https://en.wikipedia.org/wiki/Timsort).
  /// It is designed to be very fast in cases where this sequence is nearly sorted, or consists of
  /// two or more sorted sequences concatenated one after another.
  ///
  /// Also, it allocates temporary storage half the size of `self`, but for short sequences a
  /// non-allocating insertion sort is used instead.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![2, 3, 1];
  ///
  /// assert_eq!(a.sorted_by_key(|&k| -k), vec![3, 2, 1]);
  /// ```
  #[inline]
  #[must_use]
  fn sorted_by_key<K: Ord>(self, to_key: impl FnMut(&Item) -> K) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut result = self.into_iter().collect::<Vec<Item>>();
    result.sort_by_key(to_key);
    result.into_iter().collect()
  }

  /// Creates a new sequence by sorting this sequence, but might not preserve the order of equal elements.
  ///
  /// This sort is unstable (i.e., may reorder equal elements), in-place
  /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
  ///
  /// # Current implementation
  ///
  /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
  /// which combines the fast average case of randomized quicksort with the fast worst case of
  /// heapsort, while achieving linear time on sequences with certain patterns. It uses some
  /// randomization to avoid degenerate cases, but with a fixed seed to always provide
  /// deterministic behavior.
  ///
  /// It is typically faster than stable sorting, except in a few special cases, e.g., when this
  /// sequence consists of several concatenated sorted sequences.
  ///
  /// [pdqsort]: https://github.com/orlp/pdqsort
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![2, 3, 1];
  ///
  /// assert_eq!(a.sorted_unstable(), vec![1, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn sorted_unstable(self) -> Self
  where
    Item: Ord,
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut result = self.into_iter().collect::<Vec<Item>>();
    result.sort_unstable();
    result.into_iter().collect()
  }

  /// Creates a new sequence by sorting this sequence with a comparator function,
  /// but might not preserve the order of equal elements.
  ///
  /// This sort is unstable (i.e., may reorder equal elements), in-place
  /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
  ///
  /// The comparator function must define a total ordering for the elements in this sequence. If
  /// the ordering is not total, the order of the elements is unspecified. An order is a
  /// total order if it is (for all `a`, `b` and `c`):
  ///
  /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
  /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
  ///
  /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
  /// `partial_cmp` as our sort function when we know this sequence doesn't contain a `NaN`.
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![2, 3, 1];
  ///
  /// assert_eq!(a.sorted_unstable_by(|a, b| a.partial_cmp(b).unwrap()), vec![1, 2, 3]);
  /// ```
  ///
  /// # Current implementation
  ///
  /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
  /// which combines the fast average case of randomized quicksort with the fast worst case of
  /// heapsort, while achieving linear time on sequences with certain patterns. It uses some
  /// randomization to avoid degenerate cases, but with a fixed seed to always provide
  /// deterministic behavior.
  ///
  /// It is typically faster than stable sorting, except in a few special cases, e.g., when this
  /// sequence consists of several concatenated sorted sequences.
  ///
  /// [pdqsort]: https://github.com/orlp/pdqsort
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![2, 3, 1];
  ///
  /// assert_eq!(a.sorted_unstable_by(|a, b| a.cmp(b)), vec![1, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn sorted_unstable_by(self, compare: impl FnMut(&Item, &Item) -> Ordering) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut result = self.into_iter().collect::<Vec<Item>>();
    result.sort_unstable_by(compare);
    result.into_iter().collect()
  }

  /// Creates a new sequence by sorting this sequence with a key extraction function,
  /// but might not preserve the order of equal elements.
  ///
  /// This sort is unstable (i.e., may reorder equal elements), in-place
  /// (i.e., does not allocate), and *O*(*m* \* *n* \* log(*n*)) worst-case, where the key function is
  /// *O*(*m*).
  ///
  /// # Current implementation
  ///
  /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
  /// which combines the fast average case of randomized quicksort with the fast worst case of
  /// heapsort, while achieving linear time on slices with certain patterns. It uses some
  /// randomization to avoid degenerate cases, but with a fixed seed to always provide
  /// deterministic behavior.
  ///
  /// Due to its key calling strategy, [`sorted_unstable_by_key()`](SequenceTo::sorted_unstable_by_key)
  /// is likely to be slower than [`sorted_by_cached_key()`](Sequence::.sorted_by_cached_key) in
  /// cases where the key function is expensive.
  ///
  /// [pdqsort]: https://github.com/orlp/pdqsort
  ///
  /// # Examples
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![2, 3, 1];
  ///
  /// assert_eq!(a.sorted_unstable_by_key(|&k| -k), vec![3, 2, 1]);
  /// ```
  #[inline]
  #[must_use]
  fn sorted_unstable_by_key<K: Ord>(self, to_key: impl FnMut(&Item) -> K) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let mut result = self.into_iter().collect::<Vec<Item>>();
    result.sort_unstable_by_key(to_key);
    result.into_iter().collect()
  }

  /// Creates a new sequence from this sequence stepping by
  /// the given amount for each retained element.
  ///
  /// Note: The first element of this sequence will always be returned,
  /// regardless of the step given.
  ///
  /// # Panics
  ///
  /// The method will panic if the given step is `0`.
  ///
  /// # Examples
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 2, 3];
  /// let a = vec![1, 2, 2, 3];
  ///
  /// assert_eq!(a.step_by(3), vec![1, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.step_by(2), vec![1, 2]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.step_by(1), vec![1, 2, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn step_by(self, step: usize) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    self.into_iter().step_by(step).collect()
  }

  /// Creates a new sequence by replacing an element at the specified index
  /// in this sequence.
  ///
  /// If the specified index exceeds this sequence size, no elements are replaced.
  ///
  /// # Panics
  ///
  /// Panics if `index` is out of bounds.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.substitute_at(1, 4), vec![1, 4, 3]);
  /// ```
  #[must_use]
  fn substitute_at(self, index: usize, replacement: Item) -> Self;

  /// Creates a new sequence by replacing all elements at specified indices in this sequence
  /// by elements from another collection.
  ///
  /// If the specified index exceeds this sequence size, no elements are replaced.
  ///
  /// # Panics
  ///
  /// Panics if any of the `indices` is out of bounds.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.substitute_at_multi(vec![0, 2], vec![4, 5]), vec![4, 2, 5]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.substitute_at_multi(vec![0, 2], vec![4]), vec![4, 2, 3]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.substitute_at_multi(vec![0, 2], vec![4, 5, 6]), vec![4, 2, 5]);
  /// ```
  #[must_use]
  fn substitute_at_multi(
    self, indices: impl IntoIterator<Item = usize>, replacements: impl IntoIterator<Item = Item>,
  ) -> Self;

  /// Creates a new sequence by swapping elements at specified indices
  /// in this sequence.
  ///
  /// If one of the indices exceeds this sequence size, the element is only removed.
  /// If both indices exceed this sequence size, no elements are swapped.
  ///
  /// # Panics
  ///
  /// Panics if `source_index` or `target_index` are out of bounds.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.swap_at(0, 2), vec![3, 2, 1]);
  ///
  /// # let a = a_source.clone();
  /// assert_eq!(a.swap_at(1, 1), vec![1, 2, 3]);
  /// ```
  #[must_use]
  fn swap_at(self, source_index: usize, target_index: usize) -> Self;

  /// Creates a new sequence from this sequence without
  /// the first element.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.tail(), vec![2, 3]);
  ///
  /// assert_eq!(e.tail(), vec![]);
  /// ```
  #[must_use]
  fn tail(self) -> Self;

  /// Creates a new sequence that yields the first `n` elements, or fewer
  /// if this sequence has fewer than `n` elements.
  ///
  /// `take(n)` yields elements until `n` elements are yielded or the end of
  /// this sequence is reached (whichever happens first).
  /// The returned sequence is a prefix of length `n` if this sequence
  /// contains at least `n` elements, otherwise it contains all the
  /// (fewer than `n`) elements of this sequence.
  ///
  /// # Examples
  ///
  /// Basic usage:
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.take(2), vec![1, 2]);
  /// ```
  ///
  /// If less than `n` elements are available,
  /// `take` will limit itself to the size of this sequence:
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.take(2), vec![1, 2]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.take(5), vec![1, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn take(self, n: usize) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    self.into_iter().take(n).collect()
  }

  /// Creates a new sequence without trailing elements based on a predicate.
  ///
  /// `take_while()` takes a closure as an argument. It will call this
  /// closure on each element of this sequence and yield elements
  /// while it returns `true`.
  ///
  /// After `false` is returned, `take_while()`'s job is over, and the
  /// rest of the elements are ignored.
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.take_while(|&x| x < 3), vec![1, 2]);
  /// ```
  #[inline]
  #[must_use]
  fn take_while(self, predicate: impl FnMut(&Item) -> bool) -> Self
  where
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    self.into_iter().take_while(predicate).collect()
  }

  /// Creates a new sequence by omitting duplicate elements.
  ///
  /// Duplicates are detected using hash and equality.
  ///
  /// The algorithm is stable, returning the non-duplicate items in the order
  /// in which they occur in this sequence. In a set of duplicate
  /// items, the first item encountered is the item retained.
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 2, 3];
  ///
  /// assert_eq!(a.unique(), vec![1, 2, 3]);
  /// ```
  #[must_use]
  fn unique(self) -> Self
  where
    Item: Eq + Hash + Clone,
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let iterator = self.into_iter();
    let mut occurred = HashSet::with_capacity(iterator.size_hint().0);
    iterator
      .filter_map(|item| {
        if occurred.contains(&item) {
          None
        } else {
          let _ = occurred.insert(item.clone());
          Some(item)
        }
      })
      .collect()
  }

  /// Creates a new sequence by omitting duplicate elements.
  ///
  /// Duplicates are detected by comparing the key they map to
  /// with the result of the keying function `to_key` using hash and equality.
  ///
  /// The algorithm is stable, returning the non-duplicate items in the order
  /// in which they occur in this sequence. In a set of duplicate
  /// items, the first item encountered is the item retained.
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 2, 3];
  ///
  /// assert_eq!(a.unique_by(|x| x % 2), vec![1, 2]);
  /// ```
  #[must_use]
  fn unique_by<K>(self, mut to_key: impl FnMut(&Item) -> K) -> Self
  where
    K: Eq + Hash,
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    let iterator = self.into_iter();
    let mut occurred = HashSet::with_capacity(iterator.size_hint().0);
    iterator
      .filter(|item| {
        let key = to_key(item);
        if occurred.contains(&key) {
          false
        } else {
          let _unused = occurred.insert(key);
          true
        }
      })
      .collect()
  }

  /// Creates two new sequences by splitting this sequence of pairs.
  ///
  /// `unzip()` produces two sequences: one from the left elements of the pairs,
  /// and one from the right elements.
  ///
  /// This function is, in some sense, the opposite of [`zip()`].
  ///
  /// [`zip()`]: SequenceTo::zip
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![(1, 1), (2, 2), (3, 3)];
  ///
  /// let (left, right) = a.unzip();
  ///
  /// assert_eq!(left, vec![1, 2, 3]);
  /// assert_eq!(right, vec![1, 2, 3]);
  /// ```
  #[inline]
  #[must_use]
  fn unzip<A, B>(self) -> (Self::This<A>, Self::This<B>)
  where
    Self: IntoIterator<Item = (A, B)> + Sized,
    Self::This<A>: Default + Extend<A>,
    Self::This<B>: Default + Extend<B>,
  {
    self.into_iter().unzip()
  }

  /// Creates a new sequence containing variations of specified size
  /// from the elements of this sequence.
  ///
  /// Specifying size is equal to the length of this sequence produces all permutations of this sequence.
  ///
  /// Variations are generated based on element positions, not values.
  /// Therefore, if this sequence contains duplicate elements, the resulting variations will too.
  /// To obtain variations of unique elements, use [`unique()`]`.variations()`.
  ///
  /// The order or variation values is preserved.
  ///
  /// [`unique()`]: SequenceTo::unique
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.variations(0), vec![vec![]]);
  /// assert_eq!(a.variations(1), vec![vec![1], vec![2], vec![3]]);
  /// assert_eq!(a.variations(2), vec![
  ///   vec![1, 2],
  ///   vec![1, 3],
  ///   vec![2, 1],
  ///   vec![2, 3],
  ///   vec![3, 1],
  ///   vec![3, 2]
  /// ]);
  /// // Permutations
  /// assert_eq!(a.variations(3), vec![
  ///   vec![1, 2, 3],
  ///   vec![1, 3, 2],
  ///   vec![2, 1, 3],
  ///   vec![2, 3, 1],
  ///   vec![3, 1, 2],
  ///   vec![3, 2, 1],
  /// ]);
  ///
  /// assert_eq!(e.variations(1), Vec::<Vec<i32>>::new());
  /// ```
  #[allow(clippy::cast_sign_loss)]
  #[allow(clippy::cast_possible_truncation)]
  #[allow(clippy::cast_possible_wrap)]
  #[must_use]
  fn variations(&self, k: usize) -> Vec<Self>
  where
    Item: Clone,
    Self: FromIterator<Item> + Sized,
  {
    assert!(k <= MAX_SIZE, "k (is {k:?}) should be <= {MAX_SIZE:?})");
    let values = self.into_iter().collect::<Vec<_>>();
    let size = values.len();
    let mut variation = iter::once(i64::MIN).chain(0..(k as i64)).collect::<Vec<_>>();
    let mut used_indices =
      iter::repeat_n(true, k).chain(iter::repeat_n(false, size.saturating_sub(k))).collect::<Vec<_>>();
    let mut current_slot = (size + 1).saturating_sub(k);
    unfold(|| {
      if current_slot == 0 {
        return None;
      }
      current_slot = k;
      let tuple = Some(collect_by_index(&values, &variation[1..]));
      while current_slot > 0 && ((variation[current_slot] + 1)..(size as i64)).all(|x| used_indices[x as usize]) {
        used_indices[variation[current_slot] as usize] = false;
        current_slot -= 1;
      }
      if current_slot > 0 {
        let initial_index =
          ((variation[current_slot] + 1)..(size as i64)).find(|x| !used_indices[*x as usize]).unwrap();
        used_indices[variation[current_slot] as usize] = false;
        used_indices[initial_index as usize] = true;
        variation[current_slot] = initial_index;
        for index in &mut variation[(current_slot + 1)..=k] {
          let new_index = (0..=(size as i64)).find(|x| !used_indices[*x as usize]).unwrap();
          used_indices[new_index as usize] = true;
          *index = new_index;
        }
      }
      tuple
    })
    .collect()
  }

  /// Creates a new sequence consisting of overlapping `N` element windows
  /// of this sequence, starting at the beginning of this sequence.
  ///
  /// The step parameter determines the distance between the first elements of
  /// successive windows.
  ///
  /// If `N` is greater than the size of this sequence, it will return no windows.
  ///
  /// This is the generalized equivalent of [`windows()`].
  ///
  /// # Panics
  ///
  /// Panics if `N` is 0. This check will most probably get changed to a compile time
  /// error before this method gets stabilized.
  ///
  /// [`windows()`]: slice::windows
  ///
  /// # Examples
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.windowed(2, 1), vec![vec![1, 2], vec![2, 3]]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.windowed(2, 2), vec![vec![1, 2]]);
  ///
  /// assert_eq!(e.windowed(1, 1), Vec::<Vec<i32>>::new());
  /// ```
  #[must_use]
  fn windowed(&self, size: usize, step: usize) -> Vec<Self>
  where
    Item: Clone,
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    assert_ne!(size, 0, "window size must be non-zero");
    assert_ne!(step, 0, "step must be non-zero");
    let mut window = VecDeque::<Item>::with_capacity(size);
    self
      .into_iter()
      .filter_map(|item| {
        window.push_back(item.clone());
        if window.len() >= size {
          let tuple = Some(Self::from_iter(window.clone()));
          for _ in 0..step {
            let _unused = window.pop_front();
          }
          tuple
        } else {
          None
        }
      })
      .collect()
  }

  /// Creates a new sequence consisting of overlapping `N` element windows
  /// of this sequence, starting at the beginning of this sequence and wrapping
  /// back to the first elements when the window would otherwise exceed this sequence length.
  ///
  /// The step parameter determines the distance between the first elements of
  /// successive windows.
  ///
  /// If `N` is greater than the size of this sequence, it will return no windows.
  ///
  /// # Panics
  ///
  /// Panics if `N` is 0. This check will most probably get changed to a compile time
  /// error before this method gets stabilized.
  ///
  /// # Examples
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  /// let e = Vec::<i32>::new();
  ///
  /// assert_eq!(a.windowed_circular(2, 1), vec![vec![1, 2], vec![2, 3], vec![3, 1]]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.windowed_circular(2, 2), vec![vec![1, 2], vec![3, 1]]);
  ///
  /// assert_eq!(e.windowed_circular(1, 1), Vec::<Vec<i32>>::new());
  /// ```
  #[must_use]
  fn windowed_circular(&self, size: usize, step: usize) -> Vec<Self>
  where
    Item: Clone,
    Self: IntoIterator<Item = Item> + FromIterator<Item>,
  {
    assert_ne!(size, 0, "window size must be non-zero");
    assert_ne!(step, 0, "step must be non-zero");
    let mut window = VecDeque::<Item>::with_capacity(size);
    let mut init = VecDeque::<Item>::with_capacity(size - 1);
    let mut iterator = self.into_iter();
    unfold(|| {
      while window.len() < size {
        if let Some(item) = iterator.next() {
          window.push_back(item.clone());
          if init.len() < size - 1 {
            init.push_back(item.clone());
          }
        } else if let Some(item) = init.pop_front() {
          window.push_back(item);
        } else {
          return None;
        }
      }
      let tuple = Some(Self::from_iter(window.clone()));
      for _ in 0..step {
        let _unused = window.pop_front();
      }
      tuple
    })
    .collect()
  }

  /// 'Zips up' this sequence with another collection into a single sequence of pairs.
  ///
  /// `zip()` returns a new sequence containing pairs where the first element comes from
  /// this sequence, and the second element comes from the other collection.
  ///
  /// If any of the sequences contains more elements than the other one, the remaining elements
  /// are omitted and the resulting sequence length is the length of the shorter sequence.
  ///
  /// To 'undo' the result of zipping up two sequences, see [`unzip()`].
  ///
  /// [`unzip()`]: SequenceTo::unzip
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.zip(vec![4, 5, 6]), vec![(1, 4), (2, 5), (3, 6)]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.zip(vec![4, 5, 6, 7]), vec![(1, 4), (2, 5), (3, 6)]);
  /// # let a = a_source.clone();
  /// assert_eq!(a.zip(vec![4, 5]), vec![(1, 4), (2, 5)]);
  /// ```
  #[inline]
  #[must_use]
  fn zip<T>(self, elements: impl IntoIterator<Item = T>) -> Self::This<(Item, T)>
  where
    Self: IntoIterator<Item = Item> + Sized,
    Self::This<(Item, T)>: FromIterator<(Item, T)>,
  {
    self.into_iter().zip(elements).collect()
  }

  /// 'Zips up' this sequence with another collection into a single sequence of pairs.
  ///
  /// `zip()` returns a new sequence containing pairs where the first element comes from
  /// this sequence, and the second element comes from the other collection.
  ///
  /// If this sequence contains fewer elements than the other one, additional elements
  /// are created by calling the `to_left_value` closure, and the resulting sequence length
  /// is the length of the other sequence.
  ///
  /// If this sequence contains more elements than the other one, additional elements
  /// are created by calling the `to_right_value` closure, and the resulting sequence length
  /// is the length of this sequence.
  ///
  /// To 'undo' the result of zipping up two sequences, see [`unzip()`].
  ///
  /// [`unzip()`]: SequenceTo::unzip
  ///
  /// # Example
  ///
  /// ```
  /// use cantrip::*;
  ///
  /// # let a_source = vec![1, 2, 3];
  /// let a = vec![1, 2, 3];
  ///
  /// assert_eq!(a.zip_padded(vec![4, 5, 6], || 1, || 2), vec![(1, 4), (2, 5), (3, 6)],);
  /// # let a = a_source.clone();
  /// assert_eq!(a.zip_padded(vec![4, 5, 6, 7], || 1, || 2), vec![(1, 4), (2, 5), (3, 6), (1, 7)],);
  /// # let a = a_source.clone();
  /// assert_eq!(a.zip_padded(vec![4, 5], || 1, || 2), vec![(1, 4), (2, 5), (3, 2)],);
  /// ```
  #[inline]
  #[must_use]
  fn zip_padded<T>(
    self, elements: impl IntoIterator<Item = T>, mut to_left_value: impl FnMut() -> Item,
    mut to_right_value: impl FnMut() -> T,
  ) -> Self::This<(Item, T)>
  where
    Self: IntoIterator<Item = Item> + Sized,
    Self::This<(Item, T)>: FromIterator<(Item, T)>,
  {
    let mut left_iterator = self.into_iter();
    let mut right_iterator = elements.into_iter();
    unfold(|| match (left_iterator.next(), right_iterator.next()) {
      (Some(left), Some(right)) => Some((left, right)),
      (Some(left), None) => Some((left, to_right_value())),
      (None, Some(right)) => Some((to_left_value(), right)),
      (None, None) => None,
    })
    .collect()
  }
}

#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_truncation)]
#[inline]
pub(crate) fn collect_by_index<Item, Result>(values: &[&Item], indices: &[i64]) -> Result
where
  Item: Clone,
  Result: FromIterator<Item>,
{
  indices.iter().map(|index| values[*index as usize].clone()).collect::<Result>()
}

pub(crate) fn chunked<Item, Collection>(collection: Collection, size: usize, exact: bool) -> Vec<Collection>
where
  Collection: FromIterator<Item> + IntoIterator<Item = Item>,
{
  assert_ne!(size, 0, "chunk size must be non-zero");
  let mut iterator = collection.into_iter();
  unfold(|| {
    let mut chunk_size = 0;
    let chunk = unfold(|| {
      if chunk_size < size
        && let Some(item) = iterator.next()
      {
        chunk_size += 1;
        return Some(item);
      }
      None
    })
    .collect();
    if chunk_size == size || (!exact && chunk_size > 0) { Some(chunk) } else { None }
  })
  .collect()
}