better_collect 0.5.0-deprecated

Provides a composable, declarative way to consume an iterator
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
use std::ops::ControlFlow;

#[cfg(feature = "itertools")]
use itertools::Either;

#[cfg(feature = "unstable")]
use super::{AltBreakHint, Nest, NestExact, TeeWith};
use super::{
    Chain, Cloning, Collector, Copying, Filter, FlatMap, Flatten, Funnel, Fuse, Inspect,
    IntoCollector, IntoCollectorBase, Map, MapOutput, Partition, Skip, Take, TakeWhile, Tee,
    TeeClone, TeeFunnel, TeeMut, Unbatching, Unzip, assert_collector, assert_collector_base,
};
#[cfg(feature = "itertools")]
use super::{PartitionMap, Update};

/// The base trait of a collector.
///
/// This trait defines the output type and methods that do not depend on the item type.
/// It is crucial to avoid "type annotation needed" because implementors may implement
/// different output types and implement methods differently based on the item type,
/// which is not desired. A collector should only have one and only one output type.
/// Allowing the output type (and such methods) to vary with the item type would be
/// confusing regardless.
///
/// Implementors should never implement this trait alone, but also implement
/// [`Collector`](super::Collector).
///
/// See the [module-level documentation](super) for more information.
///
/// # Dyn Compatibility
///
/// This trait is *dyn-compatible*, meaning it can be used as a trait object.
/// You do not need to specify the [`Output`](CollectorBase::Output) type.
/// The compiler will even emit a warning if you add the
/// [`Output`](CollectorBase::Output) type.
///
/// However, as a trait object, it is pretty much useless, as the only method
/// available is [`break_hint()`](CollectorBase::break_hint).
pub trait CollectorBase {
    /// The result this collector yields, via the [`finish()`](CollectorBase::finish) method.
    ///
    /// This assosciated type does not appear in trait objects.
    type Output
    where
        Self: Sized;

    /// Consumes the collector and returns the accumulated result.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let v = vec![1, 2, 3]
    ///     .into_collector()
    ///     .take(999)
    ///     .fuse()
    ///     .filter(|&x: &i32| x > 0);
    ///
    /// assert_eq!(v.finish(), [1, 2, 3]);
    /// ```
    fn finish(self) -> Self::Output
    where
        Self: Sized;

    /// Returns a hint whether the collector has stopped accumulating.
    ///
    /// Returns [`Break(())`] if it is guaranteed that the collector
    /// has stopped accumulating, or returns [`Continue(())`] otherwise.
    ///
    /// As specified in the [module-level documentation](crate::collector),
    /// after the stop is signaled somewhere else,
    /// including through [`collect()`] or similar methods or this method itself,
    /// the behavior of this method is unspecified.
    /// This may include returning [`Break(())`] even if the collector has conceptually stopped.
    ///
    /// This method should be called once and only once before collecting
    /// items in a loop to avoid consuming one item prematurely.
    /// It is not intended for repeatedly checking whether the
    /// collector has stopped. Use [`fuse()`](CollectorBase::fuse)
    /// if you find yourself needing such behavior.
    ///
    /// If the collector is uncertain, like "maybe I won’t accumulate… uh, fine, I will,"
    /// it is recommended to just return [`Continue(())`].
    /// For example, [`filter()`] might skip some items it collects,
    /// but still returns [`Continue(())`] as long as the underlying collector can still accumulate.
    /// The filter just denies "undesirable" items and does not signal termination
    /// (this is the job of [`take_while()`] instead).
    ///
    /// The default implementation always returns [`Continue(())`].
    ///
    /// # Examples
    ///
    /// Correct usage:
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .take_while(|&x| x != 3);
    ///
    /// let mut has_stopped = collector.break_hint().is_break();
    /// let mut num = 0;
    /// while !has_stopped {
    ///     has_stopped = collector.collect(num).is_break();
    ///     num += 1;
    /// }
    ///
    /// assert_eq!(collector.finish(), [0, 1, 2]);
    /// ```
    ///
    /// Incorrect usage:
    ///
    /// ```no_run
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .take_while(|&x| x != 3);
    ///
    /// let mut num = 0;
    /// // If `collect()` has returned `Break(())` in the previous iteration,
    /// // The usage of `break_hint()` here is NOT valid. ⚠️
    /// // By the current implementation, this may loop indefinitely
    /// // until your RAM explodes! (the `Vec` keeps expanding)
    /// while collector.break_hint().is_continue() {
    ///     let _ = collector.collect(num);
    ///     num += 1;
    /// }
    ///
    /// // May not be correct anymore. ⚠️
    /// assert_eq!(collector.finish(), [0, 1, 2]);
    /// ```
    ///
    /// [`Break(())`]: std::ops::ControlFlow::Break
    /// [`Continue(())`]: std::ops::ControlFlow::Continue
    /// [`Collector`]: crate::collector::Collector
    /// [`collect()`]: crate::collector::Collector::collect
    /// [`filter()`]: crate::collector::CollectorBase::filter
    /// [`take_while()`]: crate::collector::CollectorBase::take_while
    fn break_hint(&self) -> ControlFlow<()> {
        ControlFlow::Continue(())
    }

