Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add as_slice and as_mut_slice methods #182

Merged
merged 1 commit into from Nov 16, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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