| 1 | use core::ops::{Deref, DerefMut}; |
| 2 | |
| 3 | use super::Vec; |
| 4 | use crate::alloc::{Allocator, Global}; |
| 5 | use 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" )] |
| 15 | pub 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" )] |
| 24 | impl<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 | |
| 30 | impl<'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" )] |
| 44 | impl<'a, T, A: Allocator> Deref for PeekMut<'a, T, A> { |
| 45 | type Target = T; |
| 46 | |
| 47 | fn deref(&self) -> &Self::Target { |
| 48 | let idx: usize = 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" )] |
| 55 | impl<'a, T, A: Allocator> DerefMut for PeekMut<'a, T, A> { |
| 56 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 57 | let idx: usize = 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 | } |
| 62 | |