    /// Creates a collector that can "safely" collect items even after
    /// the underlying collector has stopped accumulating,
    /// without triggering undesired behaviors.
    ///
    /// Normally, a collector having stopped may behave unpredictably,
    /// including accumulating again.
    /// `fuse()` ensures that once a collector has stopped, subsequent items
    /// are guaranteed to **not** be accumulated. This means that at that point,
    /// [`collect()`](Collector::collect), [`collect_many()`](Collector::collect_many)
    /// and [`break_hint()`](CollectorBase::break_hint) are
    /// guaranteed to return [`Break(())`].
    ///
    /// # Examples
    ///
    /// Without `fuse()`:
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// // `take_while()` is one of a few collectors that do NOT fuse internally.
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .take_while(|&x| x != 3);
    ///
    /// assert!(collector.collect(1).is_continue());
    /// assert!(collector.collect(2).is_continue());
    /// assert!(collector.collect(3).is_break());
    ///
    /// // Use after `Break` ⚠️
    /// let _ = collector.collect(4);
    ///
    /// // What do you think what `collector.finish()` would yield? You can try it yourself.
    /// // (Spoiler: by the current implementation, it may NOT be `[1, 2]`!)
    /// # // Not shown to the doc. We only confirm our claim here.
    /// # assert_ne!(collector.finish(), [1, 2]);
    /// ```
    ///
    /// With `fuse()`:
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .take_while(|&x| x != 3)
    ///     .fuse();
    ///
    /// assert!(collector.collect(1).is_continue());
    /// assert!(collector.collect(2).is_continue());
    /// assert!(collector.collect(3).is_break());
    ///
    /// // From now on, there's only `Break`. No further items are accumulated.
    /// assert!(collector.collect(4).is_break());
    /// assert!(collector.collect(5).is_break());
    /// assert!(collector.collect_many([6, 7, 8, 9]).is_break());
    ///
    /// // The output is consistent again.
    /// assert_eq!(collector.finish(), [1, 2]);
    /// ```
    ///
    /// [`Continue(())`]: ControlFlow::Continue
    /// [`Break(())`]: ControlFlow::Break
    #[inline]
    fn fuse(self) -> Fuse<Self>
    where
        Self: Sized,
    {
        assert_collector_base(Fuse::new(self))
    }

    /// Creates a collector that lets both collectors collect the same item.
    ///
    /// For each item collected, the first collector collects the item
    /// copied with the [`Copy`] trait before the second collector collects it.
    ///
    /// `tee()` only stops when **both** collectors have stopped.
    ///
    /// If the item type of this adapter is `T`, both collectors must implement
    /// [`Collector<T>`](super::Collector), and `T` must implement [`Copy`].
    ///
    /// The [`Output`](CollectorBase::Output) is a tuple containing the outputs of
    /// both underlying collectors, in order.
    ///
    /// See the [module-level documentation](crate::collector) for
    /// when this adapter is used and other variants of `tee` adapters.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::{prelude::*, cmp::Max};
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .tee(Max::new());
    ///
    /// assert!(collector.collect(4).is_continue());
    /// assert!(collector.collect(2).is_continue());
    /// assert!(collector.collect(6).is_continue());
    /// assert!(collector.collect(3).is_continue());
    ///
    /// assert_eq!(collector.finish(), (vec![4, 2, 6, 3], Some(6)));
    /// ```
    #[inline]
    fn tee<C>(self, other: C) -> Tee<Self, C::IntoCollector>
    where
        Self: Sized,
        C: IntoCollectorBase,
    {
        assert_collector_base(Tee::new(self, other.into_collector()))
    }

    /// Creates a collector that lets both collectors collect the same item.
    ///
    /// For each item collected, the first collector collects the item
    /// cloned with the [`Clone`] trait before the second collector collects it.
    /// If one of them has stopped, the implementation will **not** clone
    /// the item, and will instead feed it into the other for optimization.
    ///
    /// `tee_clone()` only stops when **both** collectors have stopped.
    ///
    /// If the item type of this adapter is `T`, both collectors must implement
    /// [`Collector<T>`](super::Collector), and `T` must implement [`Clone`].
    ///
    /// The [`Output`](CollectorBase::Output) is a tuple containing the outputs of
    /// both underlying collectors, in order.
    ///
    /// See the [module-level documentation](crate::collector) for
    /// when this adapter is used and other variants of `tee` adapters.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    /// use std::rc::Rc;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .take(2)
    ///     .tee_clone(vec![]);
    ///
    /// assert!(collector.collect(Rc::new(1)).is_continue());
    /// assert!(collector.collect(Rc::new(2)).is_continue());
    /// // From here, the `Rc` will NOT be cloned.
    /// assert!(collector.collect(Rc::new(3)).is_continue());
    ///
    /// let (nums1, nums2) = collector.finish();
    ///
    /// assert!(nums1.iter().map(|num| **num).eq([1, 2]));
    /// assert!(nums2.iter().map(|num| **num).eq([1, 2, 3]));
    /// assert!(nums2.iter().map(Rc::strong_count).eq([2, 2, 1]));
    /// ```
    #[inline]
    fn tee_clone<C>(self, other: C) -> TeeClone<Self, C::IntoCollector>
    where
        Self: Sized,
        C: IntoCollectorBase,
    {
        assert_collector_base(TeeClone::new(self, other.into_collector()))
    }

