Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix Vec Iter::count() after next_back() #250

Merged
merged 2 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions src/base_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,11 +379,10 @@ where
}

fn count(self) -> usize {
let n = self.vec.len().saturating_sub(self.range.start);
if n > usize::MAX as u64 {
panic!("The number of items in the vec {n} does not fit into usize");
}
n as usize
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
21 changes: 21 additions & 0 deletions src/vec/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,27 @@ fn test_iter() {
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);
frankdavid marked this conversation as resolved.
Show resolved Hide resolved
}
{
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);
}
}

// A struct with a bugg implementation of storable where the max_size can
// smaller than the serialized size.
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq)]
Expand Down