Guest User

Untitled

a guest
Feb 17th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. use std::fmt;
  2. use std::iter::FusedIterator;
  3.  
  4. #[derive(Clone)]
  5. pub struct MapWithSelf<I, F> {
  6. iter: I,
  7. f: F,
  8. }
  9.  
  10. impl<I: fmt::Debug, F> fmt::Debug for MapWithSelf<I, F> {
  11. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  12. f.debug_struct("MapWithSelf")
  13. .field("iter", &self.iter)
  14. .finish()
  15. }
  16. }
  17.  
  18. impl<B, I: Iterator, F> Iterator for MapWithSelf<I, F>
  19. where
  20. F: FnMut(&I, I::Item) -> B,
  21. {
  22. type Item = B;
  23.  
  24. #[inline]
  25. fn next(&mut self) -> Option<B> {
  26. self.iter.next().map(|n| (self.f)(&self.iter, n))
  27. }
  28.  
  29. #[inline]
  30. fn size_hint(&self) -> (usize, Option<usize>) {
  31. self.iter.size_hint()
  32. }
  33. }
  34.  
  35. impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for MapWithSelf<I, F>
  36. where
  37. F: FnMut(&I, I::Item) -> B,
  38. {
  39. #[inline]
  40. fn next_back(&mut self) -> Option<B> {
  41. self.iter.next_back().map(|n| (self.f)(&self.iter, n))
  42. }
  43. }
  44.  
  45. impl<B, I: ExactSizeIterator, F> ExactSizeIterator for MapWithSelf<I, F>
  46. where
  47. F: FnMut(&I, I::Item) -> B,
  48. {
  49. fn len(&self) -> usize {
  50. self.iter.len()
  51. }
  52. }
  53.  
  54. impl<B, I: FusedIterator, F> FusedIterator for MapWithSelf<I, F> where F: FnMut(&I, I::Item) -> B {}
  55.  
  56. pub trait MapWithSelfExt: Iterator {
  57. fn map_with_self<F, B>(self, f: F) -> MapWithSelf<Self, F>
  58. where
  59. Self: Sized,
  60. F: FnMut(&Self, Self::Item) -> B,
  61. {
  62. MapWithSelf { iter: self, f: f }
  63. }
  64. }
  65.  
  66. impl<I: Iterator> MapWithSelfExt for I {}
Add Comment
Please, Sign In to add comment