bulks 0.6.6

Amazing bulks! They are like iterators, but in bulk, and therefore support collection into arrays.
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
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
use core::{fmt::Display, iter::Step, marker::Destruct, ops::{Add, ControlFlow, FromResidual, Mul, Residual, Try}};

use array_trait::length::{self, Length, LengthValue, Value};

use crate::{ArrayChunks, Chain, Cloned, CollectionAdapter, CollectionStrategy, Copied, DoubleEndedBulk, Enumerate, EnumerateFrom, FlatMap, Flatten, FromBulk, InplaceBulk, InplaceBulkSpec, Inspect, Intersperse, IntersperseWith, IntoBulk, IntoContained, IntoContainedBy, Map, MapWindows, Merge, Mutate, RandomAccessBulk, RandomAccessBulkSpec, Rev, Skip, SplitBulk, StaticBulk, StepBy, Take, TryCollectionAdapter, Zip, util};

//fn _assert_is_dyn_compatible(_: &dyn Bulk<Item = ()>) {}

/// A trait for dealing with bulks.
///
/// This is the main bulk trait. For more about the concept of bulks
/// generally, please see the [crate-level documentation](crate). In particular, you
/// may want to know how to [implement `Bulk`][crate#implementing-bulk].
#[rustc_on_unimplemented(
    on(
        Self = "core::ops::range::RangeTo<Idx>",
        note = "you might have meant to use a bounded `Range`"
    ),
    on(
        Self = "core::ops::range::RangeToInclusive<Idx>",
        note = "you might have meant to use a bounded `RangeInclusive`"
    ),
    label = "`{Self}` is not a bulk",
    message = "`{Self}` is not a bulk"
)]
#[doc(notable_trait)]
#[must_use = "bulks are lazy and do nothing unless consumed"]
pub const trait Bulk: ~const IntoBulk<IntoBulk = Self>
{
    type Length: Length<Elem = ()> + ?Sized = <Self as private::BulkBase>::Length;
    type MinLength: Length<Elem = ()> + ?Sized = [(); 0];
    type MaxLength: Length<Elem = ()> + ?Sized = [()];

    /// Returns the exact length of the bulk.
    ///
    /// This function has the same safety guarantees as the
    /// [`Iterator::size_hint`] function.
    /// 
    /// Similar to [`ExactSizeIterator::len`].
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// // a finite range knows exactly how many times it will iterate
    /// let mut range = (0..5).into_bulk();
    ///
    /// let len = range.len();
    /// 
    /// assert_eq!(len, 5);
    /// ```
    #[track_caller]
    fn len(&self) -> usize;

    fn length(&self) -> Value<Self::Length>
    {
        let len = self.len();
        let length = length::value::or_len(len);
        assert!(length::value::len(length) == len);
        length
    }

    /// Returns `true` if the iterator is empty.
    ///
    /// This method has a default implementation using
    /// [`Bulk::len()`], so you don't need to implement it yourself.
    /// 
    /// Similar to [`ExactSizeIterator::is_empty`].
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    ///
    /// let one_element = bulks::once(0);
    /// assert!(!one_element.is_empty());
    /// ```
    #[inline]
    #[track_caller]
    fn is_empty(&self) -> bool
    {
        self.len() == 0
    }

    /// Returns the first value, and discards the rest of the bulk.
    /// 
    /// Returns [`None`] if the bulk is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let bulk = a.bulk();
    /// 
    /// let a1 = bulk.first();
    /// assert_eq!(a1, Some(&1));
    /// ```
    fn first(self) -> Option<Self::Item>
    where
        Self::Item: ~const Destruct,
        Self: Sized
    {
        const fn break_on_first<T>(x: T) -> ControlFlow<T>
        {
            ControlFlow::Break(x)
        }

        match self.try_for_each(break_on_first)
        {
            ControlFlow::Break(first) => Some(first),
            ControlFlow::Continue(()) => None
        }
    }

    /// Returns the last value, and discards the rest of the bulk.
    /// 
    /// Returns [`None`] if the bulk is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let bulk = a.bulk();
    /// 
    /// let a1 = bulk.last();
    /// assert_eq!(a1, Some(&3));
    /// ```
    fn last(self) -> Option<Self::Item>
    where
        Self::Item: ~const Destruct,
        Self: Sized
    {
        const fn store<T>(_: T, x: T) -> T
        where
            T: ~const Destruct
        {
            x
        }

        self.reduce(store)
    }

    /// Returns the `n`-th value, and discards the rest of the bulk.
    /// 
    /// Returns [`None`] if index `n` is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let bulk = a.bulk();
    /// 
    /// // The bulk is consumed, so it must be cloned each time. Don't actually do this.
    /// let a1 = bulk.clone().first();
    /// let a2 = bulk.clone().nth(1);
    /// let a3 = bulk.clone().nth(2);
    /// let a4 = bulk.clone().nth(3);
    /// 
    /// assert_eq!(a1, Some(&1));
    /// assert_eq!(a2, Some(&2));
    /// assert_eq!(a3, Some(&3));
    /// assert_eq!(a4, None);
    /// ```
    fn nth<L>(self, n: L) -> Option<Self::Item>
    where
        Self: Sized,
        Self::Item: ~const Destruct,
        L: LengthValue
    {
        self.skip(n).first()
    }

    fn many<NN, const N: usize>(self, n: NN) -> [Option<Self::Item>; N]
    where
        Self: Sized,
        Self::Item: ~const Destruct,
        NN: ~const IntoBulk<Item = usize, IntoBulk: ~const Bulk + StaticBulk<Array<()> = [(); N]>>
    {
        // TODO: can be optimized by sorting first and storing permutations, then unsorting after.

        struct Functor<'a, T, const N: usize>
        {
            done: usize,
            refs: &'a mut [Result<T, usize>; N]
        }
        impl<'a, T, const N: usize> Functor<'a, T, N>
        {
            const fn update(&mut self, i: usize, x: T)
            where
                T: ~const Destruct
            {
                const trait ManySpec: Sized
                {
                    fn update<const N: usize>(refs: &mut [Result<Self, usize>; N], k: &mut usize, i: usize, x: Self);
                }
                impl<T> const ManySpec for T
                where
                    T: ~const Destruct
                {
                    default fn update<const N: usize>(refs: &mut [Result<Self, usize>; N], k: &mut usize, i: usize, x: Self)
                    {
                        while *k < N
                        {
                            if let Err(j) = &refs[*k]
                            {
                                if *j == i
                                {
                                    refs[*k] = Ok(x);
                                    return
                                }
                                else
                                {
                                    break
                                }
                            }
                            *k += 1
                        }
                        let mut n = *k;
                        while n < N
                        {
                            if let Err(j) = &refs[n] && *j == i
                            {
                                refs[n] = Ok(x);
                                return
                            }
                            n += 1
                        }
                    }
                }
                impl<T> const ManySpec for T
                where
                    T: Copy + ~const Destruct
                {
                    fn update<const N: usize>(refs: &mut [Result<Self, usize>; N], k: &mut usize, i: usize, x: Self)
                    {
                        while *k < N
                        {
                            if let Err(j) = &refs[*k]
                            {
                                if *j == i
                                {
                                    refs[*k] = Ok(x)
                                }
                                else
                                {
                                    break
                                }
                            }
                            *k += 1
                        }
                        let mut n = *k;
                        while n < N
                        {
                            if let Err(j) = &refs[n] && *j == i
                            {
                                refs[n] = Ok(x)
                            }
                            n += 1
                        }
                    }
                }

                ManySpec::update(self.refs, &mut self.done, i, x);
            }
        }

        impl<'a, T, const N: usize> const FnOnce<((usize, T),)> for Functor<'a, T, N>
        where
            T: ~const Destruct
        {
            type Output = ();

            extern "rust-call" fn call_once(mut self, args: ((usize, T),)) -> Self::Output
            {
                self.call_mut(args)
            }
        }
        impl<'a, T, const N: usize> const FnMut<((usize, T),)> for Functor<'a, T, N>
        where
            T: ~const Destruct
        {
            extern "rust-call" fn call_mut(&mut self, ((i, x),): ((usize, T),)) -> Self::Output
            {
                self.update(i, x);
            }
        }

        let mut refs = n.into_bulk()
            .map(Err)
            .collect_array();

        self.enumerate()
            .for_each(Functor {
                done: 0,
                refs: &mut refs
            });

        refs.map(Result::ok)
    }

    /// Calls a closure on each element of a bulk.
    ///
    /// This is equivalent to using a [`for`] loop on the bulk, although
    /// `break` and `continue` are not possible from a closure. It's generally
    /// more idiomatic to use a `for` loop, but `for_each` may be more legible
    /// when processing items at the end of longer iterator chains. In some
    /// cases `for_each` may also be faster than a loop, because it will use
    /// internal iteration on adapters like [`Chain`](crate::Chain).
    ///
    /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    ///
    /// let a = [1, 2, 3, 4];
    /// let mut x0 = 0;
    /// a.into_bulk()
    ///     .for_each(|x| {
    ///         assert_eq!(x, x0 + 1);
    ///         x0 = x;
    ///     })
    /// ```
    fn for_each<F>(self, f: F)
    where
        Self: Sized,
        F: ~const FnMut(Self::Item) + ~const Destruct;

    /// A bulk method that applies a fallible function to each item in the
    /// bulk, stopping at the first error and returning that error.
    ///
    /// This can also be thought of as the fallible form of [`for_each()`](Bulk::for_each)
    /// or as the stateless version of [`try_fold()`](Bulk::try_fold).
    ///
    /// # Examples
    ///
    /// ```
    /// use bulks::*;
    ///
    /// let a = ["1", "2", "3", "4", "wrong"];
    /// let mut x0 = 0;
    /// let res = a.into_bulk()
    ///     .try_for_each(|x| {
    ///         let x = x.parse::<u32>().map_err(|_| x)?;
    ///         assert_eq!(x, x0 + 1);
    ///         x0 = x;
    ///         Ok(())
    ///     });
    /// assert_eq!(res, Err("wrong"))
    /// ```
    fn try_for_each<F, R>(self, f: F) -> R
    where
        Self: Sized,
        Self::Item: ~const Destruct,
        F: ~const FnMut(Self::Item) -> R + ~const Destruct,
        R: ~const Try<Output = (), Residual: ~const Destruct>;

    /// Folds every element into an accumulator by applying an operation,
    /// returning the final result.
    ///
    /// `fold()` takes two arguments: an initial value, and a closure with two
    /// arguments: an 'accumulator', and an element. The closure returns the value that
    /// the accumulator should have for the next iteration.
    ///
    /// The initial value is the value the accumulator will have on the first
    /// call.
    ///
    /// After applying this closure to every element of the iterator, `fold()`
    /// returns the accumulator.
    ///
    /// This operation is sometimes called 'reduce' or 'inject'.
    ///
    /// Folding is useful whenever you have a collection of something, and want
    /// to produce a single value from it.
    ///
    /// Note: [`reduce()`](Bulk::reduce) can be used to use the first element as the initial
    /// value, if the accumulator type and item type is the same.
    ///
    /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
    /// operators like `+`, the order the elements are combined in is not important, but for non-associative
    /// operators like `-` the order will affect the final result.
    /// For a *right-associative* version of `fold()`, see [`DoubleEndedBulk::rfold()`].
    ///
    /// # Note to Implementors
    ///
    /// Several of the other (forward) methods have default implementations in
    /// terms of this one, so try to implement this explicitly if it can
    /// do something better than the default `for` loop implementation.
    ///
    /// In particular, try to have this call `fold()` on the internal parts
    /// from which this iterator is composed.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// // the sum of all of the elements of the array
    /// let sum = a.bulk().fold(0, |acc, x| acc + x);
    ///
    /// assert_eq!(sum, 6);
    /// ```
    ///
    /// Let's walk through each step of the iteration here:
    ///
    /// | element | acc | x | result |
    /// |---------|-----|---|--------|
    /// |         | 0   |   |        |
    /// | 1       | 0   | 1 | 1      |
    /// | 2       | 1   | 2 | 3      |
    /// | 3       | 3   | 3 | 6      |
    ///
    /// And so, our final result, `6`.
    ///
    /// This example demonstrates the left-associative nature of `fold()`:
    /// it builds a string, starting with an initial value
    /// and continuing with each element from the front until the back:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let numbers = [1, 2, 3, 4, 5];
    ///
    /// let zero = "0".to_string();
    ///
    /// let result = numbers.bulk().fold(zero, |acc, &x| {
    ///     format!("({acc} + {x})")
    /// });
    ///
    /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
    /// ```
    /// It's common for people who haven't used iterators a lot to
    /// use a `for` loop with a list of things to build up a result. Those
    /// can be turned into `fold()`s:
    ///
    /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let numbers = [1, 2, 3, 4, 5];
    ///
    /// let mut result = 0;
    ///
    /// // for loop:
    /// for i in &numbers {
    ///     result = result + i;
    /// }
    ///
    /// // fold:
    /// let result2 = numbers.bulk().fold(0, |acc, &x| acc + x);
    ///
    /// // they're the same
    /// assert_eq!(result, result2);
    /// ```
    #[doc(alias = "inject", alias = "foldl")]
    #[inline]
    fn fold<B, F>(self, init: B, f: F) -> B
    where
        Self: Sized,
        B: ~const Destruct,
        F: ~const FnMut(B, Self::Item) -> B + ~const Destruct
    {
        struct Closure<'a, B, F>
        {
            z: &'a mut Option<B>,
            f: F
        }
        impl<'a, B, F, T> const FnOnce<(T,)> for Closure<'a, B, F>
        where
            B: ~const Destruct,
            F: ~const FnOnce(B, T) -> B,
        {
            type Output = ();

            extern "rust-call" fn call_once(self, (x,): (T,)) -> Self::Output
            {
                let Self { z, f } = self;
                let zz = unsafe {z.take().unwrap_unchecked()};
                let _ = z.insert((f)(zz, x));
            }
        }
        impl<'a, B, F, T> const FnMut<(T,)> for Closure<'a, B, F>
        where
            B: ~const Destruct,
            F: ~const FnMut(B, T) -> B,
        {
            extern "rust-call" fn call_mut(&mut self, (x,): (T,)) -> Self::Output
            {
                let Self { z, f } = self;
                let zz = unsafe {z.take().unwrap_unchecked()};
                let _ = z.insert((f)(zz, x));
            }
        }

        let mut z = Some(init);
        self.for_each(Closure {
            z: &mut z,
            f
        });

        unsafe {
            z.unwrap_unchecked()
        }
    }

    fn try_fold<B, F, R>(self, init: B, f: F) -> R
    where
        B: ~const Destruct,
        Self: Sized,
        Self::Item: ~const Destruct,
        F: ~const FnMut(B, Self::Item) -> R + ~const Destruct,
        R: ~const Try<Output = B, Residual: ~const Destruct>
    {
        struct Closure<'a, B, F>
        {
            z: &'a mut Option<B>,
            f: F
        }
        impl<'a, B, F, T, R> const FnOnce<(T,)> for Closure<'a, B, F>
        where
            B: ~const Destruct,
            F: ~const FnOnce(B, T) -> R,
            R: ~const Try<Output = B, Residual: ~const Destruct>
        {
            type Output = ControlFlow<R::Residual, ()>;

            extern "rust-call" fn call_once(self, (x,): (T,)) -> Self::Output
            {
                let Self { z, f } = self;
                let zz = unsafe {z.take().unwrap_unchecked()};
                let _ = z.insert(f(zz, x).branch()?);
                ControlFlow::Continue(())
            }
        }
        impl<'a, B, F, T, R> const FnMut<(T,)> for Closure<'a, B, F>
        where
            B: ~const Destruct,
            F: ~const FnMut(B, T) -> R,
            R: ~const Try<Output = B, Residual: ~const Destruct>
        {
            extern "rust-call" fn call_mut(&mut self, (x,): (T,)) -> Self::Output
            {
                let Self { z, f } = self;
                let zz = unsafe {z.take().unwrap_unchecked()};
                let _ = z.insert(f(zz, x).branch()?);
                ControlFlow::Continue(())
            }
        }

        let mut z = Some(init);
        match self.try_for_each(Closure {
            z: &mut z,
            f
        })
        {
            ControlFlow::Break(residual) => R::from_residual(residual),
            ControlFlow::Continue(()) => R::from_output(unsafe {
                z.unwrap_unchecked()
            })
        }
    }

    fn reduce<F>(self, f: F) -> Option<Self::Item>
    where 
        Self: Sized,
        Self::Item: ~const Destruct,
        F: ~const FnMut(Self::Item, Self::Item) -> Self::Item + ~const Destruct
    {
        struct Closure<F>
        {
            f: F
        }
        impl<F, T> const FnOnce<(Option<T>, T)> for Closure<F>
        where
            F: ~const FnOnce(T, T) -> T + ~const Destruct
        {
            type Output = Option<T>;

            extern "rust-call" fn call_once(self, (z, x): (Option<T>, T)) -> Self::Output
            {
                let Self { f } = self;

                match z
                {
                    Some(z) => Some(f(z, x)),
                    None => Some(x)
                }
            }
        }
        impl<F, T> const FnMut<(Option<T>, T)> for Closure<F>
        where
            F: ~const FnMut(T, T) -> T
        {
            extern "rust-call" fn call_mut(&mut self, (z, x): (Option<T>, T)) -> Self::Output
            {
                let Self { f } = self;

                match z
                {
                    Some(z) => Some(f(z, x)),
                    None => Some(x)
                }
            }
        }

        self.fold(None, Closure {
            f
        })
    }

    fn try_reduce<F, R>(self, f: F) -> <R::Residual as Residual<Option<R::Output>>>::TryType
    where
        Self: Sized,
        Self::Item: ~const Destruct,
        F: ~const FnMut(Self::Item, Self::Item) -> R + ~const Destruct,
        R: ~const Try<Output = Self::Item, Residual: Residual<Option<Self::Item>, TryType: ~const Try> + ~const Destruct>
    {
        struct Closure<F>
        {
            f: F
        }
        impl<F, T, R> const FnOnce<(Option<T>, T)> for Closure<F>
        where
            F: ~const FnOnce(T, T) -> R + ~const Destruct,
            R: ~const Try<Output = T, Residual: ~const Destruct>
        {
            type Output = ControlFlow<R::Residual, Option<T>>;

            extern "rust-call" fn call_once(self, (z, x): (Option<T>, T)) -> Self::Output
            {
                let Self { f } = self;

                ControlFlow::Continue(Some(
                    match z
                    {
                        Some(z) => f(z, x).branch()?,
                        None => x
                    }
                ))
            }
        }
        impl<F, T, R> const FnMut<(Option<T>, T)> for Closure<F>
        where
            F: ~const FnMut(T, T) -> R,
            R: ~const Try<Output = T, Residual: ~const Destruct>
        {
            extern "rust-call" fn call_mut(&mut self, (z, x): (Option<T>, T)) -> Self::Output
            {
                let Self { f } = self;

                ControlFlow::Continue(Some(
                    match z
                    {
                        Some(z) => f(z, x).branch()?,
                        None => x
                    }
                ))
            }
        }

        match self.try_fold(None, Closure {
            f
        })
        {
            ControlFlow::Break(residual) => FromResidual::from_residual(residual),
            ControlFlow::Continue(output) => Try::from_output(output)
        }
    }
    
    /// Creates a bulk starting at the same point, but stepping by
    /// the given amount at each iteration.
    /// 
    /// Similar to [`Iterator::step_by`].
    ///
    /// # Panics
    ///
    /// The method will panic if the given step is `0`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let a = [0, 1, 2, 3, 4, 5];
    /// 
    /// let mut bulk = a.into_bulk().step_by([(); 2]);
    /// let a_even: [_; _] = bulk.collect();
    ///
    /// assert_eq!(a_even, [0, 2, 4]);
    /// 
    /// let mut bulk = a.into_bulk().skip([(); 1]).step_by([(); 2]);
    /// let a_odd: [_; _] = bulk.collect();
    /// 
    /// assert_eq!(a_odd, [1, 3, 5]);
    /// ```
    #[inline]
    #[track_caller]
    fn step_by<L>(self, step: L) -> StepBy<Self, L::Length<()>>
    where
        Self: Sized,
        L: LengthValue
    {
        StepBy::new(self, step)
    }

    /// Takes two bulks and creates a new bulk over both in sequence.
    ///
    /// In other words, it links two bulks together, in a chain. 🔗
    /// 
    /// Similar to [`Iterator::chain`].
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let s1 = b"abc";
    /// let s2 = b"def";
    ///
    /// let mut bulk = s1.into_bulk()
    ///     .chain(s2)
    ///     .copied();
    /// 
    /// let s: [_; _] = bulk.collect();
    /// 
    /// assert_eq!(s, *b"abcdef");
    /// ```
    ///
    /// Since the argument to [`chain()`](Bulk::chain) uses [`IntoBulk`], we can pass
    /// anything that can be converted into a [`Bulk`], not just a
    /// [`Bulk`] itself. For example, arrays (`[T; _]`) implement
    /// [`IntoBulk`], and so can be passed to [`chain()`](Bulk::chain) directly:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let a1 = [1, 2, 3];
    /// let a2 = [4, 5, 6];
    ///
    /// let mut bulk = a1.into_bulk()
    ///     .chain(a2);
    /// 
    /// let a: [_; _] = bulk.collect();
    /// 
    /// assert_eq!(a, [1, 2, 3, 4, 5, 6]);
    /// ```
    #[inline]
    #[track_caller]
    fn chain<U>(self, other: U) -> Chain<Self, U::IntoBulk>
    where
        Self: Sized,
        U: ~const IntoBulk<Item = Self::Item>,
    {
        Chain::new(self, other.into_bulk())
    }

    /// 'Zips up' two bulks or iterators into a single bulk of pairs. One of them must be a bulk.
    /// 
    /// Similar to [`Iterator::zip`].
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let s1 = b"abc".into_bulk().copied();
    /// let s2 = b"def".into_bulk().copied();
    ///
    /// let mut bulk = s1.zip(s2);
    /// 
    /// let s: [_; _] = bulk.collect();
    /// 
    /// assert_eq!(s, [(b'a', b'd'), (b'b', b'e'), (b'c', b'f')]);
    /// ```
    ///
    /// Since the argument to [`zip()`](Bulk::zip) uses [`IntoBulk`], we can pass
    /// anything that can be converted into a [`Bulk`], not just a
    /// [`Bulk`] itself. For example, arrays (`[T]`) implement
    /// [`IntoBulk`], and so can be passed to [`zip()`](Bulk::zip) directly:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let a1 = [1, 2, 3];
    /// let a2 = [4, 5, 6];
    ///
    /// let mut bulk = a1.into_bulk().zip(a2);
    ///
    /// let a: [_; _] = bulk.collect();
    /// 
    /// assert_eq!(a, [(1, 4), (2, 5), (3, 6)]);
    /// ```
    ///
    /// `zip()` is often used to zip an infinite iterator to a finite one.
    /// This works because the finite iterator will eventually return [`None`],
    /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let enumerate: [_; _] = (*b"foo").into_bulk().enumerate().collect();
    ///
    /// let zipper: Vec<_> = bulks::rzip(0.., *b"foo").collect();
    /// 
    /// assert_eq!((0, b'f'), enumerate[0]);
    /// assert_eq!((0, b'f'), zipper[0]);
    /// 
    /// assert_eq!((1, b'o'), enumerate[1]);
    /// assert_eq!((1, b'o'), zipper[1]);
    /// 
    /// assert_eq!((2, b'o'), enumerate[2]);
    /// assert_eq!((2, b'o'), zipper[2]);
    /// ```
    ///
    /// It can be more readable to use [`bulks::zip`](crate::zip):
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    ///
    /// let a = [1, 2, 3];
    /// let b = [2, 3, 4];
    ///
    /// let mut zipped = bulks::zip(
    ///     a.into_bulk().map(|x| x * 2).skip([(); 1]),
    ///     b.into_bulk().map(|x| x * 2).skip([(); 1]),
    /// );
    /// 
    /// let c: [_; _] = zipped.collect();
    /// 
    /// assert_eq!(c, [(4, 6), (6, 8)]);
    /// ```
    ///
    /// compared to:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// # use bulks::*;
    /// #
    /// # let a = [1, 2, 3];
    /// # let b = [2, 3, 4];
    /// #
    /// let mut zipped = a.into_bulk()
    ///     .map(|x| x * 2)
    ///     .skip([(); 1])
    ///     .zip(b.into_bulk()
    ///         .map(|x| x * 2)
    ///         .skip([(); 1])
    ///     );
    /// #
    /// # let c: [_; _] = zipped.collect();
    /// # assert_eq!(c, [(4, 6), (6, 8)]);
    /// ```
    #[inline]
    #[track_caller]
    fn zip<U>(self, other: U) -> Zip<Self, <<U as IntoContained>::IntoContained as IntoBulk>::IntoBulk>
    where
        Self: Sized,
        U: ~const IntoContainedBy<Self>
    {
        crate::zip(self, other)
    }

    /// Merges two bulks or iterators into a single bulk using a merging function.
    /// 
    /// Similar to [`Bulk::zip`], followed by [`Bulk::map`], but keeps the tail if the length of the two bulks differ.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let s1 = b"abc".into_bulk().copied();
    /// let s2 = b"def".into_bulk().copied();
    ///
    /// let mut bulk = s1.merge(s2, Add::add);
    /// 
    /// let s: [_; _] = bulk.collect();
    /// 
    /// assert_eq!(s, [b'a' + b'd', b'b' + b'e', b'c' + b'f', b'g']);
    /// ```
    #[inline]
    #[track_caller]
    fn merge<U, F, O>(self, other: U, merger: F) -> Merge<Self, U::IntoBulk, F>
    where
        Self: Sized,
        U: ~const IntoBulk,
        Self::Item: Into<O>,
        U::Item: Into<O>,
        F: FnMut(Self::Item, U::Item) -> O
    {
        crate::merge(self, other, merger)
    }

    /// Creates a new bulk which places a copy of `separator` between adjacent
    /// items of the original bulk.
    /// 
    /// Similar to [`Iterator::intersperse`].
    ///
    /// In case `separator` does not implement [`Clone`](core::clone::Clone) or needs to be
    /// computed every time, use [`intersperse_with`](Bulk::intersperse_with).
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let mut a: [_; _] = [0, 1, 2].into_bulk().intersperse(100).collect();
    /// 
    /// assert_eq!(a, [0, 100, 1, 100, 2]);
    /// ```
    ///
    /// `intersperse` can be very useful to join a bulk's items using a common element:
    /// ```
    /// use bulks::*;
    ///
    /// let words = ["Hello", "World", "!"];
    /// let hello: String = words.into_bulk().intersperse(" ").collect();
    /// assert_eq!(hello, "Hello World !");
    /// ```
    #[inline]
    #[track_caller]
    fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
    where
        Self: Sized,
        Self::Item: Clone,
    {
        Intersperse::new(self, separator)
    }

    /// Creates a new bulk which places an item generated by `separator`
    /// between adjacent items of the original bulk.
    ///
    /// The closure will be called exactly once each time an item is placed
    /// between two adjacent items from the underlying bulk; specifically,
    /// the closure is not called if the underlying bulk has less than
    /// two items.
    /// 
    /// Similar to [`Iterator::intersperse_with`].
    ///
    /// If the bulk's item implements [`Clone`](core::clone::Clone), it may be easier to use
    /// [`intersperse`](Bulk::intersperse).
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    ///
    /// #[derive(PartialEq, Debug)]
    /// struct NotClone(usize);
    ///
    /// let v = [NotClone(0), NotClone(1), NotClone(2)];
    /// let u: [_; _] = v.into_bulk().intersperse_with(|| NotClone(99)).collect();
    ///
    /// assert_eq!(u, [NotClone(0), NotClone(99), NotClone(1), NotClone(99), NotClone(2)]);
    /// ```
    ///
    /// [`intersperse_with`](Bulk::intersperse_with) can be used in situations where the separator needs
    /// to be computed:
    /// ```
    /// use bulks::*;
    ///
    /// let src = ["Hello", "to", "all", "people", "!!"].bulk().copied();
    ///
    /// // The closure mutably borrows its context to generate an item.
    /// let mut happy_emojis = [" ❤️ ", " 😀 "].into_iter();
    /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
    ///
    /// let result: String = src.intersperse_with(separator).collect();
    /// 
    /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
    /// ```
    #[inline]
    #[track_caller]
    fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
    where
        Self: Sized,
        G: FnMut() -> Self::Item,
    {
        IntersperseWith::new(self, separator)
    }

    /// Takes a closure and creates a bulk which calls that closure on each
    /// element.
    ///
    /// [`map()`](Bulk::map) transforms one bulk into another, by means of its argument:
    /// something that implements [`FnMut`]. It produces a new bulk which
    /// calls this closure on each element of the original bulk.
    /// 
    /// Similar to [`Iterator::map`].
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let mut b: [_; _] = a.bulk().map(|x| 2 * x).collect();
    ///
    /// assert_eq!(b, [2, 4, 6]);
    /// ```
    ///
    /// If you're doing some sort of side effect, prefer [`for`] to [`map()`](Bulk::map):
    ///
    /// ```
    /// # #![allow(unused_must_use)]
    /// use bulks::*;
    /// 
    /// // don't do this:
    /// (0..5).into_bulk().map(|x| println!("{x}"));
    ///
    /// // it won't even execute, as it is lazy. Rust will warn you about this.
    ///
    /// // Instead, use a for-loop:
    /// for x in (0..5).into_bulk()
    /// {
    ///     println!("{x}");
    /// }
    /// ```
    /// 
    /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
    #[inline]
    #[track_caller]
    fn map<B, F>(self, f: F) -> Map<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Item) -> B,
    {
        Map::new(self, f)
    }

    /// Creates a bulk which gives the current index together with its values.
    ///
    /// The bulk returned yields pairs `(i, val)`, where `i` is the
    /// current index of iteration and `val` is its corresponding value.
    /// 
    /// Similar to [`Iterator::enumerate`].
    ///
    /// [`enumerate()`](Bulk::enumerate) keeps its count as a [`usize`]. If you want to count by a
    /// different sized integer, use [`enumerate_from`](Bulk::enumerate_from) instead.
    ///
    /// # Overflow Behavior
    ///
    /// The method does no guarding against overflows, so enumerating more than
    /// [`usize::MAX`] elements either produces the wrong result or panics. If
    /// overflow checks are enabled, a panic is guaranteed.
    ///
    /// # Panics
    ///
    /// The returned bulk might panic if the to-be-returned index would
    /// overflow a [`usize`].
    ///
    /// # Examples
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = ['a', 'b', 'c'];
    ///
    /// let b = a.into_bulk()
    ///     .enumerate()
    ///     .collect_array();
    ///
    /// assert_eq!(b, [(0, 'a'), (1, 'b'), (2, 'c')]);
    /// ```
    #[inline]
    #[track_caller]
    fn enumerate(self) -> Enumerate<Self>
    where
        Self: Sized
    {
        Enumerate::new(self)
    }

    /// Creates a bulk which gives the current index counting from a given initial index together with its values.
    ///
    /// The bulk returned yields pairs `(i, val)`, where `i` is the
    /// current index of iteration and `val` is its corresponding value.
    /// 
    /// This is similar to [`Bulk::enumerate`], except here a different type and initial value for counting can be used.
    /// For counting an [`usize`] from 0 and up, [`Bulk::enumerate`] is a better alternative.
    ///
    /// # Overflow Behavior
    ///
    /// The method does no guarding against overflows, so enumerating more elements than supported values of `U`
    /// either produces the wrong result or panics. If
    /// overflow checks are enabled, a panic will happen depending how [`Step::forward`] is implemented for `U`.
    ///
    /// # Panics
    ///
    /// The returned bulk might panic if the to-be-returned index would
    /// overflow.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = ['a', 'b', 'c'];
    ///
    /// let b = a.into_bulk()
    ///     .enumerate_from(1)
    ///     .collect_array();
    ///
    /// assert_eq!(b, [(1, 'a'), (2, 'b'), (3, 'c')]);
    /// ```
    #[inline]
    #[track_caller]
    fn enumerate_from<U>(self, initial_count: U) -> EnumerateFrom<Self, U>
    where
        Self: Sized,
        U: Step + Copy
    {
        EnumerateFrom::new(self, initial_count)
    }

    /// Creates a bulk that skips the first `n` elements.
    /// 
    /// Similar to [`Iterator::skip`].
    ///
    /// [`skip(n)`](Bulk::skip) skips elements until `n` elements are skipped or the end of the
    /// bulk is reached (whichever happens first). The returned bulk will yield the remaining elements.
    /// If the original bulk is too short, then the returned bulk is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let b: [_; _] = a.into_bulk().skip([(); 2]).collect();
    /// let c: Vec<_> = a.into_bulk().skip(2).collect();
    ///
    /// assert_eq!(b, [3]);
    /// assert_eq!(c, [3]);
    /// ```
    #[inline]
    #[track_caller]
    fn skip<L>(self, n: L) -> Skip<Self, L::Length<()>>
    where
        Self: Sized,
        L: LengthValue
    {
        Skip::new(self, n)
    }

    /// Creates a bulk for the first `n` elements, or fewer
    /// if the underlying bulk/iterator is shorter.
    ///
    /// [`take(n)`](Bulk::take) yields elements until `n` elements are yielded or the end of the
    /// bulk is reached (whichever happens first).
    /// The returned bulk is a prefix of length `n` if the original bulk/iterator
    /// contains at least `n` elements, otherwise it contains all of the
    /// (fewer than `n`) elements of the original bulk/iterator.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let b: Vec<_> = a.into_bulk().take([(); 2]).collect();
    ///
    /// assert_eq!(b, [1, 2]);
    /// ```
    ///
    /// `take()` is often used with an infinite iterator, to make it finite:
    ///
    /// ```
    /// let a: Vec<_> = (0..).take(3).collect();
    ///
    /// assert_eq!(a, [0, 1, 2])
    /// ```
    ///
    /// If less than `n` elements are available,
    /// [`take`](Bulk::take) will limit itself to the size of the underlying bulk/iterator:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let v = [1, 2];
    /// let b: [_; _] = v.into_bulk().take([(); 5]).collect();
    /// 
    /// assert_eq!(b, [1, 2])
    /// ```
    #[doc(alias = "limit")]
    #[inline]
    #[track_caller]
    fn take<L>(self, n: L) -> Take<Self, L::Length<()>>
    where
        Self: Sized,
        L: LengthValue
    {
        Take::new(self, n)
    }

    /// Creates a bulk that works like map, but flattens nested structure.
    ///
    /// The [`map`](Bulk::map) adapter is very useful, but only when the closure
    /// argument produces values. If it produces something iterable instead, there's
    /// an extra layer of indirection. [`flat_map()`](Bulk::flat_map) will remove this extra layer
    /// on its own.
    /// 
    /// Similar to [`Iterator::flat_map`].
    ///
    /// You can think of `flat_map(f)` as the semantic equivalent
    /// of [`map`](Bulk::map)ping, and then [`flatten`](Bulk::flatten)ing as in `map(f).flatten()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let words = [b"alpha", b"beta ", b"gamma"];
    ///
    /// let merged: String = words.into_bulk()
    ///     .flat_map(|&s| s.into_bulk().map(|b| char::from(b)))
    ///     .collect();
    /// assert_eq!(merged, "alphabeta gamma");
    /// ```
    #[inline]
    #[track_caller]
    fn flat_map<U, F>(self, f: F) -> FlatMap<Self, F>
    where
        Self: Sized,
        U: IntoBulk<IntoBulk: StaticBulk>,
        F: FnMut(Self::Item) -> U,
    {
        FlatMap::new(self, f)
    }

    /// Creates a bulk that flattens nested structure.
    ///
    /// This is useful when you have a bulk of bulk or a bulk of
    /// things that can be turned into bulks and you want to remove one
    /// level of indirection.
    /// 
    /// Similar to [`Iterator::flatten`].
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let data = [[1, 2, 3], [4, 5, 6]];
    /// let flattened: [_; _] = data.into_bulk().flatten().collect();
    /// assert_eq!(flattened, [1, 2, 3, 4, 5, 6]);
    /// ```
    ///
    /// Mapping and then flattening:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let words = [b"alpha", b"beta ", b"gamma"];
    ///
    /// let merged: String = words.into_bulk()
    ///     .map(|&s| s.into_bulk().map(|b| char::from(b)))
    ///     .flatten()
    ///     .collect();
    /// assert_eq!(merged, "alphabeta gamma");
    /// ```
    ///
    /// You can also rewrite this in terms of [`flat_map()`](Bulk::flat_map), which is preferable
    /// in this case since it conveys intent more clearly:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let words = [b"alpha", b"beta ", b"gamma"];
    ///
    /// let merged: String = words.into_bulk()
    ///     .flat_map(|&s| s.into_bulk().map(|b| char::from(b)))
    ///     .collect();
    /// assert_eq!(merged, "alphabeta gamma");
    /// ```
    ///
    /// Flattening only removes one level of nesting at a time:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
    ///
    /// let d2: [_; _] = d3.into_bulk().flatten().collect();
    /// assert_eq!(d2, [[1, 2], [3, 4], [5, 6], [7, 8]]);
    ///
    /// let d1: [_; _] = d3.into_bulk().flatten().flatten().collect();
    /// assert_eq!(d1, [1, 2, 3, 4, 5, 6, 7, 8]);
    /// ```
    ///
    /// Here we see that [`flatten()`](Bulk::flatten) does not perform a "deep" flatten.
    /// Instead, only one level of nesting is removed. That is, if you
    /// [`flatten()`](Bulk::flatten) a three-dimensional array, the result will be
    /// two-dimensional and not one-dimensional. To get a one-dimensional
    /// structure, you have to [`flatten()`](Bulk::flatten) again.
    #[inline]
    #[track_caller]
    fn flatten(self) -> Flatten<Self>
    where
        Self: Sized,
        Self::Item: IntoBulk<IntoBulk: StaticBulk>,
    {
        Flatten::new(self)
    }

    /// Calls the given function `f` for each contiguous window of size `N` over
    /// `self` and returns a bulk of the outputs of `f`. The windows during mapping will overlap.
    /// 
    /// Similar to [`Iterator::map_windows`].
    ///
    /// In the following example, the closure is called three times with the
    /// arguments `&['a', 'b']`, `&['b', 'c']` and `&['c', 'd']` respectively.
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    ///
    /// let strings: [_; _] = b"abcd".bulk()
    ///     .map(|&c| char::from(c))
    ///     .map_windows(|[x, y]| format!("{}+{}", x, y))
    ///     .collect();
    ///
    /// assert_eq!(strings, ["a+b", "b+c", "c+d"]);
    /// ```
    ///
    /// Note that the const parameter `N` is usually inferred by the
    /// destructured argument in the closure.
    ///
    /// The returned bulk yields 𝑘 − `N` + 1 items (where 𝑘 is the number of
    /// items yielded by `self`). If 𝑘 is less than `N`, this method yields an
    /// empty bulk.
    ///
    /// # Panics
    ///
    /// Panics if `N` is zero.
    ///
    /// ```should_panic
    /// use bulks::*;
    ///
    /// let bulk = [0].into_bulk().map_windows(|&[]| ());
    /// ```
    ///
    /// # Examples
    ///
    /// Building the sums of neighboring numbers.
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    ///
    /// let w: [_; _] = [1, 3, 8, 1].bulk()
    ///     .map_windows(|&[a, b]| a + b)
    ///     .collect();
    /// 
    /// assert_eq!(w, [1 + 3, 3 + 8, 8 + 1]);
    /// ```
    ///
    /// Since the elements in the following example implement [`Copy`], we can
    /// just copy the array and get a bulk of the windows.
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    ///
    /// let w: [[_; _]; _] = b"ferris".bulk()
    ///     .map_windows(|w: &[_; 3]| w.bulk()
    ///         .copied()
    ///         .copied()
    ///         .collect())
    ///     .collect();
    /// 
    /// assert_eq!(w, [[b'f', b'e', b'r'], [b'e', b'r', b'r'], [b'r', b'r', b'i'], [b'r', b'i', b's']]);
    /// ```
    ///
    /// You can also use this function to check the sortedness of a bulk.
    /// For the simple case, rather use [`Bulk::is_sorted`].
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    ///
    /// let w: [_; _] = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].bulk()
    ///     .map_windows(|[a, b]| a <= b)
    ///     .collect();
    /// 
    /// assert_eq!(w, [true, true, false, true, true, false]);
    /// ```
    #[inline]
    #[track_caller]
    fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
    where
        Self: Sized,
        F: FnMut(&[Self::Item; N]) -> R,
    {
        MapWindows::new(self, f)
    }

    /// Does something with each element of a bulk, passing the value on.
    ///
    /// When using bulks, you'll often chain several of them together.
    /// While working on such code, you might want to check out what's
    /// happening at various parts in the pipeline. To do that, insert
    /// a call to [`inspect()`](Bulk::inspect).
    /// 
    /// Similar to [`Iterator::inspect`].
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 4, 2, 3];
    ///
    /// // this iterator sequence is complex.
    /// let sum = a.bulk()
    ///     .cloned()
    ///     .map(|x| if x % 2 == 0 {Some(x)} else {None})
    ///     .fold(0, |sum, i| sum + i.unwrap_or(0));
    ///
    /// println!("{sum}");
    ///
    /// // let's add some inspect() calls to investigate what's happening
    /// let sum = a.bulk()
    ///     .cloned()
    ///     .inspect(|x| println!("about to filter: {x}"))
    ///     .map(|x| if x % 2 == 0 {Some(x)} else {None})
    ///     .inspect(|x| if let Some(x) = x {println!("made it through filter: {x}")})
    ///     .fold(0, |sum, i| sum + i.unwrap_or(0));
    ///
    /// 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
    /// ```
    ///
    /// Logging errors before discarding them:
    ///
    /// ```
    /// let lines = ["1", "2", "a"];
    ///
    /// let sum: i32 = lines
    ///     .iter()
    ///     .map(|line| line.parse::<i32>())
    ///     .inspect(|num| {
    ///         if let Err(ref e) = *num {
    ///             println!("Parsing error: {e}");
    ///         }
    ///     })
    ///     .filter_map(Result::ok)
    ///     .sum();
    ///
    /// println!("Sum: {sum}");
    /// ```
    ///
    /// This will print:
    ///
    /// ```text
    /// Parsing error: invalid digit found in string
    /// Sum: 3
    /// ```
    #[inline]
    #[track_caller]
    fn inspect<F>(self, f: F) -> Inspect<Self, F>
    where
        Self: Sized,
        F: FnMut(&Self::Item),
    {
        Inspect::new(self, f)
    }

    /// Mutates with each element of a bulk, passing the value on.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 4, 2, 3];
    ///
    /// // this iterator sequence is complex.
    /// let b: [_; _] = a.into_bulk()
    ///     .mutate(|x| *x += 1)
    ///     .collect();
    ///
    /// assert_eq!(b, [2, 5, 3, 4]);
    /// ```
    #[inline]
    #[track_caller]
    fn mutate<F>(self, f: F) -> Mutate<Self, F>
    where
        Self: Sized,
        F: FnMut(&mut Self::Item),
    {
        Mutate::new(self, f)
    }

    /// Transforms a bulk into a collection.
    ///
    /// [`collect()`](Bulk::collect) can take anything bulkable, and turn it into a relevant
    /// collection.
    /// 
    /// Similar to [`Iterator::collect`].
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let doubled: [i32; 3] = a.bulk()
    ///     .map(|x| x * 2)
    ///     .collect();
    ///
    /// assert_eq!(doubled, [2, 4, 6]);
    /// ```
    ///
    /// Note that we needed the `: [i32; 3]` on the left-hand side. This is because
    /// we could collect into, for example, a [`VecDeque<T>`](std::collections::VecDeque) instead:
    ///
    /// ```
    /// use std::collections::VecDeque;
    /// 
    /// use bulks::*;
    ///
    /// let a = [1, 2, 3];
    ///
    /// let doubled: VecDeque<i32> = a.bulk()
    ///     .map(|x| x * 2)
    ///     .collect();
    ///
    /// assert_eq!(doubled[0], 2);
    /// assert_eq!(doubled[1], 4);
    /// assert_eq!(doubled[2], 6);
    /// ```
    ///
    /// Using the 'turbofish' instead of annotating `doubled`:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let doubled = a.bulk()
    ///     .map(|x| x * 2)
    ///     .collect::<[i32; 3], _>();
    ///
    /// assert_eq!(doubled, [2, 4, 6]);
    /// ```
    ///
    /// Because `collect()` only cares about what you're collecting into, you can
    /// still use a partial type hint, `_`, with the turbofish:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let doubled: [_; _] = a.bulk()
    ///     .map(|x| x * 2)
    ///     .collect();
    ///
    /// assert_eq!(doubled, [2, 4, 6]);
    /// ```
    ///
    /// Using `collect()` to make a [`String`](std::string::String):
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let chars = ['g', 'd', 'k', 'k', 'n'];
    ///
    /// let hello: String = chars.bulk()
    ///     .copied()
    ///     .map(|x| x as u8)
    ///     .map(|x| (x + 1) as char)
    ///     .collect();
    ///
    /// assert_eq!(hello, "hello");
    /// ```
    ///
    /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
    /// see if any of them failed:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
    ///
    /// let result: Result<[_; _], &str> = results.into_bulk().collect();
    ///
    /// // gives us the first error
    /// assert_eq!(result, Err("nope"));
    ///
    /// let results = [Ok(1), Ok(3)];
    ///
    /// let result: Result<[_; _], &str> = results.into_bulk().collect();
    ///
    /// // gives us the list of answers
    /// assert_eq!(result, Ok([1, 3]));
    /// ```
    #[inline]
    #[must_use = "if you really need to exhaust the bulk, consider `.for_each(drop)` instead"]
    fn collect<C, A>(self) -> C
    where
        Self: Sized,
        C: ~const FromBulk<A>,
        A: CollectionAdapter<Elem = Self::Item> + ~const CollectionStrategy<Self, C> + ?Sized
    {
        FromBulk::from_bulk(self)
    }

    /// Fallibly transforms a bulk into a collection, short circuiting if
    /// a failure is encountered.
    ///
    /// `try_collect()` is a variation of [`collect()`][`Bulk::collect`] that allows fallible
    /// conversions during collection. Its main use case is simplifying conversions from
    /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
    /// types (e.g. [`Result`]).
    ///
    /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromBulk`];
    /// only the inner type produced on `Try::Output` must implement it. Concretely,
    /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
    /// [`FromBulk`], even though [`ControlFlow`] doesn't.
    /// 
    /// Unlike with [`Iterator::try_collect`], the bulk is fully consumed even if it short-circuits.
    /// A short-circuit will cause the rest of the elements of the bulk to be dropped.
    ///
    /// # Examples
    /// 
    /// Successfully collecting a bulk of `Option<i32>` into `Option<[i32; _]>`:
    /// ```
    /// use bulks::*;
    /// 
    /// let u = [Some(1), Some(2), Some(3)];
    /// 
    /// let v = u.into_bulk().try_collect::<[i32; _], _>();
    /// 
    /// assert_eq!(v, Some([1, 2, 3]));
    /// ```
    ///
    /// Failing to collect in the same way:
    /// ```
    /// use bulks::*;
    /// 
    /// let u = [Some(1), Some(2), None, Some(3)];
    /// 
    /// let v = u.into_bulk().try_collect::<[i32; _], _>();
    /// 
    /// assert_eq!(v, None);
    /// ```
    ///
    /// A similar example, but with `Result`:
    /// ```
    /// use bulks::*;
    /// 
    /// let u: [Result<i32, ()>; _] = [Ok(1), Ok(2), Ok(3)];
    /// 
    /// let v = u.into_bulk().try_collect::<[i32; _], _>();
    /// 
    /// assert_eq!(v, Ok([1, 2, 3]));
    ///
    /// let u = [Ok(1), Ok(2), Err(()), Ok(3)];
    /// 
    /// let v = u.into_bulk().try_collect::<[i32; _], _>();
    /// 
    /// assert_eq!(v, Err(()));
    /// ```
    ///
    /// Finally, even [`ControlFlow`] works, despite the fact that it
    /// doesn't implement [`FromBulk`].
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// use core::ops::ControlFlow::{Break, Continue};
    ///
    /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
    /// 
    /// let v = u.into_bulk().try_collect::<[_; _], _>();
    /// 
    /// assert_eq!(v, Break(3));
    ///
    /// let v = u.into_bulk().take([(); 2])
    ///     .chain(u.into_bulk().skip([(); 3]))
    ///     .try_collect::<[_; _], _>();
    /// 
    /// assert_eq!(v, Continue([1, 2, 4, 5]));
    /// ```
    #[inline]
    #[must_use = "if you really need to exhaust the bulk, consider `.for_each(drop)` instead"]
    fn try_collect<C, A>(self) -> <<Self::Item as Try>::Residual as Residual<C>>::TryType
    where
        Self: Sized,
        C: ~const FromBulk<A>,
        A: CollectionAdapter<Elem = <Self::Item as Try>::Output> + ~const TryCollectionAdapter<Self, C> + ?Sized,
        Self::Item: ~const Try<Residual: ~const Residual<C, TryType: ~const Try>> + ~const Destruct
    {
        FromBulk::try_from_bulk(self)
    }

    /// Transforms a statically sized bulk into an array.
    /// The bulk must implement [`StaticBulk`].
    /// 
    /// This is equivalent to [`collect()`](Bulk::collect), but the type does not need to be inferred.
    /// For types other than arrays, use [`collect()`](Bulk::collect).
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let doubled = a.bulk()
    ///     .map(|x| x * 2)
    ///     .collect_array();
    ///
    /// assert_eq!(doubled, [2, 4, 6]);
    /// ```
    /// 
    /// Alternatively, [`collect()`](Bulk::collect) can be used, but this requires us to specify the return type.
    ///
    /// ```
    /// use bulks::*;
    /// 
    /// let a = [1, 2, 3];
    ///
    /// let doubled: [i32; 3] = a.bulk()
    ///     .map(|x| x * 2)
    ///     .collect();
    ///
    /// assert_eq!(doubled, [2, 4, 6]);
    /// ```
    #[must_use = "if you really need to exhaust the bulk, consider `.for_each(drop)` instead"]
    fn collect_array(self) -> <Self as StaticBulk>::Array<<Self as IntoIterator>::Item>
    where
        Self: StaticBulk
    {
        util::collect_array_with!(|f| self.for_each(f); for Self)
    }

    /// Fallibly transforms a statically sized bulk into an array, short circuiting if
    /// a failure is encountered.
    /// The bulk must implement [`StaticBulk`].
    ///
    /// `try_collect_array()` is a variation of [`collect_array()`][`Bulk::collect_array`] that allows fallible
    /// conversions during collection. Its main use case is simplifying conversions from
    /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
    /// types (e.g. [`Result`]).
    ///
    /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromBulk`];
    /// only the inner type produced on `Try::Output` must implement it. Concretely,
    /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
    /// [`FromBulk`], even though [`ControlFlow`] doesn't.
    /// 
    /// This is equivalent to [`try_collect()`](Bulk::try_collect), but the type does not need to be inferred.
    /// For types other than arrays, use [`try_collect()`](Bulk::try_collect).
    /// 
    /// Unlike with [`Iterator::try_collect`], the bulk is fully consumed even if it short-circuits.
    /// A short-circuit will cause the rest of the elements of the bulk to be dropped.
    ///
    /// # Examples
    /// 
    /// Successfully collecting a bulk of `Option<i32>` into `Option<[i32; _]>`:
    /// ```
    /// use bulks::*;
    /// 
    /// let u = [Some(1), Some(2), Some(3)];
    /// let v = u.into_bulk().try_collect_array();
    /// assert_eq!(v, Some([1, 2, 3]));
    /// ```
    ///
    /// Failing to collect in the same way:
    /// ```
    /// use bulks::*;
    /// 
    /// let u = [Some(1), Some(2), None, Some(3)];
    /// let v = u.into_bulk().try_collect_array();
    /// assert_eq!(v, None);
    /// ```
    /// 
    /// Alternatively, [`try_collect()`](Bulk::try_collect) can be used, but this requires us to specify the return type.
    /// ```
    /// use bulks::*;
    /// 
    /// let u = [Some(1), Some(2), Some(3)];
    /// let v: Option<[i32; 3]> = u.into_bulk().try_collect();
    /// assert_eq!(v, Some([1, 2, 3]));
    /// ```
    ///
    /// A similar example, but with `Result`:
    /// ```
    /// use bulks::*;
    /// 
    /// let u: [Result<i32, ()>; _] = [Ok(1), Ok(2), Ok(3)];
    /// let v = u.into_bulk().try_collect_array();
    /// assert_eq!(v, Ok([1, 2, 3]));
    ///
    /// let u = [Ok(1), Ok(2), Err(()), Ok(3)];
    /// let v = u.into_bulk().try_collect_array();
    /// assert_eq!(v, Err(()));
    /// ```
    ///
    /// Finally, even [`ControlFlow`] works, despite the fact that it
    /// doesn't implement [`FromBulk`].
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use core::ops::ControlFlow::{Break, Continue};
    /// 
    /// use bulks::*;
    ///
    /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
    /// 
    /// let v = u.into_bulk().try_collect_array();
    /// assert_eq!(v, Break(3));
    ///
    /// let v = u.into_bulk().take([(); 2])
    ///     .chain(u.into_bulk().skip([(); 3]))
    ///     .try_collect_array();
    /// assert_eq!(v, Continue([1, 2, 4, 5]));
    /// ```
    #[allow(clippy::type_complexity)]
    #[must_use = "if you really need to exhaust the bulk, consider `.for_each(drop)` instead"]
    fn try_collect_array(self) -> <<Self::Item as Try>::Residual as Residual<Self::Array<<Self::Item as Try>::Output>>>::TryType
    where
        Self: StaticBulk<Item: ~const Destruct + ~const Try<Residual: Residual<(), TryType: ~const Try> + Residual<Self::Array<<Self::Item as Try>::Output>, TryType: ~const Try> + ~const Destruct, Output: ~const Destruct>> + ~const Bulk
    {
        Try::from_output(util::try_collect_array_with!(|pusher| self.try_for_each(pusher)?; for Self))
    }

    /// Reverses a bulks's direction.
    ///
    /// Usually, bulks span from left to right. After using `rev()`,
    /// a bulk will instead span from right to left.
    /// 
    /// Similar to [`Iterator::rev`].
    ///
    /// # Examples
    ///
    /// ```
    /// use bulks::*;
    ///
    /// let a = [1, 2, 3];
    ///
    /// let b: [_; _] = a.into_bulk().rev().collect();
    ///
    /// assert_eq!(b, [3, 2, 1]);
    /// ```
    #[inline]
    #[track_caller]
    #[doc(alias = "reverse")]
    fn rev(self) -> Rev<Self>
    where
        Self: Sized,
        Self: DoubleEndedBulk
    {
        Rev::new(self)
    }

    /// Creates a bulk which copies all of its elements.
    ///
    /// This is useful when you have a bulk of `&T`, but you need a
    /// bulk of `T`.
    /// 
    /// Similar to [`Iterator::copied`].
    ///
    /// # Examples
    ///
    /// ```
    /// use bulks::*;
    ///
    /// let a = [1, 2, 3];
    ///
    /// let v_copied: [_; _] = a.bulk().copied().collect();
    ///
    /// // copied is the same as .map(|&x| x)
    /// let v_map: [_; _] = a.bulk().map(|&x| x).collect();
    ///
    /// assert_eq!(v_copied, [1, 2, 3]);
    /// assert_eq!(v_map, [1, 2, 3]);
    /// ```
    #[inline]
    #[track_caller]
    fn copied<'a, T>(self) -> Copied<Self>
    where
        T: Copy + 'a,
        Self: Sized + ~const Bulk<Item = &'a T>,
    {
        Copied::new(self)
    }

    /// Creates a bulk which [`clone`](Clone::clone)s all of its elements.
    ///
    /// This is useful when you have a bulk of `&T`, but you need a
    /// bulk of `T`.
    ///
    /// There is no guarantee whatsoever about the `clone` method actually
    /// being called *or* optimized away. So code should not depend on
    /// either.
    /// 
    /// Similar to [`Iterator::cloned`].
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use bulks::*;
    ///
    /// let a = [1, 2, 3];
    ///
    /// let v_cloned: [_; _] = a.bulk().cloned().collect();
    ///
    /// // cloned is the same as .map(|&x| x), for integers
    /// let v_map: [_; _] = a.bulk().map(|&x| x).collect();
    ///
    /// assert_eq!(v_cloned, [1, 2, 3]);
    /// assert_eq!(v_map, [1, 2, 3]);
    /// ```
    #[inline]
    #[track_caller]
    fn cloned<'a, T>(self) -> Cloned<Self>
    where
        T: Clone + 'a,
        Self: Sized + ~const Bulk<Item = &'a T>,
    {
        Cloned::new(self)
    }

    /// Returns a bulk of `N` elements of the bulk at a time.
    ///
    /// The chunks do not overlap. If `N` does not divide the length of the
    /// bulk, then the last up to `N-1` elements will be omitted or the remainder
    /// can then be retrieved from [`.into_remainder()`][crate::ArrayChunks::into_remainder]
    /// or [`.collect_with_remainder()`][crate::ArrayChunks::collect_with_remainder]
    /// 
    /// Similar to [`Iterator::array_chunks`].
    ///
    /// # Panics
    ///
    /// Panics if `N` is zero.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    ///
    /// let bulk = b"lorem".bulk()
    ///     .copied()
    ///     .array_chunks();
    /// 
    /// let (c, r) = bulk.collect_with_remainder::<[_; _], _>();
    /// 
    /// let r: Vec<_> = r.collect();
    /// 
    /// assert_eq!(c, [[b'l', b'o'], [b'r', b'e']]);
    /// assert_eq!(r, [b'm']);
    /// ```
    ///
    /// ```
    /// use bulks::*;
    ///
    /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
    /// //          ^-----^  ^------^
    /// for [x, y, z] in data.bulk().array_chunks()
    /// {
    ///     assert_eq!(x + y + z, 4);
    /// }
    /// ```
    #[inline]
    #[track_caller]
    fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
    where
        Self: Sized,
    {
        ArrayChunks::new(self)
    }

    /// Splits a bulk in two at a specified index.
    /// 
    /// # Example
    /// 
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let a = b"leftright";
    /// 
    /// let (a1, a2) = a.bulk()
    ///     .copied()
    ///     .split_at([(); 4]);
    /// 
    /// let left: [_; _] = a1.collect();
    /// let right: [_; _] = a2.collect();
    /// 
    /// assert_eq!(&left, b"left");
    /// assert_eq!(&right, b"right");
    /// ```
    #[track_caller]
    fn split_at<L>(self, n: L) -> (Self::Left, Self::Right)
    where
        Self: ~const SplitBulk<L> + Sized,
        L: LengthValue
    {
        SplitBulk::split_at(self, n)
    }

    /// Splits a bulk in two at a specified reversed index.
    /// 
    /// # Example
    /// 
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// use bulks::*;
    /// 
    /// let a = b"leftright";
    /// 
    /// let (a1, a2) = a.bulk()
    ///     .copied()
    ///     .rsplit_at([(); 5]);
    /// 
    /// let left: [_; _] = a1.collect();
    /// let right: [_; _] = a2.collect();
    /// 
    /// assert_eq!(&left, b"left");
    /// assert_eq!(&right, b"right");
    /// ```
    #[track_caller]
    fn rsplit_at<L>(self, n: L) -> (Self::Left, Self::Right)
    where
        Self: ~const SplitBulk<length::value::SaturatingSub<<<Self as Bulk>::Length as Length>::Value, L>> + Sized,
        L: LengthValue
    {
        let l = self.length();
        SplitBulk::split_at(self, length::value::saturating_sub(l, n))
    }

    fn each_ref<'a>(&'a self) -> Self::EachRef<'a>
    where
        Self: ~const RandomAccessBulk + 'a
    {
        RandomAccessBulk::each_ref(self)
    }
    fn each_mut<'a>(&'a mut self) -> Self::EachMut<'a>
    where
        Self: ~const InplaceBulk + 'a
    {
        InplaceBulk::each_mut(self)
    }

    fn get<'a, L>(&'a self, i: L) -> Option<&'a Self::ItemPointee>
    where
        Self: ~const RandomAccessBulk + 'a,
        L: LengthValue
    {
        RandomAccessBulkSpec::_get(self, i)
    }

    fn get_mut<'a, L>(&'a mut self, i: L) -> Option<&'a mut Self::ItemPointee>
    where
        Self: ~const InplaceBulk + 'a,
        L: LengthValue
    {
        InplaceBulkSpec::_get_mut(self, i)
    }

    fn try_get<'a, L>(&'a self, i: L) -> Result<&'a Self::ItemPointee, OutOfRange>
    where
        Self: ~const RandomAccessBulk + 'a,
        L: LengthValue
    {
        match self.get(i)
        {
            Some(x) => Ok(x),
            None => {
                let len = self.len();
                let i = length::value::len(i);
                assert!(i >= len, "Malformed bulk length");
                Err(OutOfRange { i, len })
            }
        }
    }

    fn try_get_mut<'a, L>(&'a mut self, i: L) -> Result<&'a mut Self::ItemPointee, OutOfRange>
    where
        Self: ~const InplaceBulk + 'a,
        L: LengthValue
    {
        let len = self.len();
        match self.get_mut(i)
        {
            Some(x) => Ok(x),
            None => {
                let i = length::value::len(i);
                assert!(i >= len, "Malformed bulk length");
                Err(OutOfRange { i, len })
            }
        }
    }

    fn get_many<'a, NN, const N: usize>(&'a self, i: NN) -> [Option<&'a <Self as RandomAccessBulk>::ItemPointee>; N]
    where
        Self: ~const RandomAccessBulk + 'a,
        NN: ~const IntoBulk<Item = usize, IntoBulk: ~const Bulk + StaticBulk<Array<()> = [(); N]>>
    {
        RandomAccessBulkSpec::_get_many(self, i)
    }

    fn get_many_mut<'a, NN, const N: usize>(&'a mut self, i: NN) -> [Option<&'a mut <Self as RandomAccessBulk>::ItemPointee>; N]
    where
        Self: ~const InplaceBulk + 'a,
        NN: ~const IntoBulk<Item = usize, IntoBulk: ~const Bulk + StaticBulk<Array<()> = [(); N]>>
    {
        InplaceBulkSpec::_get_many_mut(self, i)
    }

    fn swap_inplace<L, R>(&mut self, lhs: L, rhs: R)
    where
        Self: ~const InplaceBulk,
        L: LengthValue,
        R: LengthValue
    {
        match self.try_swap_inplace(lhs, rhs)
        {
            Ok(()) => (),
            Err(err) => err.halt()
        }
    }

    fn try_swap_inplace<L, R>(&mut self, lhs: L, rhs: R) -> Result<(), OutOfRange>
    where
        Self: ~const InplaceBulk,
        L: LengthValue,
        R: LengthValue
    {
        let n = self.length();
        let bulk = self.each_mut();

        let j = length::value::min(lhs, rhs);
        let i = length::value::max(lhs, rhs);

        struct Closure<T>
        {
            first: Option<T>,
            last: Option<T>
        }
        impl<T> const FnOnce<(T,)> for Closure<T>
        where
            T: ~const Destruct
        {
            type Output = ();
            
            extern "rust-call" fn call_once(mut self, args: (T,)) -> Self::Output
            {
                self.call_mut(args)
            }
        }
        impl<T> const FnMut<(T,)> for Closure<T>
        where
            T: ~const Destruct
        {
            extern "rust-call" fn call_mut(&mut self, (x,): (T,)) -> Self::Output
            {
                if self.first.is_none()
                {
                    self.first = Some(x)
                }
                else
                {
                    self.last = Some(x)
                }
            }
        }

        let mut closure = Closure {
            first: None,
            last: None
        };

        bulk.take(length::value::add(i, [(); 1]))
            .skip(j)
            .step_by(length::value::sub(i, j))
            .for_each(&mut closure);

        match if length::value::ge(i, n)
        {
            Err(length::value::len(i))
        }
        else
        {
            match (closure.first, closure.last)
            {
                (Some(first), Some(last)) => { core::mem::swap(first, last); Ok(()) },
                (Some(_), None) if length::value::eq(i, j) => Ok(()),
                (Some(_), None) => Err(length::value::len(j)),
                (None, None) | (None, Some(_)) => Err(length::value::len(i))
            }
        }
        {
            Ok(()) => Ok(()),
            Err(i) => Err(OutOfRange { i, len: length::value::len(n) })
        }
    }

    fn sum_from<T>(self, from: T) -> T
    where
        T: ~const Add<Self::Item, Output = T> + ~const Destruct,
        Self: Sized
    {
        self.fold(from, Add::add)
    }

    fn product_from<T>(self, from: T) -> T
    where
        T: ~const Mul<Self::Item, Output = T> + ~const Destruct,
        Self: Sized
    {
        self.fold(from, Mul::mul)
    }
}

