@@ -2,7 +2,7 @@ use crate::array;
2
2
use crate :: iter:: { FusedIterator , Iterator } ;
3
3
use crate :: mem;
4
4
use crate :: mem:: MaybeUninit ;
5
- use crate :: ops:: { ControlFlow , Try } ;
5
+ use crate :: ops:: { ControlFlow , NeverShortCircuit , Try } ;
6
6
use crate :: ptr;
7
7
8
8
/// An iterator over `N` elements of the iterator at a time.
@@ -104,30 +104,12 @@ where
104
104
}
105
105
}
106
106
107
- fn fold < B , F > ( self , init : B , mut f : F ) -> B
107
+ fn fold < B , F > ( mut self , init : B , mut f : F ) -> B
108
108
where
109
109
Self : Sized ,
110
110
F : FnMut ( B , Self :: Item ) -> B ,
111
111
{
112
- let mut array = MaybeUninit :: uninit_array ( ) ;
113
- // SAFETY: `array` will still be valid if `guard` is dropped.
114
- let mut guard = unsafe { FrontGuard :: new ( & mut array) } ;
115
-
116
- self . iter . fold ( init, |mut acc, item| {
117
- // SAFETY: `init` starts at 0, increases by one each iteration and
118
- // is reset to 0 once it reaches N.
119
- unsafe { array. get_unchecked_mut ( guard. init ) } . write ( item) ;
120
- guard. init += 1 ;
121
- if guard. init == N {
122
- guard. init = 0 ;
123
- let array = mem:: replace ( & mut array, MaybeUninit :: uninit_array ( ) ) ;
124
- // SAFETY: the condition above asserts that all elements are
125
- // initialized.
126
- let item = unsafe { MaybeUninit :: array_assume_init ( array) } ;
127
- acc = f ( acc, item) ;
128
- }
129
- acc
130
- } )
112
+ self . try_fold ( init, |acc, x| NeverShortCircuit ( f ( acc, x) ) ) . 0
131
113
}
132
114
}
133
115
@@ -205,31 +187,7 @@ where
205
187
Self : Sized ,
206
188
F : FnMut ( B , Self :: Item ) -> B ,
207
189
{
208
- // We are iterating from the back we need to first handle the remainder.
209
- if self . next_back_remainder ( ) . is_none ( ) {
210
- return init;
211
- }
212
-
213
- let mut array = MaybeUninit :: uninit_array ( ) ;
214
-
215
- // SAFETY: `array` will still be valid if `guard` is dropped.
216
- let mut guard = unsafe { BackGuard :: new ( & mut array) } ;
217
-
218
- self . iter . rfold ( init, |mut acc, item| {
219
- guard. uninit -= 1 ;
220
- // SAFETY: `uninit` starts at N, decreases by one each iteration and
221
- // is reset to N once it reaches 0.
222
- unsafe { array. get_unchecked_mut ( guard. uninit ) } . write ( item) ;
223
- if guard. uninit == 0 {
224
- guard. uninit = N ;
225
- let array = mem:: replace ( & mut array, MaybeUninit :: uninit_array ( ) ) ;
226
- // SAFETY: the condition above asserts that all elements are
227
- // initialized.
228
- let item = unsafe { MaybeUninit :: array_assume_init ( array) } ;
229
- acc = f ( acc, item) ;
230
- }
231
- acc
232
- } )
190
+ self . try_rfold ( init, |acc, x| NeverShortCircuit ( f ( acc, x) ) ) . 0
233
191
}
234
192
}
235
193
0 commit comments