Skip to content

Commit 967c0ad

Browse files
committed
Implement IterMut::as_mut_slice
1 parent e9b0d99 commit 967c0ad

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

library/core/src/slice/iter.rs

+48
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,47 @@ impl<'a, T> IterMut<'a, T> {
304304
pub fn as_slice(&self) -> &[T] {
305305
self.make_slice()
306306
}
307+
308+
/// Views the underlying data as a mutable subslice of the original data.
309+
///
310+
/// To avoid creating `&mut [T]` references that alias, the returned slice
311+
/// borrows its lifetime from the iterator the method is applied on.
312+
///
313+
/// # Examples
314+
///
315+
/// Basic usage:
316+
///
317+
/// ```
318+
/// # #![feature(slice_iter_mut_as_mut_slice)]
319+
///
320+
/// let mut slice: &mut [usize] = &mut [1, 2, 3];
321+
///
322+
/// // First, we get the iterator:
323+
/// let mut iter = slice.iter_mut();
324+
/// // Then, we get a mutable slice from it:
325+
/// let mut_slice = iter.as_mut_slice();
326+
/// // So if we check what the `as_mut_slice` method returned, we have "[1, 2, 3]":
327+
/// assert_eq!(mut_slice, &mut [1, 2, 3]);
328+
///
329+
/// // We can use it to mutate the slice:
330+
/// mut_slice[0] = 4;
331+
/// mut_slice[2] = 5;
332+
///
333+
/// // Next, we can move to the second element of the slice, checking that
334+
/// // it yields the value we just wrote:
335+
/// assert_eq!(iter.next(), Some(&mut 4));
336+
/// // Now `as_mut_slice` returns "[2, 5]":
337+
/// assert_eq!(iter.as_mut_slice(), &mut [2, 5]);
338+
/// ```
339+
#[must_use]
340+
// FIXME: Uncomment the `AsMut<[T]>` impl when this gets stabilized.
341+
#[unstable(feature = "slice_iter_mut_as_mut_slice", issue = "93079")]
342+
pub fn as_mut_slice(&mut self) -> &mut [T] {
343+
// SAFETY: the iterator was created from a mutable slice with pointer
344+
// `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
345+
// for `from_raw_parts_mut` are fulfilled.
346+
unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
347+
}
307348
}
308349

309350
#[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
@@ -313,6 +354,13 @@ impl<T> AsRef<[T]> for IterMut<'_, T> {
313354
}
314355
}
315356

357+
// #[stable(feature = "slice_iter_mut_as_mut_slice", since = "FIXME")]
358+
// impl<T> AsMut<[T]> for IterMut<'_, T> {
359+
// fn as_mut(&mut self) -> &mut [T] {
360+
// self.as_mut_slice()
361+
// }
362+
// }
363+
316364
iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
317365

318366
/// An internal abstraction over the splitting iterators, so that

0 commit comments

Comments
 (0)