@@ -379,4 +379,66 @@ impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
379379 fn nth_back ( & mut self , n : usize ) -> Option < I :: Item > {
380380 ( * * self ) . nth_back ( n)
381381 }
382+ fn rfold < B , F > ( self , init : B , f : F ) -> B
383+ where
384+ F : FnMut ( B , Self :: Item ) -> B ,
385+ {
386+ self . spec_rfold ( init, f)
387+ }
388+ fn try_rfold < B , F , R > ( & mut self , init : B , f : F ) -> R
389+ where
390+ F : FnMut ( B , Self :: Item ) -> R ,
391+ R : Try < Output = B > ,
392+ {
393+ self . spec_try_rfold ( init, f)
394+ }
395+ }
396+
397+ /// Helper trait to specialize `rfold` and `rtry_fold` for `&mut I where I: Sized`
398+ trait DoubleEndedIteratorRefSpec : DoubleEndedIterator {
399+ fn spec_rfold < B , F > ( self , init : B , f : F ) -> B
400+ where
401+ F : FnMut ( B , Self :: Item ) -> B ;
402+
403+ fn spec_try_rfold < B , F , R > ( & mut self , init : B , f : F ) -> R
404+ where
405+ F : FnMut ( B , Self :: Item ) -> R ,
406+ R : Try < Output = B > ;
407+ }
408+
409+ impl < I : DoubleEndedIterator + ?Sized > DoubleEndedIteratorRefSpec for & mut I {
410+ default fn spec_rfold < B , F > ( self , init : B , mut f : F ) -> B
411+ where
412+ F : FnMut ( B , Self :: Item ) -> B ,
413+ {
414+ let mut accum = init;
415+ while let Some ( x) = self . next_back ( ) {
416+ accum = f ( accum, x) ;
417+ }
418+ accum
419+ }
420+
421+ default fn spec_try_rfold < B , F , R > ( & mut self , init : B , mut f : F ) -> R
422+ where
423+ F : FnMut ( B , Self :: Item ) -> R ,
424+ R : Try < Output = B > ,
425+ {
426+ let mut accum = init;
427+ while let Some ( x) = self . next_back ( ) {
428+ accum = f ( accum, x) ?;
429+ }
430+ try { accum }
431+ }
432+ }
433+
434+ impl < I : DoubleEndedIterator > DoubleEndedIteratorRefSpec for & mut I {
435+ impl_fold_via_try_fold ! { spec_rfold -> spec_try_rfold }
436+
437+ fn spec_try_rfold < B , F , R > ( & mut self , init : B , f : F ) -> R
438+ where
439+ F : FnMut ( B , Self :: Item ) -> R ,
440+ R : Try < Output = B > ,
441+ {
442+ ( * * self ) . try_rfold ( init, f)
443+ }
382444}
0 commit comments