gat-lending-iterator 0.1.8

A library for iterators who's items can [mutably] reference the 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
use core::cmp::Ordering;
use std::{num::NonZeroUsize, ops::Deref};

use crate::{
    Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse, Inspect, Map, MapWhile,
    OptionTrait, Scan, SingleArgFnMut, SingleArgFnOnce, Skip, SkipWhile, StepBy, Take, TakeWhile,
    Zip,
};

/// Like [`Iterator`], but items may borrow from `&mut self`.
///
/// This means that the compiler will check that you finish using an item
/// before requesting the next item, as it's not allowed for two `&mut self` to exist
/// at the same time.
pub trait LendingIterator {
    /// The type of the elements being iterated over.
    type Item<'a>
    where
        Self: 'a;

    /// Advances the lending iterator and returns the next value.
    ///
    /// See [`Iterator::next`].
    fn next(&mut self) -> Option<Self::Item<'_>>;

    /// Returns the bounds on the remaining length of the iterator.
    ///
    /// See [`Iterator::size_hint`].
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }

    /// Returns the number of items in the lending iterator.
    ///
    /// See [`Iterator::count`].
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.fold(0, |count, _| count + 1)
    }

    /// Advances the lending iterator by `n` elements.
    ///
    /// See [`Iterator::advance_by`].
    #[inline]
    #[allow(clippy::missing_errors_doc)]
    fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> {
        for i in 0..n {
            if self.next().is_none() {
                // SAFETY: `i` is always less than `n`.
                return Err(unsafe { NonZeroUsize::new_unchecked(n - i) });
            }
        }
        Ok(())
    }

    /// Returns the `n`th element of the lending iterator.
    ///
    /// See [`Iterator::nth`].
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item<'_>> {
        self.advance_by(n).ok()?;
        self.next()
    }

    /// Creates a lending iterator starting at the same point, but stepping by
    /// the given amount at each iteration.
    ///
    /// See [`Iterator::step_by`].
    #[inline]
    fn step_by(self, step: usize) -> StepBy<Self>
    where
        Self: Sized,
    {
        StepBy::new(self, step)
    }

    /// Creates a lending iterator that lends the first `n` elements, or fewer
    /// if the underlying iterator ends sooner.
    ///
    /// See [`Iterator::take`].
    #[inline]
    fn take(self, n: usize) -> Take<Self>
    where
        Self: Sized,
    {
        Take::new(self, n)
    }

    /// Creates a lending iterator that lends items matching a predicate.
    ///
    /// The predicate is called once for every item.
    /// Once it returns false once, `None` is returned for all subsequent calls to [`next`].
    ///
    /// [`next`]: Self::next
    #[inline]
    fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
    where
        Self: Sized,
        P: for<'a> FnMut(&Self::Item<'a>) -> bool,
    {
        TakeWhile::new(self, predicate)
    }

    /// Takes two lending iterators and creates a new lending iterator over both in sequence.
    ///
    /// See [`Iterator::chain`].
    #[inline]
    fn chain<I>(self, other: I) -> Chain<Self, I>
    where
        Self: Sized,
        for<'a> I: LendingIterator<Item<'a> = Self::Item<'a>> + 'a,
    {
        Chain::new(self, other)
    }

    /// 'Zips up' two lending iterators into a single lending iterator of pairs.
    #[inline]
    fn zip<I>(self, other: I) -> Zip<Self, I>
    where
        Self: Sized,
        I: LendingIterator,
    {
        Zip::new(self, other)
    }

    /// Takes a closure and creates a lending iterator which calls that closure on each
    /// element.
    ///
    /// As of writing, in stable rust it's not possible to create a closure
    /// where the lifetime of its output is tied to its input.
    /// If you're on nightly, you can use the unstable
    /// `closure_lifetime_binder` feature. If you're on stable, try using
    /// a function.
    ///
    /// In the case that the closure's return type doesn't borrow from its input,
    /// the resulting `LendingIterator` will implement [`IntoIterator`].
    ///
    /// See [`Iterator::map`].
    #[inline]
    fn map<F>(self, f: F) -> Map<Self, F>
    where
        Self: Sized,
        F: for<'a> SingleArgFnMut<Self::Item<'a>>,
    {
        Map::new(self, f)
    }

    /// Calls a closure on each element of the lending iterator.
    ///
    /// See [`Iterator::for_each`].
    #[inline]
    fn for_each<F>(mut self, mut f: F)
    where
        Self: Sized,
        F: FnMut(Self::Item<'_>),
    {
        while let Some(item) = self.next() {
            f(item);
        }
    }

    /// Creates a lending iterator which uses a closure to determine if an element
    /// should be yielded.
    ///
    /// See [`Iterator::filter`].
    #[inline]
    fn filter<P>(self, predicate: P) -> Filter<Self, P>
    where
        Self: Sized,
        P: for<'a> FnMut(&Self::Item<'a>) -> bool,
    {
        Filter::new(self, predicate)
    }

    /// Creates a lending iterator that both filters and maps.
    ///
    /// See [`Iterator::filter_map`].
    #[inline]
    fn filter_map<F>(self, f: F) -> FilterMap<Self, F>
    where
        Self: Sized,
        F: for<'a> SingleArgFnMut<Self::Item<'a>>,
        for<'a> <F as SingleArgFnOnce<Self::Item<'a>>>::Output: OptionTrait,
    {
        FilterMap::new(self, f)
    }

    /// Folds every element into an accumulator by applying an operation,
    /// returning the final result.
    ///
    /// See [`Iterator::fold`].
    #[inline]
    fn fold<B, F>(mut self, init: B, mut f: F) -> B
    where
        Self: Sized,
        F: FnMut(B, Self::Item<'_>) -> B,
    {
        let mut accum = init;
        while let Some(x) = self.next() {
            accum = f(accum, x);
        }
        accum
    }

    /// Creates a lending iterator which [`clone`]s all of its elements.
    ///
    /// The resulting lending iterator implements [`IntoIterator`].
    ///
    /// See [`Iterator::cloned`].
    ///
    /// [`clone`]: Clone::clone
    fn cloned<T>(self) -> Cloned<Self>
    where
        Self: Sized,
        for<'a> Self::Item<'a>: Deref<Target = T>,
        T: Clone,
    {
        Cloned::new(self)
    }

    /// Creates a lending iterator which copies all of its elements.
    ///
    /// The resulting lending iterator implements [`IntoIterator`].
    ///
    /// See [`Iterator::copied`].
    #[inline]
    fn copied<T>(self) -> Copied<Self>
    where
        Self: Sized,
        for<'a> Self::Item<'a>: Deref<Target = T>,
        T: Copy,
    {
        Copied::new(self)
    }

    /// Creates a lending iterator which gives the current iteration count as well as the next value.
    #[inline]
    fn enumerate(self) -> Enumerate<Self>
    where
        Self: Sized,
    {
        Enumerate::new(self)
    }

    /// Creates a lending iterator that skips over the first `n` elements of self.
    #[inline]
    fn skip(self, n: usize) -> Skip<Self>
    where
        Self: Sized,
    {
        Skip::new(self, n)
    }

    /// Creates a lending iterator that rejects elements while `predicate` returns `true`.
    #[inline]
    fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
    where
        Self: Sized,
        P: for<'a> FnMut(&Self::Item<'a>) -> bool,
    {
        SkipWhile::new(self, predicate)
    }

    /// Creates a lending iterator that yields the current element unchanged,
    /// while calling a provided function with a reference to that element.
    ///
    /// See [`Iterator::inspect`].
    #[inline]
    fn inspect<F>(self, f: F) -> Inspect<Self, F>
    where
        Self: Sized,
        F: for<'a> FnMut(&Self::Item<'a>),
    {
        Inspect::new(self, f)
    }

    /// Creates a lending iterator that yields elements transformed by a stateful closure.
    ///
    /// See [`Iterator::scan`].
    #[inline]
    fn scan<St, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
    where
        Self: Sized,
    {
        Scan::new(self, initial_state, f)
    }

    /// Creates a lending iterator that yields elements while the predicate returns `Some`.
    ///
    /// See [`Iterator::map_while`].
    #[inline]
    fn map_while<F>(self, f: F) -> MapWhile<Self, F>
    where
        Self: Sized,
        F: for<'a> SingleArgFnMut<Self::Item<'a>>,
        for<'a> <F as SingleArgFnOnce<Self::Item<'a>>>::Output: OptionTrait,
    {
        MapWhile::new(self, f)
    }

    /// Creates a lending iterator that yields `None` forever after the
    /// underlying iterator yields `None` once.
    ///
    /// See [`Iterator::fuse`].
    #[inline]
    fn fuse(self) -> Fuse<Self>
    where
        Self: Sized,
    {
        Fuse::new(self)
    }

    /// Creates a lending iterator that repeats elements endlessly by cloning the iterator.
    ///
    /// See [`Iterator::cycle`].
    #[inline]
    fn cycle(self) -> Cycle<Self>
    where
        Self: Sized + Clone,
    {
        Cycle::new(self)
    }

    /// Borrows the lending iterator.
    ///
    /// This is useful to allow applying iterator adapters while still
    /// retaining ownership of the original iterator.
    ///
    /// Unfortunately adapters that take in a closure are currently
    /// incompatible with this, due to limitations in the borrow checker.
    #[inline]
    fn by_ref(&mut self) -> &mut Self
    where
        Self: Sized,
    {
        self
    }

    /// Tests if every element of the iterator matches a predicate.
    #[inline]
    fn all<P>(&mut self, mut predicate: P) -> bool
    where
        P: FnMut(Self::Item<'_>) -> bool,
    {
        while let Some(item) = self.next() {
            if !predicate(item) {
                return false;
            }
        }
        true
    }

    /// Tests if any element of the iterator matches a predicate.
    #[inline]
    fn any<P>(&mut self, mut predicate: P) -> bool
    where
        P: FnMut(Self::Item<'_>) -> bool,
    {
        while let Some(item) = self.next() {
            if predicate(item) {
                return true;
            }
        }
        false
    }

    /// Checks if the elements of this iterator are partitioned according to the given predicate,
    /// such that all those that return `true` precede all those that return `false`.
    #[inline]
    #[allow(clippy::wrong_self_convention)]
    fn is_partitioned<P>(mut self, mut predicate: P) -> bool
    where
        Self: Sized,
        P: FnMut(Self::Item<'_>) -> bool,
    {
        while let Some(item) = self.next() {
            if !predicate(item) {
                break;
            }
        }
        while let Some(item) = self.next() {
            if predicate(item) {
                return false;
            }
        }
        true
    }

    /// Searches for an element of an iterator that satisfies a predicate.
    #[inline]
    fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item<'_>>
    where
        P: FnMut(&Self::Item<'_>) -> bool,
    {
        loop {
            // SAFETY: see https://docs.rs/polonius-the-crab/0.3.1/polonius_the_crab/#the-arcanemagic
            let self_ = unsafe { &mut *(self as *mut Self) };
            if let Some(item) = self_.next() {
                if (predicate)(&item) {
                    return Some(item);
                }
            } else {
                return None;
            }
        }
    }

    /// Applies function to the elements of iterator and returns
    /// the first non-none result.
    #[inline]
    fn find_map<B, F>(&mut self, mut f: F) -> Option<B>
    where
        F: FnMut(Self::Item<'_>) -> Option<B>,
    {
        loop {
            // SAFETY: see https://docs.rs/polonius-the-crab/0.3.1/polonius_the_crab/#the-arcanemagic
            let self_ = unsafe { &mut *(self as *mut Self) };
            if let Some(item) = self_.next() {
                if let Some(result) = f(item) {
                    return Some(result);
                }
            } else {
                return None;
            }
        }
    }

    /// Searches for an element in an iterator, returning its index.
    #[inline]
    fn position<P>(&mut self, mut predicate: P) -> Option<usize>
    where
        P: FnMut(Self::Item<'_>) -> bool,
    {
        let mut i = 0;
        while let Some(item) = self.next() {
            if predicate(item) {
                return Some(i);
            }
            i += 1;
        }
        None
    }

    /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
    /// of another.
    fn cmp<I>(mut self, mut other: I) -> Ordering
    where
        I: for<'a> LendingIterator<Item<'a> = Self::Item<'a>>,
        for<'a> Self::Item<'a>: Ord,
        Self: Sized,
    {
        // TODO: this could be implemented as `self.cmp_by(other, |x, y| x.cmp(y))`
        // except that doesn't type check due to lifetime issues.
        loop {
            match (self.next(), other.next()) {
                (Some(x), Some(y)) => match x.cmp(&y) {
                    Ordering::Equal => {}
                    non_eq => return non_eq,
                },
                (None, None) => return Ordering::Equal,
                (None, _) => return Ordering::Less,
                (_, None) => return Ordering::Greater,
            }
        }
    }

    /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
    /// of another with respect to the specified comparison function.
    fn cmp_by<I, F>(mut self, mut other: I, mut cmp: F) -> Ordering
    where
        Self: Sized,
        I: LendingIterator,
        F: FnMut(Self::Item<'_>, I::Item<'_>) -> Ordering,
    {
        loop {
            match (self.next(), other.next()) {
                (Some(x), Some(y)) => match cmp(x, y) {
                    Ordering::Equal => {}
                    non_eq => return non_eq,
                },
                (None, None) => return Ordering::Equal,
                (None, _) => return Ordering::Less,
                (_, None) => return Ordering::Greater,
            }
        }
    }

    /// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of
    /// this [`Iterator`] with those of another. The comparison works like short-circuit
    /// evaluation, returning a result without comparing the remaining elements.
    /// As soon as an order can be determined, the evaluation stops and a result is returned.
    fn partial_cmp<I>(mut self, mut other: I) -> Option<Ordering>
    where
        I: LendingIterator,
        for<'a> Self::Item<'a>: PartialOrd<I::Item<'a>>,
        Self: Sized,
    {
        loop {
            match (self.next(), other.next()) {
                (Some(x), Some(y)) => match x.partial_cmp(&y) {
                    Some(Ordering::Equal) => {}
                    non_eq => return non_eq,
                },
                (None, None) => return Some(Ordering::Equal),
                (None, _) => return Some(Ordering::Less),
                (_, None) => return Some(Ordering::Greater),
            }
        }
    }

    /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
    /// of another with respect to the specified comparison function.
    fn partial_cmp_by<I, F>(mut self, mut other: I, mut partial_cmp: F) -> Option<Ordering>
    where
        Self: Sized,
        I: LendingIterator,
        F: FnMut(Self::Item<'_>, I::Item<'_>) -> Option<Ordering>,
    {
        loop {
            match (self.next(), other.next()) {
                (Some(x), Some(y)) => match partial_cmp(x, y) {
                    Some(Ordering::Equal) => {}
                    non_eq => return non_eq,
                },
                (None, None) => return Some(Ordering::Equal),
                (None, _) => return Some(Ordering::Less),
                (_, None) => return Some(Ordering::Greater),
            }
        }
    }

    /// Determines if the elements of this [`Iterator`] are equal to those of
    /// another.
    fn eq<I>(mut self, mut other: I) -> bool
    where
        I: LendingIterator,
        for<'a> Self::Item<'a>: PartialEq<I::Item<'a>>,
        Self: Sized,
    {
        loop {
            match (self.next(), other.next()) {
                (Some(x), Some(y)) => {
                    if x != y {
                        return false;
                    }
                }
                (None, None) => return true,
                _ => return false,
            }
        }
    }

    /// Determines if the elements of this [`Iterator`] are equal to those of
    /// another with respect to the specified equality function.
    fn eq_by<I, F>(mut self, mut other: I, mut eq: F) -> bool
    where
        Self: Sized,
        I: LendingIterator,
        F: FnMut(Self::Item<'_>, I::Item<'_>) -> bool,
    {
        loop {
            match (self.next(), other.next()) {
                (Some(x), Some(y)) => {
                    if !eq(x, y) {
                        return false;
                    }
                }
                (None, None) => return true,
                _ => return false,
            }
        }
    }

    /// Determines if the elements of this [`Iterator`] are not equal to those of
    /// another.
    fn ne<I>(self, other: I) -> bool
    where
        I: LendingIterator,
        for<'a> Self::Item<'a>: PartialEq<I::Item<'a>>,
        Self: Sized,
    {
        !self.eq(other)
    }

    /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
    /// less than those of another.
    fn lt<I>(self, other: I) -> bool
    where
        I: LendingIterator,
        for<'a> Self::Item<'a>: PartialOrd<I::Item<'a>>,
        Self: Sized,
    {
        self.partial_cmp(other) == Some(Ordering::Less)
    }

    /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
    /// less or equal to those of another.
    fn le<I>(self, other: I) -> bool
    where
        I: LendingIterator,
        for<'a> Self::Item<'a>: PartialOrd<I::Item<'a>>,
        Self: Sized,
    {
        matches!(
            self.partial_cmp(other),
            Some(Ordering::Less | Ordering::Equal)
        )
    }

    /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
    /// greater than those of another.
    fn gt<I>(self, other: I) -> bool
    where
        I: LendingIterator,
        for<'a> Self::Item<'a>: PartialOrd<I::Item<'a>>,
        Self: Sized,
    {
        self.partial_cmp(other) == Some(Ordering::Greater)
    }

    /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
    /// greater or equal to those of another.
    fn ge<I>(self, other: I) -> bool
    where
        I: LendingIterator,
        for<'a> Self::Item<'a>: PartialOrd<I::Item<'a>>,
        Self: Sized,
    {
        matches!(
            self.partial_cmp(other),
            Some(Ordering::Greater | Ordering::Equal)
        )
    }

    /// Reduces the elements to a single one, by repeatedly applying a reducing
    /// operation.
    ///
    /// If the iterator is empty, returns [`None`]; otherwise, returns the
    /// result of the reduction.
    ///
    /// The reducing function takes an accumulator and an element and returns a new accumulator.
    /// For lending iterators, since items borrow from `&mut self`, the accumulator must be
    /// an owned type that doesn't borrow from the iterator.
    ///
    /// See [`Iterator::reduce`].
    #[inline]
    fn reduce<B, F>(mut self, f: F) -> Option<B>
    where
        Self: Sized,
        F: FnMut(B, Self::Item<'_>) -> B,
        B: for<'a> From<Self::Item<'a>>,
    {
        let first = B::from(self.next()?);
        Some(self.fold(first, f))
    }

    /// An iterator method that applies a fallible function to each item in the
    /// iterator, stopping at the first error and returning that error.
    ///
    /// After an error is returned, the iterator may be in an unspecified state.
    ///
    /// # Errors
    ///
    /// Returns the first error produced by the closure `f`.
    ///
    /// See [`Iterator::try_fold`].
    #[inline]
    fn try_fold<B, F, E>(&mut self, init: B, mut f: F) -> Result<B, E>
    where
        Self: Sized,
        F: FnMut(B, Self::Item<'_>) -> Result<B, E>,
    {
        let mut accum = init;
        while let Some(x) = self.next() {
            accum = f(accum, x)?;
        }
        Ok(accum)
    }

    /// An iterator method that applies a fallible function to each item in the
    /// iterator, stopping at the first error and returning that error.
    ///
    /// # Errors
    ///
    /// Returns the first error produced by the closure `f`.
    ///
    /// See [`Iterator::try_for_each`].
    #[inline]
    fn try_for_each<F, E>(&mut self, mut f: F) -> Result<(), E>
    where
        Self: Sized,
        F: FnMut(Self::Item<'_>) -> Result<(), E>,
    {
        while let Some(x) = self.next() {
            f(x)?;
        }
        Ok(())
    }

    /// Applies function to the elements of iterator and returns
    /// the first true result or the first error.
    ///
    /// # Errors
    ///
    /// Returns the first error produced by the predicate `f`.
    ///
    /// See [`Iterator::try_find`].
    #[inline]
    fn try_find<F, R>(&mut self, mut f: F) -> Result<Option<Self::Item<'_>>, R>
    where
        Self: Sized,
        F: FnMut(&Self::Item<'_>) -> Result<bool, R>,
    {
        loop {
            // SAFETY: see https://docs.rs/polonius-the-crab/0.3.1/polonius_the_crab/#the-arcanemagic
            let self_ = unsafe { &mut *(self as *mut Self) };
            if let Some(item) = self_.next() {
                match f(&item) {
                    Ok(true) => return Ok(Some(item)),
                    Ok(false) => continue,
                    Err(e) => return Err(e),
                }
            }
            return Ok(None);
        }
    }

    /// Reduces the elements to a single one by repeatedly applying a reducing operation.
    /// If the closure returns a failure, the failure is propagated back to the caller immediately.
    ///
    /// For lending iterators, the accumulator must be an owned type since items borrow from `&mut self`.
    ///
    /// # Errors
    ///
    /// Returns the first error produced by the reducing closure `f`.
    ///
    /// See [`Iterator::try_reduce`].
    #[inline]
    fn try_reduce<B, F, E>(mut self, f: F) -> Result<Option<B>, E>
    where
        Self: Sized,
        F: FnMut(B, Self::Item<'_>) -> Result<B, E>,
        B: for<'a> From<Self::Item<'a>>,
    {
        let first = B::from(match self.next() {
            Some(i) => i,
            None => return Ok(None),
        });
        self.try_fold(first, f).map(Some)
    }

    /// Returns the maximum element of an iterator.
    ///
    /// For lending iterators, items are compared in their borrowed form and only
    /// converted to the owned type `T` when they become the new maximum, minimizing
    /// conversions.
    ///
    /// See [`Iterator::max`].
    #[inline]
    fn max<T>(mut self) -> Option<T>
    where
        Self: Sized,
        T: for<'a> From<Self::Item<'a>>,
        for<'a> T: PartialOrd<Self::Item<'a>>,
    {
        let first = T::from(self.next()?);
        Some(self.fold(first, |max, x| if max < x { T::from(x) } else { max }))
    }

    /// Returns the minimum element of an iterator.
    ///
    /// For lending iterators, items are compared in their borrowed form and only
    /// converted to the owned type `T` when they become the new minimum, minimizing
    /// conversions.
    ///
    /// See [`Iterator::min`].
    #[inline]
    fn min<T>(mut self) -> Option<T>
    where
        Self: Sized,
        T: for<'a> From<Self::Item<'a>>,
        for<'a> T: PartialOrd<Self::Item<'a>>,
    {
        let first = T::from(self.next()?);
        Some(self.fold(first, |min, x| if min > x { T::from(x) } else { min }))
    }

    /// Returns the element that gives the maximum value from the specified function.
    ///
    /// For lending iterators, the comparison function operates on borrowed items and owned
    /// values. Items are only converted to `T` when they become the new maximum.
    ///
    /// See [`Iterator::max_by`].
    #[inline]
    fn max_by<T, F>(mut self, mut compare: F) -> Option<T>
    where
        Self: Sized,
        F: for<'a> FnMut(&T, &Self::Item<'a>) -> Ordering,
        T: for<'a> From<Self::Item<'a>>,
    {
        let first = T::from(self.next()?);
        Some(self.fold(first, |max, x| match compare(&max, &x) {
            Ordering::Less => T::from(x),
            _ => max,
        }))
    }

    /// Returns the element that gives the minimum value from the specified function.
    ///
    /// For lending iterators, the comparison function operates on borrowed items and owned
    /// values. Items are only converted to `T` when they become the new minimum.
    ///
    /// See [`Iterator::min_by`].
    #[inline]
    fn min_by<T, F>(mut self, mut compare: F) -> Option<T>
    where
        Self: Sized,
        F: for<'a> FnMut(&T, &Self::Item<'a>) -> Ordering,
        T: for<'a> From<Self::Item<'a>>,
    {
        let first = T::from(self.next()?);
        Some(self.fold(first, |min, x| match compare(&min, &x) {
            Ordering::Greater => T::from(x),
            _ => min,
        }))
    }

    /// Returns the element that gives the maximum value with respect to the
    /// specified key function.
    ///
    /// For lending iterators, the key function operates on borrowed items. Items are
    /// only converted to `T` when they produce a new maximum key.
    ///
    /// See [`Iterator::max_by_key`].
    #[inline]
    fn max_by_key<T, B, F>(mut self, mut f: F) -> Option<T>
    where
        Self: Sized,
        B: Ord,
        F: for<'a> FnMut(&Self::Item<'a>) -> B,
        T: for<'a> From<Self::Item<'a>>,
    {
        let first_item = self.next()?;
        let first_key = f(&first_item);
        let first = T::from(first_item);
        Some(
            self.fold((first, first_key), |(max, max_key), x| {
                let x_key = f(&x);
                if x_key > max_key {
                    (T::from(x), x_key)
                } else {
                    (max, max_key)
                }
            })
            .0,
        )
    }

    /// Returns the element that gives the minimum value with respect to the
    /// specified key function.
    ///
    /// For lending iterators, the key function operates on borrowed items. Items are
    /// only converted to `T` when they produce a new minimum key.
    ///
    /// See [`Iterator::min_by_key`].
    #[inline]
    fn min_by_key<T, B, F>(mut self, mut f: F) -> Option<T>
    where
        Self: Sized,
        B: Ord,
        F: for<'a> FnMut(&Self::Item<'a>) -> B,
        T: for<'a> From<Self::Item<'a>>,
    {
        let first_item = self.next()?;
        let first_key = f(&first_item);
        let first = T::from(first_item);
        Some(
            self.fold((first, first_key), |(min, min_key), x| {
                let x_key = f(&x);
                if x_key < min_key {
                    (T::from(x), x_key)
                } else {
                    (min, min_key)
                }
            })
            .0,
        )
    }

    /// Sums the elements of an iterator.
    ///
    /// Takes each element, converts it to the sum type, and adds them together.
    ///
    /// An empty iterator returns the zero value of the type.
    ///
    /// For lending iterators, items must be convertible to the sum type.
    ///
    /// See [`Iterator::sum`].
    #[inline]
    fn sum<S>(self) -> S
    where
        Self: Sized,
        for<'a> S: std::ops::AddAssign<Self::Item<'a>> + Default,
    {
        let mut sum = S::default();
        self.for_each(|item| sum += item);
        sum
    }

    /// Iterates over the entire iterator, multiplying all the elements
    ///
    /// An empty iterator returns the multiplicative identity (1).
    ///
    /// Unlike [`Iterator::product`], this works directly with borrowed items by requiring
    /// the product type to implement `MulAssign` for the borrowed item type.
    ///
    /// Note: Requires `From<u8>` to create the identity value (1). This works for all
    /// standard numeric types. For types without this conversion, consider using
    /// [`fold`](Self::fold) or [`reduce`](Self::reduce) instead.
    ///
    /// See [`Iterator::product`].
    #[inline]
    fn product<P>(self) -> P
    where
        Self: Sized,
        for<'a> P: std::ops::MulAssign<Self::Item<'a>>,
        P: From<u8>,
    {
        let mut product = P::from(1u8);
        self.for_each(|item| product *= item);
        product
    }
}

impl<T: LendingIterator> LendingIterator for &mut T {
    type Item<'a>
        = T::Item<'a>
    where
        Self: 'a;

    #[inline]
    fn next(&mut self) -> Option<Self::Item<'_>> {
        (**self).next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (**self).size_hint()
    }
}