    /// Creates a collector that lets both collectors collect the same item.
    ///
    /// For each item collected, the first collector collects
    /// the mutable reference of the item before the second collector collects it.
    ///
    /// `tee_funnel()` only stops when **both** collectors have stopped.
    ///
    /// If the item type of this adapter is `T`,
    /// the first collector must implement [`for<'a> Collector<&'a mut T>`](super::Collector)
    /// (a collector that can collect a mutable reference with any lifetime),
    /// and the second collector must implement [`Collector<T>`](super::Collector).
    ///
    /// The [`Output`](CollectorBase::Output) is a tuple containing the outputs of
    /// both underlying collectors, in order.
    ///
    /// See the [module-level documentation](crate::collector) for
    /// when this adapter is used and other variants of `tee` adapters.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::{prelude::*, clb_mut};
    ///
    /// let mut collector = String::new()
    ///     .into_concat()
    ///     .map(clb_mut!(|s: &mut String| -> &str { &s[..] }))
    ///     .tee_funnel(vec![]);
    ///
    /// let strings = ["noble", "and", "singer"].map(String::from);
    /// assert!(collector.collect_many(strings).is_continue());
    ///
    /// let (concat, string_vec) = collector.finish();
    ///
    /// assert_eq!(concat, "nobleandsinger");
    /// assert_eq!(string_vec, ["noble", "and", "singer"]);
    /// ```
    #[inline]
    fn tee_funnel<C>(self, other: C) -> TeeFunnel<Self, C::IntoCollector>
    where
        Self: Sized,
        C: IntoCollectorBase,
    {
        assert_collector_base(TeeFunnel::new(self, other.into_collector()))
    }

    /// Creates a collector that lets both collectors collect the same item.
    ///
    /// For each item collected, the first collector collects
    /// the mutable reference of the item before the second collector also
    /// collects the mutable reference of it.
    ///
    /// `tee_mut()` only stops when **both** collectors have stopped.
    ///
    /// If the item type of this adapter is `&'i mut T`,
    /// the first collector must implement [`for<'a> Collector<&'a mut T>`](super::Collector)
    /// (a collector that can collect a mutable reference with any lifetime),
    /// and the second collector must implement [`Collector<&'i mut T>`](super::Collector).
    ///
    /// The [`Output`](CollectorBase::Output) is a tuple containing the outputs of
    /// both underlying collectors, in order.
    ///
    /// See the [module-level documentation](crate::collector) for
    /// when this adapter is used and other variants of `tee` adapters.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::{cmp::Max, prelude::*, clb_mut};
    ///
    /// let mut collector = String::new()
    ///     .into_concat()
    ///     .map(clb_mut!(|s: &mut String| -> &str { &s[..] }))
    ///     .tee_mut(Max::new().map(
    ///         clb_mut!(|s: &mut String| -> usize { s.len() })
    ///     ))
    ///     .tee_funnel(vec![]);
    ///
    /// let strings = ["noble", "and", "singer"].map(String::from);
    /// assert!(collector.collect_many(strings).is_continue());
    ///
    /// let ((concat, max_len), string_vec) = collector.finish();
    ///
    /// assert_eq!(concat, "nobleandsinger");
    /// assert_eq!(max_len, Some(6));
    /// assert_eq!(string_vec, ["noble", "and", "singer"]);
    /// ```
    #[inline]
    fn tee_mut<C>(self, other: C) -> TeeMut<Self, C::IntoCollector>
    where
        Self: Sized,
        C: IntoCollectorBase,
    {
        assert_collector_base(TeeMut::new(self, other.into_collector()))
    }

    /// Creates a collector that [`clone`](Clone::clone)s every collected item.
    ///
    /// This is useful when you have a [`Collector<T>`](super::Collector), but you
    /// need a [`for<'a> Collector<&'a mut T>`](super::Collector)
    /// or [`for<'a> Collector<&'a T>`](super::Collector).
    ///
    /// Many collectors may have implementations for references, such as collections.
    /// In this case, you do not need this adapter.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let collector = vec![]
    ///     .into_concat()
    ///     .cloning() // Try putting `cloning` before every other collector
    ///     .filter(|num: &&Vec<_>| num.len() > 1);
    ///
    /// let concat = [vec![0, 1, 2], vec![3], vec![4, 5]]
    ///     .iter()
    ///     .feed_into(collector);
    ///
    /// assert_eq!(concat, [0, 1, 2, 4, 5]);
    /// ```
    #[inline]
    fn cloning(self) -> Cloning<Self>
    where
        Self: Sized,
    {
        assert_collector_base(Cloning::new(self))
    }

    /// Creates a collector that copies every collected item.
    ///
    /// This is useful when you have a [`Collector<T>`](super::Collector), but you
    /// need a [`for<'a> Collector<&'a mut T>`](super::Collector)
    /// or [`for<'a> Collector<&'a T>`](super::Collector).
    ///
    /// Many collectors may have implementations for references, such as collections.
    /// In this case, you do not need this adapter.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let collector = vec![]
    ///     .into_collector()
    ///     .copying();
    ///
    /// let concat = [0, 1, 2, 3, 4]
    ///     .iter()
    ///     .feed_into(collector);
    ///
    /// assert_eq!(concat, [0, 1, 2, 3, 4]);
    /// ```
    #[inline]
    fn copying(self) -> Copying<Self>
    where
        Self: Sized,
    {
        assert_collector_base(Copying::new(self))
    }

