diff --git a/library/core/src/slice/iter/macros.rs b/library/core/src/slice/iter/macros.rs index 04945fa0e82..5434827e5dd 100644 --- a/library/core/src/slice/iter/macros.rs +++ b/library/core/src/slice/iter/macros.rs @@ -188,7 +188,7 @@ macro_rules! iterator { #[inline] fn advance_by(&mut self, n: usize) -> Result<(), usize>{ let advance = cmp::min(n, len!(self)); - // SAFETY: `advance` does not exceed `self.len()` by construction + // SAFETY: By construction, `advance` does not exceed `self.len()`. unsafe { self.post_inc_start(advance as isize) }; if advance == n { Ok(()) } else { Err(advance) } } @@ -383,7 +383,7 @@ macro_rules! iterator { #[inline] fn advance_back_by(&mut self, n: usize) -> Result<(), usize> { let advance = cmp::min(n, len!(self)); - // SAFETY: `advance` does not exceed `self.len()` by construction + // SAFETY: By construction, `advance` does not exceed `self.len()`. unsafe { self.pre_dec_end(advance as isize) }; if advance == n { Ok(()) } else { Err(advance) } } diff --git a/library/core/tests/slice.rs b/library/core/tests/slice.rs index 3a98cd9d2ee..240b894057c 100644 --- a/library/core/tests/slice.rs +++ b/library/core/tests/slice.rs @@ -134,6 +134,48 @@ fn test_partition_point() { assert_eq!(b.partition_point(|&x| x < 8), 5); } +#[test] +fn test_iterator_advance_by() { + let v = &[0, 1, 2, 3, 4]; + + for i in 0..=v.len() { + let mut iter = v.iter(); + iter.advance_by(i).unwrap(); + assert_eq!(iter.as_slice(), &v[i..]); + } + + let mut iter = v.iter(); + assert_eq!(iter.advance_by(v.len() + 1), Err(v.len())); + assert_eq!(iter.as_slice(), &[]); + + let mut iter = v.iter(); + iter.advance_by(3).unwrap(); + assert_eq!(iter.as_slice(), &v[3..]); + iter.advance_by(2).unwrap(); + assert_eq!(iter.as_slice(), &[]); +} + +#[test] +fn test_iterator_advance_back_by() { + let v = &[0, 1, 2, 3, 4]; + + for i in 0..=v.len() { + let mut iter = v.iter(); + iter.advance_back_by(i).unwrap(); + assert_eq!(iter.as_slice(), &v[..v.len() - i]); + } + + let mut iter = v.iter(); + assert_eq!(iter.advance_back_by(v.len() + 1), Err(v.len())); + assert_eq!(iter.as_slice(), &[]); + + let mut iter = v.iter(); + iter.advance_back_by(3).unwrap(); + assert_eq!(iter.as_slice(), &v[..v.len() - 3]); + iter.advance_back_by(2).unwrap(); + assert_eq!(iter.as_slice(), &[]); +} + #[test] fn test_iterator_nth() { let v: &[_] = &[0, 1, 2, 3, 4];