@@ -81,6 +81,33 @@ impl<I: Iterator> Iterator for WithPosition<I> {
81
81
fn size_hint ( & self ) -> ( usize , Option < usize > ) {
82
82
self . peekable . size_hint ( )
83
83
}
84
+
85
+ fn fold < B , F > ( mut self , mut init : B , mut f : F ) -> B
86
+ where
87
+ F : FnMut ( B , Self :: Item ) -> B ,
88
+ {
89
+ if let Some ( mut head) = self . peekable . next ( ) {
90
+ if !self . handled_first {
91
+ // The current head is `First` or `Only`,
92
+ // it depends if there is another item or not.
93
+ match self . peekable . next ( ) {
94
+ Some ( second) => {
95
+ let first = std:: mem:: replace ( & mut head, second) ;
96
+ init = f ( init, ( Position :: First , first) ) ;
97
+ }
98
+ None => return f ( init, ( Position :: Only , head) ) ,
99
+ }
100
+ }
101
+ // Have seen the first item, and there's something left.
102
+ init = self . peekable . fold ( init, |acc, mut item| {
103
+ std:: mem:: swap ( & mut head, & mut item) ;
104
+ f ( acc, ( Position :: Middle , item) )
105
+ } ) ;
106
+ // The "head" is now the last item.
107
+ init = f ( init, ( Position :: Last , head) ) ;
108
+ }
109
+ init
110
+ }
84
111
}
85
112
86
113
impl < I > ExactSizeIterator for WithPosition < I > where I : ExactSizeIterator { }
0 commit comments