alloc/vec/
peek_mut.rs

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