about summary refs log tree commit diff
path: root/src/libcore/slice
diff options
context:
space:
mode:
authorJosh Stone <jistone@redhat.com>2019-03-04 15:12:45 -0800
committerJosh Stone <jistone@redhat.com>2019-03-04 15:12:45 -0800
commit538a0963ff4a55da47fcf2a1e14c62edab5af48d (patch)
tree4591fdc1ab918bebaef703d2b2b80237ab07c97a /src/libcore/slice
parenta9da8fc9c267c08cfdb8cf5b39da14f154d12939 (diff)
downloadrust-538a0963ff4a55da47fcf2a1e14c62edab5af48d.tar.gz
rust-538a0963ff4a55da47fcf2a1e14c62edab5af48d.zip
Add as_slice() to slice::IterMut and vec::Drain
In bluss/indexmap#88, we found that there was no easy way to implement
`Debug` for our `IterMut` and `Drain` iterators. Those are built on
`slice::IterMut` and `vec::Drain`, which implement `Debug` themselves,
but have no other way to access their data. With a new `as_slice()`
method, we can read the data and customize its presentation.
Diffstat (limited to 'src/libcore/slice')
-rw-r--r--src/libcore/slice/mod.rs32
1 files changed, 32 insertions, 0 deletions
diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs
index 2063f8ffaf6..b48101c23da 100644
--- a/src/libcore/slice/mod.rs
+++ b/src/libcore/slice/mod.rs
@@ -3288,6 +3288,38 @@ impl<'a, T> IterMut<'a, T> {
     pub fn into_slice(self) -> &'a mut [T] {
         unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
     }
+
+    /// Views the underlying data as a subslice of the original data.
+    ///
+    /// To avoid creating `&mut` references that alias, this has a
+    /// borrowed lifetime from the iterator.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// # #![feature(slice_iter_mut_as_slice)]
+    /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
+    /// // struct (&[usize here]):
+    /// let mut slice = &mut [1, 2, 3];
+    ///
+    /// // Then, we get the iterator:
+    /// let mut iter = slice.iter_mut();
+    /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
+    /// println!("{:?}", iter.as_slice());
+    /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
+    ///
+    /// // Next, we move to the second element of the slice:
+    /// iter.next();
+    /// // Now `as_slice` returns "[2, 3]":
+    /// println!("{:?}", iter.as_slice());
+    /// assert_eq!(iter.as_slice(), &[2, 3]);
+    /// ```
+    #[unstable(feature = "slice_iter_mut_as_slice", reason = "recently added", issue = "0")]
+    pub fn as_slice(&self) -> &[T] {
+        self.make_slice()
+    }
 }
 
 iterator!{struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}