@@ -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 !self . handled_first {
90
+ // Haven't seen the first item yet, and there might be one to give.
91
+ self . handled_first = true ;
92
+ if let Some ( first) = self . peekable . next ( ) {
93
+ // Peek to see if this is also the last item,
94
+ // in which case tag it as `Only`.
95
+ match self . peekable . peek ( ) {
96
+ Some ( _) => init = f ( init, ( Position :: First , first) ) ,
97
+ None => return f ( init, ( Position :: Only , first) ) ,
98
+ }
99
+ }
100
+ }
101
+ if let Some ( mut head) = self . peekable . next ( ) {
102
+ // Have seen the first item, and there's something left.
103
+ ( init, head) = self . peekable . fold ( ( init, head) , |( acc, old) , new| {
104
+ ( f ( acc, ( Position :: Middle , old) ) , new)
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