Skip to content

Commit 08a1dd2

Browse files
committed
implement TrustedRandomAccess for array::IntoIter
1 parent 895d7a9 commit 08a1dd2

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

library/core/src/array/iter.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use crate::{
44
fmt,
5-
iter::{ExactSizeIterator, FusedIterator, TrustedLen},
5+
iter::{ExactSizeIterator, FusedIterator, TrustedLen, TrustedRandomAccess},
66
mem::{self, MaybeUninit},
77
ops::Range,
88
ptr,
@@ -130,6 +130,18 @@ impl<T, const N: usize> Iterator for IntoIter<T, N> {
130130
fn last(mut self) -> Option<Self::Item> {
131131
self.next_back()
132132
}
133+
134+
#[inline]
135+
unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item
136+
where
137+
Self: TrustedRandomAccess,
138+
{
139+
// SAFETY: Callers are only allowed to pass an index that is in bounds
140+
// Additionally Self: TrustedRandomAccess is only implemented for T: Copy which means even
141+
// multiple repeated reads of the same index would be safe and the
142+
// values aree !Drop, thus won't suffer from double drops.
143+
unsafe { self.data.get_unchecked(self.alive.start + idx).assume_init_read() }
144+
}
133145
}
134146

135147
#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
@@ -184,6 +196,17 @@ impl<T, const N: usize> FusedIterator for IntoIter<T, N> {}
184196
#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
185197
unsafe impl<T, const N: usize> TrustedLen for IntoIter<T, N> {}
186198

199+
#[doc(hidden)]
200+
#[unstable(feature = "trusted_random_access", issue = "none")]
201+
// T: Copy as approximation for !Drop since get_unchecked does not update the pointers
202+
// and thus we can't implement drop-handling
203+
unsafe impl<T, const N: usize> TrustedRandomAccess for IntoIter<T, N>
204+
where
205+
T: Copy,
206+
{
207+
const MAY_HAVE_SIDE_EFFECT: bool = false;
208+
}
209+
187210
#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
188211
impl<T: Clone, const N: usize> Clone for IntoIter<T, N> {
189212
fn clone(&self) -> Self {

0 commit comments

Comments
 (0)