Skip to content

Commit c975415

Browse files
author
bors-servo
authored
Auto merge of #182 - rklaehn:add-iter-as-slice, r=mbrubeck
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
2 parents 0afb664 + bd47300 commit c975415

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

lib.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1553,6 +1553,20 @@ impl<A: Array> DoubleEndedIterator for IntoIter<A> {
15531553
impl<A: Array> ExactSizeIterator for IntoIter<A> {}
15541554
impl<A: Array> FusedIterator for IntoIter<A> {}
15551555

1556+
impl<A: Array> IntoIter<A> {
1557+
/// Returns the remaining items of this iterator as a slice.
1558+
pub fn as_slice(&self) -> &[A::Item] {
1559+
let len = self.end - self.current;
1560+
unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
1561+
}
1562+
1563+
/// Returns the remaining items of this iterator as a mutable slice.
1564+
pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1565+
let len = self.end - self.current;
1566+
unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
1567+
}
1568+
}
1569+
15561570
impl<A: Array> IntoIterator for SmallVec<A> {
15571571
type IntoIter = IntoIter<A>;
15581572
type Item = A::Item;
@@ -2225,6 +2239,20 @@ mod tests {
22252239
assert_eq!(vec.into_iter().len(), 1);
22262240
}
22272241

2242+
#[test]
2243+
fn test_into_iter_as_slice() {
2244+
let vec = SmallVec::<[u32; 2]>::from(&[1, 2, 3][..]);
2245+
let mut iter = vec.clone().into_iter();
2246+
assert_eq!(iter.as_slice(), &[1, 2, 3]);
2247+
assert_eq!(iter.as_mut_slice(), &[1, 2, 3]);
2248+
iter.next();
2249+
assert_eq!(iter.as_slice(), &[2, 3]);
2250+
assert_eq!(iter.as_mut_slice(), &[2, 3]);
2251+
iter.next_back();
2252+
assert_eq!(iter.as_slice(), &[2]);
2253+
assert_eq!(iter.as_mut_slice(), &[2]);
2254+
}
2255+
22282256
#[test]
22292257
fn shrink_to_fit_unspill() {
22302258
let mut vec = SmallVec::<[u8; 2]>::from_iter(0..3);

0 commit comments

Comments
 (0)