Skip to content

Commit

Permalink
Support the case when an element is popped while an iterator is alive
Browse files Browse the repository at this point in the history
  • Loading branch information
frankdavid committed Nov 24, 2024
1 parent 1662676 commit dc21034
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/base_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,10 @@ where
}

fn count(self) -> usize {
self.range.count()
min(self.vec.len(), self.range.end)
.saturating_sub(self.range.start)
.try_into()
.expect("Cannot express count as usize")
}

fn nth(&mut self, n: usize) -> Option<T> {
Expand Down
16 changes: 15 additions & 1 deletion src/vec/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,25 @@ fn test_iter() {
assert_eq!(sv.iter().skip(3).count(), 0);
assert_eq!(sv.iter().skip(4).count(), 0);
assert_eq!(sv.iter().skip(usize::MAX).count(), 0);
}

#[test]
fn test_iter_count() {
let sv = StableVec::<u64, M>::new(M::default()).unwrap();
sv.push(&1).unwrap();
sv.push(&2).unwrap();
sv.push(&3).unwrap();
sv.push(&4).unwrap();
{
let mut iter = sv.iter();
iter.next_back();
assert_eq!(iter.count(), 3);
}
{
assert_eq!(sv.len(), 3);
let mut iter = sv.iter();
iter.next_back();
sv.pop(); // this pops the element that we iterated through on the previous line
sv.pop();
assert_eq!(iter.count(), 2);
}
}
Expand Down

0 comments on commit dc21034

Please sign in to comment.