Improve performance characteristics of Vector iterators to better match Vec iterators - #104
Improve performance characteristics of Vector iterators to better match Vec iterators#104jessegrosjean wants to merge 2 commits into
Conversation
timotree3
left a comment
There was a problem hiding this comment.
Just passing by and I noticed what I believe to be multiple bugs in this implementation. All my comments apply to both the Iterator and DoubleEndedIterator implementations for all the mutability variants.
| if n >= self.len() { | ||
| None | ||
| } else { | ||
| self.front_index += n; |
|
|
||
| fn nth(&mut self, n: usize) -> Option<Self::Item> { | ||
| if n >= self.len() { | ||
| None |
There was a problem hiding this comment.
I don't believe this shortcut is correct. It introduces a bug.
Before this change, this works:
let vec = vector![1, 2, 3];
let mut iter = vec.iter();
assert_eq!(iter.nth(3), None);
assert_eq!(iter.next(), None);Afterwards, it panics because the call to next() returns Some(1).
Since the implementation of next() already has a check for exhaustion, I would remove this if altogether and replace it with its else case.
| impl<'a, A: Clone> ExactSizeIterator for Iter<'a, A> {} | ||
| impl<'a, A: Clone> ExactSizeIterator for Iter<'a, A> { | ||
| fn len(&self) -> usize { | ||
| self.back_index - self.front_index |
There was a problem hiding this comment.
What if this underflows?
| self.back_index - self.front_index | |
| self.back_index.saturating_sub(self.front_index) |
| impl<'a, A: Clone> ExactSizeIterator for IterMut<'a, A> {} | ||
| impl<'a, A: Clone> ExactSizeIterator for IterMut<'a, A> { | ||
| fn len(&self) -> usize { | ||
| self.back_index - self.front_index |
There was a problem hiding this comment.
| self.back_index - self.front_index | |
| self.back_index.saturing_sub(self.front_index) |
|
|
||
| impl<'a, A: Clone> ExactSizeIterator for Chunks<'a, A> { | ||
| fn len(&self) -> usize { | ||
| self.back_index - self.front_index |
There was a problem hiding this comment.
| self.back_index - self.front_index | |
| self.back_index.saturing_sub(self.front_index) |
|
|
||
| impl<'a, A: Clone> ExactSizeIterator for ChunksMut<'a, A> { | ||
| fn len(&self) -> usize { | ||
| self.back_index - self.front_index |
There was a problem hiding this comment.
| self.back_index - self.front_index | |
| self.back_index.saturing_sub(self.front_index) |
In particular provided implementations of
len,count,nth, andnth_backforIter,IterMut,Chunks,ChunksMutthat make use offront_indexandback_indexto improve performance.Similar work might also be useful for
ConsumingIter, but I couldn't easily trace that code to see where/if such improvements would make sense.