    /// Creates a collector that stops accumulating after collecting the first `n` items,
    /// or fewer if the underlying collector stops sooner.
    ///
    /// `take(n)` collects items until either `n` items have been collected
    /// or the underlying collector stops, whichever happens first.
    /// For collections, the [`Output`](CollectorBase::Output) will contain
    /// at most `n` more items than it had before construction.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .take(3);
    ///
    /// assert!(collector.collect(1).is_continue());
    /// assert!(collector.collect(2).is_continue());
    ///
    /// // Immediately stops after the third item.
    /// assert!(collector.collect(3).is_break());
    /// # // Internal assertion.
    /// # assert!(collector.collect(4).is_break());
    ///
    /// assert_eq!(collector.finish(), [1, 2, 3]);
    /// ```
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = String::new()
    ///     .into_collector()
    ///     .take(0);
    ///
    /// // This collector stops accumulating from construction.
    /// assert!(collector.break_hint().is_break());
    /// assert_eq!(collector.finish(), "");
    /// ```
    #[inline]
    fn take(self, n: usize) -> Take<Self>
    where
        Self: Sized,
    {
        assert_collector_base(Take::new(self, n))
    }

    /// Creates a collector that skips the first `n` collected items
    /// before it begins accumulating them.
    ///
    /// `skip(n)` ignores collected items until `n` items have been collected.
    /// After that, subsequent items are accumulated normally.
    ///
    /// Note that in the current implementation,
    /// if the underlying collector has stopped accumulating during skipping,
    /// its [`collect()`], [`break_hint()`] and similar methods will return [`Break(())`],
    /// regardless of whether the adaptor has skipped enough items or not.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .skip(3);
    ///
    /// assert!(collector.collect(1).is_continue());
    /// assert!(collector.collect(2).is_continue());
    /// assert!(collector.collect(3).is_continue());
    ///
    /// // It has skipped enough items.
    /// assert!(collector.collect(4).is_continue());
    /// assert!(collector.collect(5).is_continue());
    ///
    /// assert_eq!(collector.finish(), [4, 5]);
    /// ```
    ///
    /// [`Break(())`]: ControlFlow::Break
    /// [`collect()`]: super::Collector::collect
    /// [`break_hint()`]: CollectorBase::break_hint
    fn skip(self, n: usize) -> Skip<Self>
    where
        Self: Sized,
    {
        assert_collector_base(Skip::new(self, n))
    }

    /// Creates a collector that destructures each 2-tuple `(A, B)` item and distributes its fields:
    /// `A` goes to the first collector, and `B` goes to the second collector.
    ///
    /// `unzip()` is useful when you want to split an [`Iterator`]
    /// producing tuples or structs into multiple collections.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// struct User {
    ///     id: u32,
    ///     name: String,
    ///     email: String,
    /// }
    ///
    /// let users = [
    ///     User {
    ///         id: 1,
    ///         name: "Alice".to_owned(),
    ///         email: "alice@mail.com".to_owned(),
    ///     },
    ///     User {
    ///         id: 2,
    ///         name: "Bob".to_owned(),
    ///         email: "bob@mail.com".to_owned(),
    ///     },
    /// ];
    ///
    /// let ((ids, names), emails) = users
    ///     .into_iter()
    ///     .feed_into(
    ///         vec![]
    ///             .into_collector()
    ///             .unzip(vec![])
    ///             .unzip(vec![])
    ///             .map(|user: User| ((user.id, user.name), user.email)),
    ///     );
    ///
    /// assert_eq!(ids, [1, 2]);
    /// assert_eq!(names, vec!["Alice", "Bob"]);
    /// assert_eq!(emails, vec!["alice@mail.com", "bob@mail.com"]);
    /// ```
    #[inline]
    fn unzip<C>(self, other: C) -> Unzip<Self, C::IntoCollector>
    where
        Self: Sized,
        C: IntoCollectorBase,
    {
        assert_collector_base(Unzip::new(self, other.into_collector()))
    }

    /// Creates a collector that feeds every item in the first collector until it stops accumulating,
    /// then continues feeding items into the second one.
    ///
    /// The first collector should be finite (typically achieved with
    /// [`take`](CollectorBase::take) or [`take_while`](super::CollectorBase::take_while)),
    /// otherwise it will hoard all incoming items and never pass any to the second.
    ///
    /// The [`Output`](CollectorBase::Output) is a tuple containing the outputs of
    /// both underlying collectors, in order.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .take(2)
    ///     .chain(vec![]);
    ///
    /// assert!(collector.collect(1).is_continue());
    ///
    /// // Now the first collector stops accumulating, but the second one is still active.
    /// assert!(collector.collect(2).is_continue());
    ///
    /// // Now the second one takes the spotlight.
    /// assert!(collector.collect(3).is_continue());
    /// assert!(collector.collect(4).is_continue());
    /// assert!(collector.collect(5).is_continue());
    ///
    /// assert_eq!(collector.finish(), (vec![1, 2], vec![3, 4, 5]));
    /// ```
    #[inline]
    fn chain<C>(self, other: C) -> Chain<Self, C::IntoCollector>
    where
        Self: Sized,
        C: IntoCollectorBase,
    {
        assert_collector_base(Chain::new(self, other.into_collector()))
    }

    /// Creates a collector that transforms the final accumulated result.
    ///
    /// This is used when your output gets "ugly" after a chain of adaptors,
    /// or when you do not want to break your API by (accidentally) rearranging adaptors,
    /// or when you just want a different output type for your collector.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::{prelude::*, iter::Count};
    ///
    /// let mut average = i32::adding()
    ///     .tee(Count::new())
    ///     .map_output(|(sum, count)| {
    ///         (count != 0).then(|| sum as f64 / count as f64)
    ///     });
    ///
    /// assert!(average.collect(1).is_continue());
    /// assert!(average.collect(6).is_continue());
    /// assert!(average.collect(4).is_continue());
    /// assert!(average.collect(2).is_continue());
    ///
    /// assert_eq!(average.finish(), Some(3.25));
    /// ```
    fn map_output<F, T>(self, f: F) -> MapOutput<Self, F>
    where
        Self: Sized,
        F: FnOnce(Self::Output) -> T,
    {
        assert_collector_base(MapOutput::new(self, f))
    }

