From e64ea939f0d7aa3fd9ae28abece59d196f6ebe43 Mon Sep 17 00:00:00 2001 From: Kirin <1370302499@qq.com> Date: Fri, 18 Mar 2022 04:46:17 +0800 Subject: [PATCH] implement `IntoIterator` for `Vec` (#337) --- src/vec/vec-drain.md | 6 ++++-- src/vec/vec-final.md | 30 +++++++++++++++++------------- src/vec/vec-into-iter.md | 6 ++++-- src/vec/vec-raw.md | 6 ++++-- 4 files changed, 29 insertions(+), 19 deletions(-) diff --git a/src/vec/vec-drain.md b/src/vec/vec-drain.md index fbc8edd..7a0e7f8 100644 --- a/src/vec/vec-drain.md +++ b/src/vec/vec-drain.md @@ -82,8 +82,10 @@ impl Drop for IntoIter { } } -impl Vec { - pub fn into_iter(self) -> IntoIter { +impl IntoIterator for Vec { + type Item = T; + type IntoIter = IntoIter; + fn into_iter(self) -> IntoIter { unsafe { let iter = RawValIter::new(&self); diff --git a/src/vec/vec-final.md b/src/vec/vec-final.md index 786cfab..f4cd597 100644 --- a/src/vec/vec-final.md +++ b/src/vec/vec-final.md @@ -158,19 +158,6 @@ impl Vec { } } - pub fn into_iter(self) -> IntoIter { - 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 { unsafe { let iter = RawValIter::new(&self); @@ -208,6 +195,23 @@ impl DerefMut for Vec { } } +impl IntoIterator for Vec { + type Item = T; + type IntoIter = IntoIter; + fn into_iter(self) -> IntoIter { + unsafe { + let iter = RawValIter::new(&self); + let buf = ptr::read(&self.buf); + mem::forget(self); + + IntoIter { + iter: iter, + _buf: buf, + } + } + } +} + struct RawValIter { start: *const T, end: *const T, diff --git a/src/vec/vec-into-iter.md b/src/vec/vec-into-iter.md index 33327e8..dc15c3e 100644 --- a/src/vec/vec-into-iter.md +++ b/src/vec/vec-into-iter.md @@ -57,8 +57,10 @@ And this is what we end up with for initialization: ```rust,ignore -impl Vec { - pub fn into_iter(self) -> IntoIter { +impl IntoIterator for Vec { + type Item = T; + type IntoIter = IntoIter; + fn into_iter(self) -> IntoIter { // Can't destructure Vec since it's Drop let ptr = self.ptr; let cap = self.cap; diff --git a/src/vec/vec-raw.md b/src/vec/vec-raw.md index a7d8dbe..e86537b 100644 --- a/src/vec/vec-raw.md +++ b/src/vec/vec-raw.md @@ -134,8 +134,10 @@ impl Drop for IntoIter { } } -impl Vec { - pub fn into_iter(self) -> IntoIter { +impl IntoIterator for Vec { + type Item = T; + type IntoIter = IntoIter; + fn into_iter(self) -> IntoIter { unsafe { // 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).