Skip to content

Commit

Permalink
Rollup merge of rust-lang#83990 - the8472:take-trusted-len, r=dtolnay
Browse files Browse the repository at this point in the history
implement `TrustedRandomAccess` for `Take` iterator adapter

`TrustedRandomAccess` requires the iterator length to fit within `usize`. `take(n)` only constrains the upper bound of an iterator. So if the inner is `TrustedRandomAccess` (which already implies a finite length) then so can be `Take`.

````@rustbot```` label T-libs-impl
  • Loading branch information
Dylan-DPC authored Apr 22, 2021
2 parents b6dbf13 + 37a5b51 commit 151c0ed
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion library/core/src/iter/adapters/take.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use crate::cmp;
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen};
use crate::iter::{
adapters::zip::try_get_unchecked, adapters::SourceIter, FusedIterator, InPlaceIterable,
TrustedLen, TrustedRandomAccess,
};
use crate::ops::{ControlFlow, Try};

/// An iterator that only iterates over the first `n` iterations of `iter`.
Expand Down Expand Up @@ -111,6 +114,15 @@ where

self.try_fold(init, ok(fold)).unwrap()
}

unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> <I as Iterator>::Item
where
Self: TrustedRandomAccess,
{
// SAFETY: the caller must uphold the contract for
// `Iterator::__iterator_get_unchecked`.
unsafe { try_get_unchecked(&mut self.iter, idx) }
}
}

#[unstable(issue = "none", feature = "inplace_iteration")]
Expand Down Expand Up @@ -207,3 +219,12 @@ impl<I> FusedIterator for Take<I> where I: FusedIterator {}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<I: TrustedLen> TrustedLen for Take<I> {}

#[doc(hidden)]
#[unstable(feature = "trusted_random_access", issue = "none")]
unsafe impl<I> TrustedRandomAccess for Take<I>
where
I: TrustedRandomAccess,
{
const MAY_HAVE_SIDE_EFFECT: bool = I::MAY_HAVE_SIDE_EFFECT;
}

0 comments on commit 151c0ed

Please sign in to comment.