    /// Creates a collector that feeds the underlying collector with
    /// the mutable reference to the item, "pretending" the collector
    /// accepts owned items.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .funnel();
    ///
    /// assert!(collector.collect_many([1, 2, 3]).is_continue());
    /// assert_eq!(collector.finish(), [1, 2, 3]);
    /// ```
    #[inline]
    fn funnel(self) -> Funnel<Self>
    where
        Self: Sized,
    {
        assert_collector_base(Funnel::new(self))
    }

    /// Creates a collector that calls a closure on each item before collecting.
    ///
    /// This is used when you need a collector that collects `U`,
    /// but you have a collector that collects `T`. In that case,
    /// you can use `map()` to transform `U` into `T` before passing it along.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![].into_collector().map(|num| num * num);
    ///
    /// assert!(collector.collect_many(1..=5).is_continue());
    ///
    /// assert_eq!(collector.finish(), [1, 4, 9, 16, 25]);
    /// ```
    ///
    /// If you have multiple collectors with different item types, this adaptor bridges them.
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let (_strings, lens) = ["a", "bcd", "ef"]
    ///     .into_iter()
    ///     .feed_into(
    ///         "".to_owned()
    ///             .into_concat()
    ///             // Limitation: type annotation may be needed.
    ///             .tee(vec![].into_collector().map(|s: &str| s.len()))
    ///     );
    ///
    /// assert_eq!(lens, [1, 3, 2]);
    /// ```
    #[inline]
    fn map<F, T, U>(self, f: F) -> Map<Self, F>
    where
        Self: Collector<T> + Sized,
        F: FnMut(U) -> T,
    {
        assert_collector::<_, U>(Map::new(self, f))
    }

    /// Creates a collector that uses a closure to determine whether an item should be accumulated.
    ///
    /// The underlying collector only collects items for which the given predicate returns `true`.
    ///
    /// Note that even if an item is not collected, this adaptor will still return
    /// [`Continue`] as long as the underlying collector does. If you want the collector to stop
    /// after the first `false`, consider using [`take_while()`](CollectorBase::take_while) instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .filter(|&x| x % 2 == 0);
    ///
    /// assert!(collector.collect(2).is_continue());
    /// assert!(collector.collect(4).is_continue());
    /// assert!(collector.collect(0).is_continue());
    ///
    /// // Still `Continue` even if an item doesn’t satisfy the predicate.
    /// assert!(collector.collect(1).is_continue());
    ///
    /// assert_eq!(collector.finish(), [2, 4, 0]);
    /// ```
    ///
    /// [`Continue`]: ControlFlow::Continue
    #[inline]
    fn filter<F, T>(self, pred: F) -> Filter<Self, F>
    where
        Self: Collector<T> + Sized,
        F: FnMut(&T) -> bool,
    {
        assert_collector::<_, T>(Filter::new(self, pred))
    }

    /// Creates a collector that accumulates items as long as a predicate returns `true`.
    ///
    /// `take_while()` collects items until it encounters one for which the predicate returns `false`.
    /// Conceptually, that item and all subsequent ones will **not** be accumulated.
    /// However, you should ensure that you do not feed more items after it has signaled
    /// a stop.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = "".to_owned()
    ///     .into_concat()
    ///     .take_while(|&s| s != "stop");
    ///
    /// assert!(collector.collect("abc").is_continue());
    /// assert!(collector.collect("def").is_continue());
    ///
    /// // Immediately stops after "stop".
    /// assert!(collector.collect("stop").is_break());
    ///
    /// assert_eq!(collector.finish(), "abcdef");
    /// ```
    fn take_while<F, T>(self, pred: F) -> TakeWhile<Self, F>
    where
        Self: Collector<T> + Sized,
        F: FnMut(&T) -> bool,
    {
        assert_collector::<_, T>(TakeWhile::new(self, pred))
    }

    // fn step_by()

    /// Creates a collector that distributes items between two collectors based on a predicate.
    ///
    /// Items for which the predicate returns `true` are sent to the first collector,
    /// and those for which it returns `false` go to the second collector.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let collector = vec![]
    ///     .into_collector()
    ///     .partition(|&mut x| x % 2 == 0, vec![]);
    /// let (evens, odds) = collector.collect_then_finish(-5..5);
    ///
    /// assert_eq!(evens, [-4, -2, 0, 2, 4]);
    /// assert_eq!(odds, [-5, -3, -1, 1, 3]);
    /// ```
    #[inline]
    fn partition<C, F, T>(self, pred: F, other_if_false: C) -> Partition<Self, C::IntoCollector, F>
    where
        Self: Collector<T> + Sized,
        C: IntoCollector<T>,
        F: FnMut(&mut T) -> bool,
    {
        assert_collector::<_, T>(Partition::new(self, other_if_false.into_collector(), pred))
    }

