1use core::marker::PhantomData;
2
3use crate::{prelude::*, FusedLender};
4
5pub fn repeat_with<'a, L, F>(f: F) -> RepeatWith<'a, L, F>
18where
19 L: ?Sized + for<'all> Lending<'all> + 'a,
20 F: FnMut() -> Lend<'a, L>,
21{
22 RepeatWith { f, _marker: PhantomData }
23}
24
25pub struct RepeatWith<'a, L: ?Sized, F> {
29 f: F,
30 _marker: core::marker::PhantomData<&'a L>,
31}
32
33impl<'lend, 'a, L, F> Lending<'lend> for RepeatWith<'a, L, F>
34where
35 L: ?Sized + for<'all> Lending<'all> + 'a,
36 F: FnMut() -> Lend<'a, L>,
37{
38 type Lend = Lend<'lend, L>;
39}
40
41impl<'a, L, F> Lender for RepeatWith<'a, L, F>
42where
43 L: ?Sized + for<'all> Lending<'all> + 'a,
44 F: FnMut() -> Lend<'a, L>,
45{
46 #[inline]
47 fn next(&mut self) -> Option<Lend<'_, Self>> {
48 Some(unsafe { core::mem::transmute::<Lend<'a, L>, Lend<'_, L>>((self.f)()) })
50 }
51 #[inline]
52 fn advance_by(&mut self, _n: usize) -> Result<(), core::num::NonZeroUsize> {
53 Ok(())
54 }
55}
56
57impl<'a, L, F> FusedLender for RepeatWith<'a, L, F>
58where
59 L: ?Sized + for<'all> Lending<'all> + 'a,
60 F: FnMut() -> Lend<'a, L>,
61{
62}
63
64pub fn fallible_repeat_with<'a, L, E, F>(f: F) -> FallibleRepeatWith<'a, L, E, F>
72where
73 L: ?Sized + for<'all> FallibleLending<'all> + 'a,
74 F: FnMut() -> Result<FallibleLend<'a, L>, E>,
75{
76 FallibleRepeatWith { f, _marker: PhantomData }
77}
78
79pub struct FallibleRepeatWith<'a, L: ?Sized, E, F> {
83 f: F,
84 _marker: core::marker::PhantomData<(&'a L, E)>,
85}
86
87impl<'lend, 'a, L, E, F> FallibleLending<'lend> for FallibleRepeatWith<'a, L, E, F>
88where
89 L: ?Sized + for<'all> FallibleLending<'all> + 'a,
90 F: FnMut() -> Result<FallibleLend<'a, L>, E>,
91{
92 type Lend = FallibleLend<'lend, L>;
93}
94
95impl<'a, L, E, F> FallibleLender for FallibleRepeatWith<'a, L, E, F>
96where
97 L: ?Sized + for<'all> FallibleLending<'all> + 'a,
98 F: FnMut() -> Result<FallibleLend<'a, L>, E>,
99{
100 type Error = E;
101
102 #[inline]
103 fn next(&mut self) -> Result<Option<FallibleLend<'_, Self>>, Self::Error> {
104 (self.f)().map(|value| {
105 Some(
106 unsafe { core::mem::transmute::<FallibleLend<'a, L>, FallibleLend<'_, L>>(value) },
108 )
109 })
110 }
111 #[inline]
112 fn advance_by(&mut self, _n: usize) -> Result<Option<core::num::NonZeroUsize>, Self::Error> {
113 Ok(None)
114 }
115}