From 41807938d2fbc7928d75b1d68ac08899682168a2 Mon Sep 17 00:00:00 2001 From: The 8472 Date: Mon, 27 Mar 2023 14:56:14 +0200 Subject: [PATCH] fix advance_by impl for vec_deque and add tests --- .../src/collections/vec_deque/into_iter.rs | 14 +++++------ library/alloc/tests/vec_deque.rs | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/library/alloc/src/collections/vec_deque/into_iter.rs b/library/alloc/src/collections/vec_deque/into_iter.rs index c277c62ad14d9..e2b40f7912e0f 100644 --- a/library/alloc/src/collections/vec_deque/into_iter.rs +++ b/library/alloc/src/collections/vec_deque/into_iter.rs @@ -56,10 +56,10 @@ impl Iterator for IntoIter { #[inline] fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { - let rem = if self.inner.len < n { - let len = self.inner.len; + let len = self.inner.len; + let rem = if len < n { self.inner.clear(); - len - n + n - len } else { self.inner.drain(..n); 0 @@ -186,12 +186,12 @@ impl DoubleEndedIterator for IntoIter { #[inline] fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { let len = self.inner.len; - let rem = if len >= n { - self.inner.truncate(len - n); - 0 - } else { + let rem = if len < n { self.inner.clear(); n - len + } else { + self.inner.truncate(len - n); + 0 }; NonZeroUsize::new(rem).map_or(Ok(()), Err) } diff --git a/library/alloc/tests/vec_deque.rs b/library/alloc/tests/vec_deque.rs index 5a0b852e8d5e2..ddc27e34ed994 100644 --- a/library/alloc/tests/vec_deque.rs +++ b/library/alloc/tests/vec_deque.rs @@ -1,3 +1,4 @@ +use core::num::NonZeroUsize; use std::assert_matches::assert_matches; use std::collections::TryReserveErrorKind::*; use std::collections::{vec_deque::Drain, VecDeque}; @@ -426,6 +427,28 @@ fn test_into_iter() { assert_eq!(it.next(), Some(7)); assert_eq!(it.size_hint(), (5, Some(5))); } + + // advance_by + { + let mut d = VecDeque::new(); + for i in 0..=4 { + d.push_back(i); + } + for i in 6..=8 { + d.push_front(i); + } + + let mut it = d.into_iter(); + assert_eq!(it.advance_by(1), Ok(())); + assert_eq!(it.next(), Some(7)); + assert_eq!(it.advance_back_by(1), Ok(())); + assert_eq!(it.next_back(), Some(3)); + + let mut it = VecDeque::from(vec![1, 2, 3, 4, 5]).into_iter(); + assert_eq!(it.advance_by(10), Err(NonZeroUsize::new(5).unwrap())); + let mut it = VecDeque::from(vec![1, 2, 3, 4, 5]).into_iter(); + assert_eq!(it.advance_back_by(10), Err(NonZeroUsize::new(5).unwrap())); + } } #[test]