]> git.lizzy.rs Git - rust.git/commitdiff
Implement `AsRef<[T]>` for `std::slice::Iter`.
authorCorey Farwell <coreyf@rwell.org>
Wed, 10 Aug 2016 00:49:41 +0000 (20:49 -0400)
committerCorey Farwell <coreyf@rwell.org>
Tue, 16 Aug 2016 15:14:52 +0000 (11:14 -0400)
`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`.

src/libcollectionstest/slice.rs
src/libcore/slice.rs

index 71416f2069fa0976d5042d11d9e67f0f110261be..cb3579f0680f8ecc22a664eed97a76bd3388cca9 100644 (file)
@@ -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];
index 3141c289e931ce0b5e001213edec511ca0dbe996..3a820a14f1214aa8424a0222cf6b3885c6f3163f 100644 (file)
@@ -37,6 +37,7 @@
 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;
@@ -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].