diff --git a/src/base_vec.rs b/src/base_vec.rs index cc5b102f..707cb303 100644 --- a/src/base_vec.rs +++ b/src/base_vec.rs @@ -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 { diff --git a/src/vec/tests.rs b/src/vec/tests.rs index d91e9ed0..7895c94d 100644 --- a/src/vec/tests.rs +++ b/src/vec/tests.rs @@ -229,6 +229,27 @@ fn test_iter() { assert_eq!(sv.iter().skip(usize::MAX).count(), 0); } +#[test] +fn test_iter_count() { + let sv = StableVec::::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); + } + { + 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)]