Skip to content

Commit

Permalink
TrustedRandomAccess specialisation for Cloned.
Browse files Browse the repository at this point in the history
This verifies that TrustedRandomAccess has no side effects when the
iterator item implements Copy. This also implements TrustedLen and
TrustedRandomAccess for str::Bytes.
  • Loading branch information
clarfonthey committed Sep 23, 2017
1 parent 7f8aef9 commit 1c589b7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/libcore/iter/mod.rs
Expand Up @@ -488,7 +488,7 @@ impl<'a, I, T: 'a> FusedIterator for Cloned<I>
{}

#[doc(hidden)]
unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
default unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
where I: TrustedRandomAccess<Item=&'a T>, T: Clone
{
unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
Expand All @@ -499,6 +499,18 @@ unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
fn may_have_side_effect() -> bool { true }
}

#[doc(hidden)]
unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
where I: TrustedRandomAccess<Item=&'a T>, T: Copy
{
unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
*self.it.get_unchecked(i)
}

#[inline]
fn may_have_side_effect() -> bool { false }
}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
where I: TrustedLen<Item=&'a T>,
Expand Down
14 changes: 13 additions & 1 deletion src/libcore/str/mod.rs
Expand Up @@ -20,7 +20,8 @@ use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
use char;
use convert::TryFrom;
use fmt;
use iter::{Map, Cloned, FusedIterator};
use iter::{Map, Cloned, FusedIterator, TrustedLen};
use iter_private::TrustedRandomAccess;
use slice::{self, SliceIndex};
use mem;

Expand Down Expand Up @@ -818,6 +819,17 @@ impl<'a> ExactSizeIterator for Bytes<'a> {
#[unstable(feature = "fused", issue = "35602")]
impl<'a> FusedIterator for Bytes<'a> {}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<'a> TrustedLen for Bytes<'a> {}

#[doc(hidden)]
unsafe impl<'a> TrustedRandomAccess for Bytes<'a> {
unsafe fn get_unchecked(&mut self, i: usize) -> u8 {
self.0.get_unchecked(i)
}
fn may_have_side_effect() -> bool { false }
}

/// This macro generates a Clone impl for string pattern API
/// wrapper types of the form X<'a, P>
macro_rules! derive_pattern_clone {
Expand Down

0 comments on commit 1c589b7

Please sign in to comment.