]> git.lizzy.rs Git - rust.git/commitdiff
Add slice::remainder
authorkadmin <julianknodt@gmail.com>
Sun, 26 Dec 2021 08:45:33 +0000 (08:45 +0000)
committerkadmin <julianknodt@gmail.com>
Sun, 17 Apr 2022 17:19:45 +0000 (17:19 +0000)
This adds a remainder function to the Slice iterator, so that a caller can access unused
elements if iteration stops.

library/core/src/slice/iter.rs
library/core/tests/lib.rs
library/core/tests/slice.rs

index 22662f7d18d07da1bb1d533a1e0d73711fa43c1b..98dd1521d0e85bea969b63d583f976bd74a023ee 100644 (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")]
index 447a6fcf7567e5c4242676c32fe0a4d6a3f7bae8..485fa305c00e19834cc3f4b590f08fdc15615607 100644 (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)]
index ada479147db95806c3e638a9ecc36687d91bba9c..872786ed1bd8083427ef1b4f2f3719e5a51947ca 100644 (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() {