alloc/vec/
peek_mut.rs

1use core::ops::{Deref, DerefMut};
2
3use super::Vec;
4use crate::fmt;
5
6/// Structure wrapping a mutable reference to the last item in a
7/// `Vec`.
8///
9/// This `struct` is created by the [`peek_mut`] method on [`Vec`]. See
10/// its documentation for more.
11///
12/// [`peek_mut`]: Vec::peek_mut
13#[unstable(feature = "vec_peek_mut", issue = "122742")]
14pub struct PeekMut<'a, T> {
15    vec: &'a mut Vec<T>,
16}
17
18#[unstable(feature = "vec_peek_mut", issue = "122742")]
19impl<T: fmt::Debug> fmt::Debug for PeekMut<'_, T> {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        f.debug_tuple("PeekMut").field(self.deref()).finish()
22    }
23}
24
25impl<'a, T> PeekMut<'a, T> {
26    pub(crate) fn new(vec: &'a mut Vec<T>) -> Option<Self> {
27        if vec.is_empty() { None } else { Some(Self { vec }) }
28    }
29
30    /// Removes the peeked value from the vector and returns it.
31    #[unstable(feature = "vec_peek_mut", issue = "122742")]
32    pub fn pop(self) -> T {
33        // SAFETY: PeekMut is only constructed if the vec is non-empty
34        unsafe { self.vec.pop().unwrap_unchecked() }
35    }
36}
37
38#[unstable(feature = "vec_peek_mut", issue = "122742")]
39impl<'a, T> Deref for PeekMut<'a, T> {
40    type Target = T;
41
42    fn deref(&self) -> &Self::Target {
43        // SAFETY: PeekMut is only constructed if the vec is non-empty
44        unsafe { self.vec.get_unchecked(self.vec.len() - 1) }
45    }
46}
47
48#[unstable(feature = "vec_peek_mut", issue = "122742")]
49impl<'a, T> DerefMut for PeekMut<'a, T> {
50    fn deref_mut(&mut self) -> &mut Self::Target {
51        let idx = self.vec.len() - 1;
52        // SAFETY: PeekMut is only constructed if the vec is non-empty
53        unsafe { self.vec.get_unchecked_mut(idx) }
54    }
55}