    /// Creates a collector that lets both collectors collect the same item.
    ///
    /// For each item collected, the first collector collects the item
    /// mapped by a given closure before the second collector collects it.
    /// If the second collector stops accumulating, the item will **not**
    /// be mapped, and instead is fed directly into the first collector.
    ///
    /// `tee_with()` only stops when **both** collectors have stopped.
    ///
    /// If the item type of this adapter is `T`, the first collector must implement
    /// [`Collector<T>`](super::Collector) and [`Collector<U>`](super::Collector),
    /// and the second collector must implement [`Collector<T>`](super::Collector).
    /// Since many collectors do not collect two or more types of items,
    /// `U` is effectively also `T` in this case.
    ///
    /// The [`Output`](CollectorBase::Output) is a tuple containing the outputs of
    /// both underlying collectors, in order.
    ///
    /// See the [module-level documentation](crate::collector) for
    /// when this adapter is used and other variants of `tee` adapters.
    #[inline]
    #[cfg(feature = "unstable")]
    fn tee_with<C, F, T, U>(self, f: F, other: C) -> TeeWith<Self, C::IntoCollector, F>
    where
        Self: Collector<T> + Collector<U> + Sized,
        C: IntoCollector<T>,
        F: FnMut(&mut T) -> U,
    {
        assert_collector::<_, T>(TeeWith::new(self, other.into_collector(), f))
    }

    /// Creates a collector with a custom collection logic.
    ///
    /// This adaptor is useful for behaviors that cannot be expressed
    /// through existing adaptors without cloning or intermediate allocations.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = Vec::<i32>::new()
    ///     .into_collector()
    ///     .unbatching(|v, arr: &[_]| v.collect_many(arr));
    ///
    /// assert!(collector.collect(&[1, 2, 3]).is_continue());
    /// assert!(collector.collect(&[4, 5]).is_continue());
    /// assert!(collector.collect(&[6, 7, 8, 9]).is_continue());
    ///
    /// assert_eq!(collector.finish(), [1, 2, 3, 4, 5, 6, 7, 8, 9]);
    /// ```
    fn unbatching<F, T>(self, f: F) -> Unbatching<Self, F>
    where
        Self: Sized,
        F: FnMut(&mut Self, T) -> ControlFlow<()>,
    {
        assert_collector_base(Unbatching::new(self, f))
    }

    // ///
    // #[inline]
    // fn map_ref_ref<F, T, U>(self, f: F) -> Map<Self, F>
    // where
    //     Self: for<'a> Collector<&'a T> + Sized,
    //     F: FnMut(&U) -> &T,
    //     T: ?Sized,
    //     U: ?Sized,
    // {
    //     assert_collector::<_, &U>(Map::new(self, f))
    // }

    // ///
    // #[inline]
    // fn map_mut_ref<F, T, U>(self, f: F) -> Map<Self, F>
    // where
    //     Self: for<'a> Collector<&'a T> + Sized,
    //     F: FnMut(&mut U) -> &T,
    //     T: ?Sized,
    //     U: ?Sized,
    // {
    //     assert_collector::<_, &mut U>(Map::new(self, f))
    // }

    // ///
    // #[inline]
    // fn map_mut_mut<F, T, U>(self, f: F) -> Map<Self, F>
    // where
    //     Self: for<'a> Collector<&'a mut T> + Sized,
    //     F: FnMut(&mut U) -> &mut T,
    //     T: ?Sized,
    //     U: ?Sized,
    // {
    //     assert_collector::<_, &mut U>(Map::new(self, f))
    // }

    /// A collector that flattens items by one level of nesting before collecting.
    ///
    /// Each item will be converted into an iterator, then the underlying collector
    /// collects every element in that iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .flatten();
    ///
    /// assert!(collector.collect([1, 2]).is_continue());
    /// assert!(collector.collect(&[] as &[i32]).is_continue());
    /// assert!(collector.collect(vec![3, 4, 5]).is_continue());
    ///
    /// assert_eq!(collector.finish(), [1, 2, 3, 4, 5]);
    /// ```
    #[inline]
    fn flatten(self) -> Flatten<Self>
    where
        Self: Sized,
    {
        assert_collector_base(Flatten::new(self))
    }

    /// A collector that collects elements in each iterator item provided by a closure.
    ///
    /// Each item will be mapped into an iterator by a closure,
    /// then the underlying collector collects every element in that iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = String::new()
    ///     .into_collector()
    ///     .flat_map(str::chars);
    ///
    /// assert!(collector.collect("elegance ").is_continue());
    /// assert!(collector.collect("and ").is_continue());
    /// assert!(collector.collect("radiance").is_continue());
    ///
    /// assert_eq!(collector.finish(), "elegance and radiance");
    /// ```
    #[inline]
    fn flat_map<F, T, I>(self, f: F) -> FlatMap<Self, F>
    where
        Self: Collector<I::Item> + Sized,
        F: FnMut(T) -> I,
        I: IntoIterator,
    {
        assert_collector::<_, T>(FlatMap::new(self, f))
    }

