implement `IntoIterator` for `Vec` (#337)

pull/346/head
Kirin 3 years ago committed by GitHub
parent 7ea147e4f6
commit e64ea939f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -82,8 +82,10 @@ impl<T> Drop for IntoIter<T> {
} }
} }
impl<T> Vec<T> { impl<T> IntoIterator for Vec<T> {
pub fn into_iter(self) -> IntoIter<T> { type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
unsafe { unsafe {
let iter = RawValIter::new(&self); let iter = RawValIter::new(&self);

@ -158,19 +158,6 @@ impl<T> Vec<T> {
} }
} }
pub fn into_iter(self) -> IntoIter<T> {
unsafe {
let iter = RawValIter::new(&self);
let buf = ptr::read(&self.buf);
mem::forget(self);
IntoIter {
iter: iter,
_buf: buf,
}
}
}
pub fn drain(&mut self) -> Drain<T> { pub fn drain(&mut self) -> Drain<T> {
unsafe { unsafe {
let iter = RawValIter::new(&self); let iter = RawValIter::new(&self);
@ -208,6 +195,23 @@ impl<T> DerefMut for Vec<T> {
} }
} }
impl<T> IntoIterator for Vec<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
unsafe {
let iter = RawValIter::new(&self);
let buf = ptr::read(&self.buf);
mem::forget(self);
IntoIter {
iter: iter,
_buf: buf,
}
}
}
}
struct RawValIter<T> { struct RawValIter<T> {
start: *const T, start: *const T,
end: *const T, end: *const T,

@ -57,8 +57,10 @@ And this is what we end up with for initialization:
<!-- ignore: simplified code --> <!-- ignore: simplified code -->
```rust,ignore ```rust,ignore
impl<T> Vec<T> { impl<T> IntoIterator for Vec<T> {
pub fn into_iter(self) -> IntoIter<T> { type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
// Can't destructure Vec since it's Drop // Can't destructure Vec since it's Drop
let ptr = self.ptr; let ptr = self.ptr;
let cap = self.cap; let cap = self.cap;

@ -134,8 +134,10 @@ impl<T> Drop for IntoIter<T> {
} }
} }
impl<T> Vec<T> { impl<T> IntoIterator for Vec<T> {
pub fn into_iter(self) -> IntoIter<T> { type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
unsafe { unsafe {
// need to use ptr::read to unsafely move the buf out since it's // need to use ptr::read to unsafely move the buf out since it's
// not Copy, and Vec implements Drop (so we can't destructure it). // not Copy, and Vec implements Drop (so we can't destructure it).

Loading…
Cancel
Save