Skip to content

Commit

Permalink
Implement AsRef<[T]> for std::slice::Iter.
Browse files Browse the repository at this point in the history
`AsRef` is designed for conversions that are "cheap" (as per
the API docs). It is the case that retrieving the underlying
data of `std::slice::Iter` is cheap. In my opinion, there's no
ambiguity about what slice data will be returned, otherwise,
I would be more cautious about implementing `AsRef`.
  • Loading branch information
frewsxcv committed Aug 16, 2016
1 parent e25542c commit 3808dc3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/libcollectionstest/slice.rs
Expand Up @@ -645,6 +645,15 @@ fn test_iter_size_hints() {
assert_eq!(xs.iter_mut().size_hint(), (5, Some(5)));
}

#[test]
fn test_iter_as_ref() {
let xs = [1, 2, 5, 10, 11];
let mut iter = xs.iter();
assert_eq!(iter.as_ref(), &[1, 2, 5, 10, 11]);
iter.next();
assert_eq!(iter.as_ref(), &[2, 5, 10, 11]);
}

#[test]
fn test_iter_clone() {
let xs = [1, 2, 5];
Expand Down
8 changes: 8 additions & 0 deletions src/libcore/slice.rs
Expand Up @@ -37,6 +37,7 @@ use clone::Clone;
use cmp::{Ordering, PartialEq, PartialOrd, Eq, Ord};
use cmp::Ordering::{Less, Equal, Greater};
use cmp;
use convert::AsRef;
use default::Default;
use fmt;
use intrinsics::assume;
Expand Down Expand Up @@ -996,6 +997,13 @@ impl<'a, T> Clone for Iter<'a, T> {
fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
}

#[stable(feature = "slice_iter_as_ref", since = "1.12.0")]
impl<'a, T> AsRef<[T]> for Iter<'a, T> {
fn as_ref(&self) -> &[T] {
self.as_slice()
}
}

/// Mutable slice iterator.
///
/// This struct is created by the [`iter_mut`] method on [slices].
Expand Down

0 comments on commit 3808dc3

Please sign in to comment.