Skip to content

Commit

Permalink
Auto merge of #92287 - JulianKnodt:slice_remainder, r=yaahc
Browse files Browse the repository at this point in the history
Add slice::remainder

This adds a remainder function to the Slice iterator, so that a caller can access unused
elements if iteration stops.

Addresses #91733
  • Loading branch information
bors committed Apr 18, 2022
2 parents 311e268 + 494901c commit d5ae66c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions library/core/src/slice/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,20 @@ impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {
pub(super) fn new(slice: &'a [T], pred: P) -> Self {
Self { v: slice, pred, finished: false }
}
/// Returns a slice which contains items not yet handled by split.
/// # Example
///
/// ```
/// #![feature(split_as_slice)]
/// let slice = [1,2,3,4,5];
/// let mut split = slice.split(|v| v % 2 == 0);
/// assert!(split.next().is_some());
/// assert_eq!(split.as_slice(), &[3,4,5]);
/// ```
#[unstable(feature = "split_as_slice", issue = "96137")]
pub fn as_slice(&self) -> &'a [T] {
if self.finished { &[] } else { &self.v }
}
}

#[stable(feature = "core_impl_debug", since = "1.9.0")]
Expand Down
1 change: 1 addition & 0 deletions library/core/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
#![feature(sort_internals)]
#![feature(slice_take)]
#![feature(slice_from_ptr_range)]
#![feature(split_as_slice)]
#![feature(maybe_uninit_uninit_array)]
#![feature(maybe_uninit_array_assume_init)]
#![feature(maybe_uninit_write_slice)]
Expand Down
12 changes: 12 additions & 0 deletions library/core/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2339,6 +2339,18 @@ fn slice_rsplit_array_mut() {
}
}

#[test]
fn split_as_slice() {
let arr = [1, 2, 3, 4, 5, 6];
let mut split = arr.split(|v| v % 2 == 0);
assert_eq!(split.as_slice(), &[1, 2, 3, 4, 5, 6]);
assert!(split.next().is_some());
assert_eq!(split.as_slice(), &[3, 4, 5, 6]);
assert!(split.next().is_some());
assert!(split.next().is_some());
assert_eq!(split.as_slice(), &[]);
}

#[should_panic]
#[test]
fn slice_split_array_ref_out_of_bounds() {
Expand Down

0 comments on commit d5ae66c

Please sign in to comment.