#[derive(Clone, Copy, Debug, thiserror::Error)]
pub struct OutOfRange
{
    pub i: usize,
    pub len: usize
}

impl OutOfRange
{
    const fn halt(self) -> !
    {
        fn rt(oor: OutOfRange) -> !
        {
            panic!("{oor}")
        }

        const fn ct(_: OutOfRange) -> !
        {
            panic!("Index out of bounds.")
        }

        core::intrinsics::const_eval_select((self,), ct, rt)
    }
}

impl Display for OutOfRange
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result
    {
        let Self { i, len } = self;
        write!(f, "Index out of bounds. Index {i} can't be larger than {len}.")
    }
}

#[cfg(test)]
mod test
{
    use crate::*;
    
    #[test]
    fn test_reduce()
    {
        let a = [1, 5, -3, 7, 9, 3, -1, 3];

        let sum = a.into_bulk().reduce(|a, b| a + b).unwrap_or(0);
        let product = a.into_bulk().reduce(|a, b| a*b).unwrap_or(1);
        let min = a.into_bulk().reduce(|a, b| a.min(b)).unwrap();
        let max = a.into_bulk().reduce(|a, b| a.max(b)).unwrap();
        let mean = sum as f32/a.len() as f32;
        let variance = a.into_bulk().map(|a| a as f32 - mean).map(|a| a*a).reduce(|a, b| a + b).unwrap_or(0.0).sqrt();

        println!("sum = {sum}");
        println!("product = {product}");
        println!("min = {min}");
        println!("max = {max}");

        println!("mean = {mean}");
        println!("variance = {variance}");
    }
}

mod private
{
    use array_trait::length::Length;

    use crate::{Bulk, StaticBulk};

    pub const trait BulkBase: IntoIterator
    {
        type Length: Length<Elem = ()> + ?Sized;
    }
    impl<T> BulkBase for T
    where
        T: Bulk + ?Sized
    {
        default type Length = [()];
    }
    impl<T> BulkBase for T
    where
        T: StaticBulk
    {
        type Length = <Self as StaticBulk>::Array<()>;
    }
}