diff --git a/library/alloc/src/collections/vec_deque/iter.rs b/library/alloc/src/collections/vec_deque/iter.rs index e8290809276..5139db7f451 100644 --- a/library/alloc/src/collections/vec_deque/iter.rs +++ b/library/alloc/src/collections/vec_deque/iter.rs @@ -13,9 +13,15 @@ /// [`iter`]: super::VecDeque::iter #[stable(feature = "rust1", since = "1.0.0")] pub struct Iter<'a, T: 'a> { - pub(crate) ring: &'a [MaybeUninit], - pub(crate) tail: usize, - pub(crate) head: usize, + ring: &'a [MaybeUninit], + tail: usize, + head: usize, +} + +impl<'a, T> Iter<'a, T> { + pub(super) fn new(ring: &'a [MaybeUninit], tail: usize, head: usize) -> Self { + Iter { ring, tail, head } + } } #[stable(feature = "collection_debug", since = "1.17.0")] diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 63280e56332..e1e0276fc8d 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -1009,7 +1009,7 @@ pub fn allocator(&self) -> &A { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn iter(&self) -> Iter<'_, T> { - Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } } + Iter::new(unsafe { self.buffer_as_slice() }, self.tail, self.head) } /// Returns a front-to-back iterator that returns mutable references. @@ -1188,12 +1188,8 @@ pub fn range(&self, range: R) -> Iter<'_, T> R: RangeBounds, { let (tail, head) = self.range_tail_head(range); - Iter { - tail, - head, - // The shared reference we have in &self is maintained in the '_ of Iter. - ring: unsafe { self.buffer_as_slice() }, - } + // The shared reference we have in &self is maintained in the '_ of Iter. + Iter::new(unsafe { self.buffer_as_slice() }, tail, head) } /// Creates an iterator that covers the specified mutable range in the deque. @@ -1309,16 +1305,15 @@ pub fn drain(&mut self, range: R) -> Drain<'_, T, A> self.head = drain_tail; let deque = NonNull::from(&mut *self); - let iter = Iter { - tail: drain_tail, - head: drain_head, + unsafe { // Crucially, we only create shared references from `self` here and read from // it. We do not write to `self` nor reborrow to a mutable reference. // Hence the raw pointer we created above, for `deque`, remains valid. - ring: unsafe { self.buffer_as_slice() }, - }; + let ring = self.buffer_as_slice(); + let iter = Iter::new(ring, drain_tail, drain_head); - unsafe { Drain::new(drain_head, head, iter, deque) } + Drain::new(drain_head, head, iter, deque) + } } /// Clears the deque, removing all values.