about summary refs log tree commit diff
diff options
context:
space:
mode:
author@amit.chandra <@amit.chandra>2019-05-31 15:09:17 +0530
committerwizAmit <amitforfriends_dns@yahoo.com>2019-06-23 12:45:59 +0530
commitb95bde44913852685b350d468d000453ece9696f (patch)
tree2cf63c90f3f4bd7fa5971101ed6f1e22b4d5ea6b
parenta96ba969156d257e5d5b692946fa8fe40ed6543a (diff)
downloadrust-b95bde44913852685b350d468d000453ece9696f.tar.gz
rust-b95bde44913852685b350d468d000453ece9696f.zip
squash of all commits for nth_back on ChunksMut
wip nth_back for chunks_mut

working chunksmut

fixed nth_back for chunksmut

Signed-off-by: wizAmit <amitforfriends_dns@yahoo.com>
-rw-r--r--src/libcore/slice/mod.rs19
-rw-r--r--src/libcore/tests/slice.rs22
2 files changed, 41 insertions, 0 deletions
diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs
index c6d44324ef5..e7d175c44c9 100644
--- a/src/libcore/slice/mod.rs
+++ b/src/libcore/slice/mod.rs
@@ -4330,6 +4330,25 @@ impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
             Some(tail)
         }
     }
+
+    #[inline]
+    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
+        let len = self.len();
+        if n >= len {
+            self.v = &mut [];
+            None
+        } else {
+            let start = (len - 1 - n) * self.chunk_size;
+            let end = match start.checked_add(self.chunk_size) {
+                Some(res) => cmp::min(res, self.v.len()),
+                None => self.v.len(),
+            };
+            let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
+            let (head, nth_back) = temp.split_at_mut(start);
+            self.v = head;
+            Some(nth_back)
+        }
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs
index 03e65d2fe0b..0519e579c98 100644
--- a/src/libcore/tests/slice.rs
+++ b/src/libcore/tests/slice.rs
@@ -223,6 +223,28 @@ fn test_chunks_mut_nth() {
 }
 
 #[test]
+fn test_chunks_mut_nth_back() {
+    let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5];
+    let mut c = v.chunks_mut(2);
+    assert_eq!(c.nth_back(1).unwrap(), &[2, 3]);
+    assert_eq!(c.next().unwrap(), &[0, 1]);
+
+    let v1: &mut [i32] = &mut [0, 1, 2, 3, 4];
+    let mut c1 = v1.chunks_mut(3);
+    assert_eq!(c1.nth_back(1).unwrap(), &[0, 1, 2]);
+    assert_eq!(c1.next(), None);
+
+    let v3: &mut [i32] = &mut [0, 1, 2, 3, 4];
+    let mut c3 = v3.chunks_mut(10);
+    assert_eq!(c3.nth_back(0).unwrap(), &[0, 1, 2, 3, 4]);
+    assert_eq!(c3.next(), None);
+
+    let v4: &mut [i32] = &mut [0, 1, 2];
+    let mut c4 = v4.chunks_mut(10);
+    assert_eq!(c4.nth_back(1_000_000_000usize), None);
+}
+
+#[test]
 fn test_chunks_mut_last() {
     let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5];
     let c = v.chunks_mut(2);