    /// Creates a "by reference" adapter for this collector.
    ///
    /// Used when you do not want, yet, consume the collector
    /// and reuse it further.
    ///
    /// It is possible since `&mut C` implements [`Collector<T>`]
    /// when `C` implements [`Collector<T>`].
    ///
    /// Due to this, function signatures and structs (using generics)
    /// should only either expect an [`impl Collector<T>`](Collector)
    /// or [`impl IntoCollector<T>`](super::IntoCollector)
    /// for more flexibility, allowing callers to opt for
    /// either ownership or borrowing.
    ///
    /// Also, if you do not chain adapters (before and after `by_ref()`),
    /// consider passing a `&mut collector` instead to express the intent better.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// fn fill_one_and_two(collector: impl IntoCollector<i32>) {
    ///     collector
    ///         .into_collector()
    ///         .collect_many([1, 2]);
    /// }
    ///
    /// let mut collector = vec![].into_collector();
    /// // `by_ref()` works, but this is more readable.
    /// fill_one_and_two(&mut collector);
    /// assert!(collector.collect(3).is_continue());
    /// assert_eq!(collector.finish(), [1, 2, 3]);
    ///
    /// let mut collector = vec![].into_collector();
    /// fill_one_and_two(collector.by_ref().filter(|&num| num % 2 == 0));
    /// assert!(collector.collect(3).is_continue());
    /// assert_eq!(collector.finish(), [2, 3]);
    /// ```
    #[inline]
    fn by_ref(&mut self) -> &mut Self
    where
        Self: Sized,
    {
        self
    }

    /// Creates a collector that "views" each item first before collecting.
    ///
    /// It is used when you want to debug/log what happens between transformations.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .inspect(|&num| println!("After the filter: {num}"))
    ///     .filter(|&num| num % 2 != 0)
    ///     .inspect(|&num| println!("Before the filter: {num}"));
    ///
    /// assert!(collector.collect(1).is_continue());
    /// assert!(collector.collect(2).is_continue());
    /// assert!(collector.collect(3).is_continue());
    ///
    /// assert_eq!(collector.finish(), [1, 3]);
    /// ```
    #[inline]
    fn inspect<F, T>(self, f: F) -> Inspect<Self, F>
    where
        Self: Collector<T> + Sized,
        F: FnMut(&T),
    {
        assert_collector::<_, T>(Inspect::new(self, f))
    }

    /// Creates a collector that alternates the behavior of [`break_hint()`](Self::break_hint).
    ///
    /// This is useful for [`unbatching()`](Self::unbatching) and
    /// [`TryFold`](crate::iter::TryFold), when you want to configure
    /// whether those stop accumulating on construction.
    ///
    /// You can leverage the fact that "after any of
    /// [`Collector::collect()`], [`Collector::collect_many()`], or
    /// [`CollectorBase::break_hint()`] have returned [`Break(())`] once,
    /// behaviors of subsequent calls to any method other than
    /// [`finish()`](CollectorBase::finish) are unspecified"
    /// to calculate the hint before collecting only.
    ///
    /// [`Break(())`]: ControlFlow::Break
    //    ///
    //    /// # Examples
    //    ///
    //    /// ```
    //    /// use std::ops::ControlFlow;
    //    /// use better_collect::prelude::*;
    //    ///
    //    /// fn vec_zip(nums: impl IntoIterator<Item = i32>) -> impl Collector<i32, Output = Vec<i32>> {
    //    ///     let mut nums = nums.into_iter();
    //    ///     let sh = nums.size_hint();
    //    ///
    //    ///     vec![]
    //    ///         .into_collector()
    //    ///         .unbatching(move |collector, item| {
    //    ///             if let Some(num) = nums.next() {
    //    ///                 collector.collect(item)
    //    ///             } else {
    //    ///                 ControlFlow::Break(())
    //    ///             }
    //    ///         })
    //    ///         .alt_break_hint(move |_| {
    //    ///             if let (0, Some(0)) = sh {
    //    ///                 ControlFlow::Break(())
    //    ///             } else {
    //    ///                 ControlFlow::Continue(())
    //    ///             }
    //    ///         })
    //    /// }
    //    /// ```
    //    ///
    #[cfg(feature = "unstable")]
    #[inline]
    fn alt_break_hint<F>(self, f: F) -> AltBreakHint<Self, F>
    where
        Self: Sized,
        F: Fn(&Self) -> ControlFlow<()>,
    {
        assert_collector_base(AltBreakHint::new(self, f))
    }

    /// Creates a collector that distributes items between two collectors based on a predicate.
    ///
    /// Items for which the predicate returns [`Either::Left`] go to the first collector,
    /// and those for which it returns [`Either::Right`] go to the second collector.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .partition_map(From::from, vec![]);
    ///
    /// assert!(collector.collect(Ok(1)).is_continue());
    /// assert!(collector.collect(Err("Error")).is_continue());
    /// assert!(collector.collect(Ok(2)).is_continue());
    ///
    /// let (errs, oks) = collector.finish();
    ///
    /// assert_eq!(oks, [1, 2]);
    /// assert_eq!(errs, ["Error"]);
    /// ```
    #[cfg(feature = "itertools")]
    #[inline]
    fn partition_map<C, F, T, L, R>(
        self,
        pred: F,
        collector_right: C,
    ) -> PartitionMap<Self, C::IntoCollector, F>
    where
        Self: Collector<L> + Sized,
        C: IntoCollector<R>,
        F: FnMut(T) -> Either<L, R>,
    {
        PartitionMap::new(self, collector_right.into_collector(), pred)
    }

    /// Creates a collector that mutates each item first before collecting.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .update(|num| *num += 1);
    ///
    /// assert!(collector.collect(1).is_continue());
    /// assert!(collector.collect(2).is_continue());
    /// assert!(collector.collect(3).is_continue());
    ///
    /// assert_eq!(collector.finish(), [2, 3, 4]);
    /// ```
    #[cfg(feature = "itertools")]
    #[inline]
    fn update<F, T>(self, f: F) -> Update<Self, F>
    where
        Self: Collector<T> + Sized,
        F: FnMut(&mut T),
    {
        Update::new(self, f)
    }

