Auto merge of #87387 - the8472:slice-iter-advance_by, r=scottmcm

Implement advance_by, advance_back_by for slice::{Iter, IterMut}

Part of #77404.

Picking up where #77633 was closed.

I have addressed https://github.com/rust-lang/rust/pull/77633#issuecomment-771842599 by restoring `nth` and `nth_back`. So according to that comment this should already be r=m-ou-se, but it has been sitting for a while.
This commit is contained in:
bors 2021-07-31 05:22:13 +00:00
commit 6b0b07d41f
2 changed files with 57 additions and 0 deletions

View File

@ -185,6 +185,13 @@ macro_rules! iterator {
}
}
fn advance_by(&mut self, n: usize) -> Result<(), usize> {
let advance = cmp::min(n, len!(self));
// SAFETY: By construction, `advance` does not exceed `self.len()`.
unsafe { self.post_inc_start(advance as isize) };
if advance == n { Ok(()) } else { Err(advance) }
}
#[inline]
fn last(mut self) -> Option<$elem> {
self.next_back()
@ -371,6 +378,14 @@ macro_rules! iterator {
Some(next_back_unchecked!(self))
}
}
#[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), usize> {
let advance = cmp::min(n, len!(self));
// SAFETY: By construction, `advance` does not exceed `self.len()`.
unsafe { self.pre_dec_end(advance as isize) };
if advance == n { Ok(()) } else { Err(advance) }
}
}
#[stable(feature = "fused", since = "1.26.0")]

View File

@ -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];