Fix size_hint for Vector iterators to return remaining length correctly
MODIFY
src/manual/core/vector.rs
src/manual/core/vector.rs
@@ -153,26 +153,6 @@ impl<T: VectorElement> Drop for Vector<T> where Self: VectorExtern<T> {
}
}
-impl<T: VectorElement> IntoIterator for Vector<T> where Vector<T>: VectorExtern<T> {
- type Item = T;
- type IntoIter = VectorIterator<T>;
-
- #[inline]
- fn into_iter(self) -> Self::IntoIter {
- Self::IntoIter::new(self)
- }
-}
-
-impl<'i, T: VectorElement> IntoIterator for &'i Vector<T> where Vector<T>: VectorExtern<T> {
- type Item = T;
- type IntoIter = VectorRefIterator<'i, T>;
-
- #[inline]
- fn into_iter(self) -> Self::IntoIter {
- self.iter()
- }
-}
-
/// Common interface for all C++ vector types generated by the crate
///
/// You'll need to import this trait to use any of the C++ vector wrappers, usually imported as

MODIFY
src/manual/core/vector/iter.rs
src/manual/core/vector/iter.rs
@@ -4,6 +4,26 @@ use libc::size_t;
use crate::core::{Vector, VectorElement, VectorExtern};
+impl<T: VectorElement> IntoIterator for Vector<T> where Vector<T>: VectorExtern<T> {
+ type Item = T;
+ type IntoIter = VectorIterator<T>;
+
+ #[inline]
+ fn into_iter(self) -> VectorIterator<T> {
+ Self::IntoIter::new(self)
+ }
+}
+
+impl<'i, T: VectorElement> IntoIterator for &'i Vector<T> where Vector<T>: VectorExtern<T> {
+ type Item = T;
+ type IntoIter = VectorRefIterator<'i, T>;
+
+ #[inline]
+ fn into_iter(self) -> VectorRefIterator<'i, T> {
+ self.iter()
+ }
+}
+
pub struct VectorIterator<T: VectorElement> where Vector<T>: VectorExtern<T> {
vec: Vector<T>,
i: size_t,
@@ -25,7 +45,7 @@ impl<T: VectorElement> Iterator for VectorIterator<T> where Vector<T>: VectorExt
}
fn size_hint(&self) -> (usize, Option<usize>) {
- let len = self.vec.len();
+ let len = self.vec.len() - self.i;
(len, Some(len))
}
@@ -59,7 +79,7 @@ impl<T: VectorElement> Iterator for VectorRefIterator<'_, T> where Vector<T>: Ve
}
fn size_hint(&self) -> (usize, Option<usize>) {
- let len = self.vec.len();
+ let len = self.vec.len() - self.i;
(len, Some(len))
}

MODIFY
tests/vector.rs
tests/vector.rs
@@ -382,6 +382,30 @@ fn iter() -> Result<()> {
}
}
+ {
+ let vec = VectorOfi32::from_iter(vec![1, 2, 3, 4]);
+ let mut vec_iter = vec.into_iter();
+ let mut len = vec_iter.len();
+ assert_eq!(4, len);
+ while let Some(..) = vec_iter.next() {
+ len -= 1;
+ assert_eq!(len, vec_iter.len());
+ assert_eq!((len, Some(len)), vec_iter.size_hint());
+ }
+ }
+
+ {
+ let vec = VectorOfi32::from_iter(vec![1, 2, 3, 4]);
+ let mut vec_iter = vec.iter();
+ let mut len = vec_iter.len();
+ assert_eq!(4, len);
+ while let Some(..) = vec_iter.next() {
+ len -= 1;
+ assert_eq!(len, vec_iter.len());
+ assert_eq!((len, Some(len)), vec_iter.size_hint());
+ }
+ }
+
Ok(())
}

Fix size_hint for Vector iterators to return remaining length correctly