Auto merge of #92287 - JulianKnodt:slice_remainder, r=yaahc

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
This commit is contained in:
bors 2022-04-18 23:34:24 +00:00
commit d5ae66c12c
3 changed files with 27 additions and 0 deletions

View file

@ -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")]

View file

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

View file

@ -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() {