Skip to content

Commit

Permalink
Auto merge of #182 - rklaehn:add-iter-as-slice, r=mbrubeck
Browse files Browse the repository at this point in the history
Add as_slice and as_mut_slice methods

To allow random access for remaining data in smallvec::IntoIter, just like
std::vec::IntoIter

Implements #181
  • Loading branch information
bors-servo committed Nov 16, 2019
2 parents 0afb664 + bd47300 commit c975415
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib.rs
Expand Up @@ -1553,6 +1553,20 @@ impl<A: Array> DoubleEndedIterator for IntoIter<A> {
impl<A: Array> ExactSizeIterator for IntoIter<A> {}
impl<A: Array> FusedIterator for IntoIter<A> {}

impl<A: Array> IntoIter<A> {
/// Returns the remaining items of this iterator as a slice.
pub fn as_slice(&self) -> &[A::Item] {
let len = self.end - self.current;
unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
}

/// Returns the remaining items of this iterator as a mutable slice.
pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
let len = self.end - self.current;
unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
}
}

impl<A: Array> IntoIterator for SmallVec<A> {
type IntoIter = IntoIter<A>;
type Item = A::Item;
Expand Down Expand Up @@ -2225,6 +2239,20 @@ mod tests {
assert_eq!(vec.into_iter().len(), 1);
}

#[test]
fn test_into_iter_as_slice() {
let vec = SmallVec::<[u32; 2]>::from(&[1, 2, 3][..]);
let mut iter = vec.clone().into_iter();
assert_eq!(iter.as_slice(), &[1, 2, 3]);
assert_eq!(iter.as_mut_slice(), &[1, 2, 3]);
iter.next();
assert_eq!(iter.as_slice(), &[2, 3]);
assert_eq!(iter.as_mut_slice(), &[2, 3]);
iter.next_back();
assert_eq!(iter.as_slice(), &[2]);
assert_eq!(iter.as_mut_slice(), &[2]);
}

#[test]
fn shrink_to_fit_unspill() {
let mut vec = SmallVec::<[u8; 2]>::from_iter(0..3);
Expand Down

0 comments on commit c975415

Please sign in to comment.