Skip to content

Commit d5ae66c

Browse files
committed
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
2 parents 311e268 + 494901c commit d5ae66c

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

library/core/src/slice/iter.rs

+14
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,20 @@ impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {
358358
pub(super) fn new(slice: &'a [T], pred: P) -> Self {
359359
Self { v: slice, pred, finished: false }
360360
}
361+
/// Returns a slice which contains items not yet handled by split.
362+
/// # Example
363+
///
364+
/// ```
365+
/// #![feature(split_as_slice)]
366+
/// let slice = [1,2,3,4,5];
367+
/// let mut split = slice.split(|v| v % 2 == 0);
368+
/// assert!(split.next().is_some());
369+
/// assert_eq!(split.as_slice(), &[3,4,5]);
370+
/// ```
371+
#[unstable(feature = "split_as_slice", issue = "96137")]
372+
pub fn as_slice(&self) -> &'a [T] {
373+
if self.finished { &[] } else { &self.v }
374+
}
361375
}
362376

363377
#[stable(feature = "core_impl_debug", since = "1.9.0")]

library/core/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
#![feature(sort_internals)]
4747
#![feature(slice_take)]
4848
#![feature(slice_from_ptr_range)]
49+
#![feature(split_as_slice)]
4950
#![feature(maybe_uninit_uninit_array)]
5051
#![feature(maybe_uninit_array_assume_init)]
5152
#![feature(maybe_uninit_write_slice)]

library/core/tests/slice.rs

+12
Original file line numberDiff line numberDiff line change
@@ -2339,6 +2339,18 @@ fn slice_rsplit_array_mut() {
23392339
}
23402340
}
23412341

2342+
#[test]
2343+
fn split_as_slice() {
2344+
let arr = [1, 2, 3, 4, 5, 6];
2345+
let mut split = arr.split(|v| v % 2 == 0);
2346+
assert_eq!(split.as_slice(), &[1, 2, 3, 4, 5, 6]);
2347+
assert!(split.next().is_some());
2348+
assert_eq!(split.as_slice(), &[3, 4, 5, 6]);
2349+
assert!(split.next().is_some());
2350+
assert!(split.next().is_some());
2351+
assert_eq!(split.as_slice(), &[]);
2352+
}
2353+
23422354
#[should_panic]
23432355
#[test]
23442356
fn slice_split_array_ref_out_of_bounds() {

0 commit comments

Comments
 (0)