    /// Creates a collector that collects all outputs produced by an inner collector.
    ///
    /// The inner collector collects items first until it stops accumulating,
    /// then, the outer collector collects the output produced by the inner collector,
    /// then repeat.
    ///
    /// The inner collector must implement [`Clone`]. Also, it should be finite
    /// so that the outer can collect more, or else the outer will be stuck with
    /// one output forever.
    ///
    /// This version collects the unfinished inner (the remainder), if any,
    /// after calling [`finish()`] or [`collect_then_finish()`].
    /// Hence, this adaptor is not "exact," similar to [`[_]::chunks()`](slice::chunks).
    /// Use [`nest_exact()`](CollectorBase::nest_exact) if you do not care about the remainder,
    /// since the exact verion is generally faster.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .nest(vec![].into_collector().take(3));
    ///
    /// assert!(collector.collect_many(1..=11).is_continue());
    ///
    /// assert_eq!(
    ///     collector.finish(),
    ///     [
    ///         vec![1, 2, 3],
    ///         vec![4, 5, 6],
    ///         vec![7, 8, 9],
    ///         vec![10, 11],
    ///     ],
    /// );
    /// ```
    ///
    /// [`finish()`]: CollectorBase::finish
    /// [`collect_then_finish()`]: Collector::collect_then_finish
    #[cfg(feature = "unstable")]
    fn nest<C>(self, inner: C) -> Nest<Self, C::IntoCollector>
    where
        Self: Collector<C::Output> + Sized,
        C: IntoCollectorBase<IntoCollector: Clone>,
    {
        assert_collector_base(Nest::new(self, inner.into_collector()))
    }

    /// Creates a collector that collects all outputs produced by an inner collector.
    ///
    /// The inner collector collects items first until it stops accumulating,
    /// then, the outer collector collects the output produced by the inner collector,
    /// then repeat.
    ///
    /// The inner collector must implement [`Clone`]. Also, it should be finite
    /// so that the outer can collect more, or else the outer will be stuck with
    /// one output forever.
    ///
    /// This version will only collect all the inners that has stopped accumulating.
    /// Any unfinished inner (the remainder) is discarded after calling
    /// [`finish()`] or [`collect_then_finish()`].
    /// Hence, this adaptor is "exact," similar to [`[_]::chunks_exact()`](slice::chunks_exact).
    /// Since the implementation is simpler, this adaptor is generally faster.
    /// Use [`nest()`](CollectorBase::nest) if you care about the remainder.
    ///
    /// # Examples
    ///
    /// ```
    /// use better_collect::prelude::*;
    ///
    /// let mut collector = vec![]
    ///     .into_collector()
    ///     .nest_exact(vec![].into_collector().take(3));
    ///
    /// assert!(collector.collect_many(1..=11).is_continue());
    ///
    /// assert_eq!(
    ///     collector.finish(),
    ///     [
    ///         [1, 2, 3],
    ///         [4, 5, 6],
    ///         [7, 8, 9],
    ///     ],
    /// );
    /// ```
    ///
    /// [`finish()`]: CollectorBase::finish
    /// [`collect_then_finish()`]: Collector::collect_then_finish
    #[cfg(feature = "unstable")]
    fn nest_exact<C>(self, inner: C) -> NestExact<Self, C::IntoCollector>
    where
        Self: Collector<C::Output> + Sized,
        C: IntoCollectorBase<IntoCollector: Clone>,
    {
        assert_collector_base(NestExact::new(self, inner.into_collector()))
    }
}

impl<C> CollectorBase for &mut C
where
    C: CollectorBase,
{
    type Output = ();

    fn finish(self) -> Self::Output {}

    fn break_hint(&self) -> ControlFlow<()> {
        C::break_hint(self)
    }
}

macro_rules! dyn_impl {
    ($($traits:ident)*) => {
        impl<'a> CollectorBase for &mut (dyn CollectorBase $(+ $traits)* + 'a) {
            type Output = ();

            #[inline]
            fn finish(self) -> Self::Output {}

            #[inline]
            fn break_hint(&self) -> ControlFlow<()> {
                <dyn CollectorBase>::break_hint(self)
            }
        }

        impl<'a, T> CollectorBase for &mut (dyn super::Collector<T> $(+ $traits)* + 'a) {
            type Output = ();

            #[inline]
            fn finish(self) -> Self::Output {}

            #[inline]
            fn break_hint(&self) -> ControlFlow<()> {
                <dyn super::Collector<T>>::break_hint(self)
            }
        }
    };
}

dyn_impl!();
dyn_impl!(Send);
dyn_impl!(Sync);
dyn_impl!(Send Sync);

// `Output` shouldn't be required to be specified.
fn _dyn_compatible(_: &mut dyn CollectorBase) {}

// You actually read this? So here's a workaround for issues
// when you can't even name the type (e.g. closures, async blocks).
#[cfg(feature = "std")]
fn _unnamed_type_workaround() {
    use crate::{cmp::Max, prelude::*};

    [|| ""].into_iter().feed_into(
        Max::new()
            .map({
                fn f(s: &mut impl FnMut() -> &'static str) -> &'static str {
                    s()
                }
                f
            })
            .take_while({
                fn f(_: &&mut impl FnMut() -> &'static str) -> bool {
                    true
                }
                f
                // |_| true
            })
            .tee_funnel(vec![]),
    );
}