From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id DE767EDE9B0 for ; Tue, 10 Sep 2024 20:04:38 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 754608D00B6; Tue, 10 Sep 2024 16:04:38 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 7040F8D0002; Tue, 10 Sep 2024 16:04:38 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5CCAD8D00B6; Tue, 10 Sep 2024 16:04:38 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0013.hostedemail.com [216.40.44.13]) by kanga.kvack.org (Postfix) with ESMTP id 3858F8D0002 for ; Tue, 10 Sep 2024 16:04:38 -0400 (EDT) Received: from smtpin19.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id E0586A8D16 for ; Tue, 10 Sep 2024 20:04:37 +0000 (UTC) X-FDA: 82549906194.19.B796962 Received: from mail-4316.protonmail.ch (mail-4316.protonmail.ch [185.70.43.16]) by imf08.hostedemail.com (Postfix) with ESMTP id DC9CB16002B for ; Tue, 10 Sep 2024 20:04:35 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=proton.me header.s=protonmail header.b=kZrlA4dD; dmarc=pass (policy=quarantine) header.from=proton.me; spf=pass (imf08.hostedemail.com: domain of benno.lossin@proton.me designates 185.70.43.16 as permitted sender) smtp.mailfrom=benno.lossin@proton.me ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1725998592; a=rsa-sha256; cv=none; b=aD9+CqKwKBRycKIYYTBbs0qVVz2Le9uzHEFA2QW2itxuZNzgqV8Qc/qFY5p0w3OF/EE3m5 r/aRoMR9lZn1uI9KsTYwAK6jlMrpx7k9811uJumE7saWoLeQd3w+QQO9X8FCrJPr3y2qXu HygpsXXWUZAx0Sn9Oi5MgXudx64n5Q4= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=proton.me header.s=protonmail header.b=kZrlA4dD; dmarc=pass (policy=quarantine) header.from=proton.me; spf=pass (imf08.hostedemail.com: domain of benno.lossin@proton.me designates 185.70.43.16 as permitted sender) smtp.mailfrom=benno.lossin@proton.me ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1725998592; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=ENz53fEk86BgBhfUiQ+jlgzdiXHlf5LBcT9PrqrkEE8=; b=vpFrhNu7o7/5dDQ3j6Q5mVnDX+/0t7K0lOnjg+3qD1bkXaqBSzYN7tBc/jwTcEJPxk5A/F 4SDJzAoxIzEK1dgMmaEzZTDLfbFtpo6gAcmNVigsLR0l+U3H46Nu8jpOX7OqUWPu5308bz pG565NgTeiwSkRQSs9r+4lAtCkSTeb0= DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=proton.me; s=protonmail; t=1725998673; x=1726257873; bh=ENz53fEk86BgBhfUiQ+jlgzdiXHlf5LBcT9PrqrkEE8=; h=Date:To:From:Cc:Subject:Message-ID:In-Reply-To:References: Feedback-ID:From:To:Cc:Date:Subject:Reply-To:Feedback-ID: Message-ID:BIMI-Selector; b=kZrlA4dDTD9K96RQAJnWasRA4TqPHYTJJBgohjGmxTDKmwXjJCUqIsC8feIpjhf2b 1zKz176HFHKBA+tv2y46nn9ZSrS6eOfIHZPAMk/LXGJDKhlZIrBrrFT4GT7NPLABRt bWYKKZk173BEGJbgrNGUqPPD6Ur8HyacnzHrUStTdlPpEzDi9RegfR8D8Uqch1tCg4 sDzxtf/d5dAT9AAqlBMdWn8AYutAsYBicT13lfO8ucZl8n1a7zba+fGRrKE5Zub7ws cZieS9v+ScvmbCbMCeXkxiB92rqiBvjoRbhsZ5fH/yr18sgvK73qPwvHHIzdchc89K u4tepUaUbftgg== Date: Tue, 10 Sep 2024 20:04:27 +0000 To: Danilo Krummrich , ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org From: Benno Lossin Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org Subject: Re: [PATCH v6 14/26] rust: alloc: implement `IntoIterator` for `Vec` Message-ID: <308d40dd-105b-4ebf-ba70-585a97d66928@proton.me> In-Reply-To: <20240816001216.26575-15-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> <20240816001216.26575-15-dakr@kernel.org> Feedback-ID: 71780778:user:proton X-Pm-Message-ID: d3f8bbb264eaf1b88a2abc6facc9fa1fcfeaab7a MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: DC9CB16002B X-Stat-Signature: 5u6ep4nesmwzy6esrr5ze86brf3cyhpk X-Rspam-User: X-HE-Tag: 1725998675-130305 X-HE-Meta: U2FsdGVkX18TvZa+EGdLvPBYHsVnvva/qzDNk50lrSCBemVY8bnyqY4KcdqgiD16RWwJHqIx76pEkB4fB2iU7+VcHvZnaDNrTjfRcNEmBZ4zFCe6kVzZJYedPUpg39Mg7m0D8RdskyMnos5ShC7rXG9b9VDK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Tj06Hh7BpAsrfKWSXgD3P2fjSFoo89pvyYagkHPTEX3H6eS7ujJCUMms83qIgMOVasTkFGFIItOii6TmM0AB+IMLRN3BnJJ2ZxF8ql4YwtI63zXOuA19dlOuMuAqo0fn01MQ4beQJ6Hcp7dxT/2gEoOhyjX8W5d5MIEiHxywF+aONHQcIqBe9EXyYJyL4Zdq89lQFYdtMpB/c= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: On 16.08.24 02:10, Danilo Krummrich wrote: > Implement `IntoIterator` for `Vec`, `Vec`'s `IntoIter` type, as well as > `Iterator` for `IntoIter`. >=20 > `Vec::into_iter` disassembles the `Vec` into its raw parts; additionally, > `IntoIter` keeps track of a separate pointer, which is incremented > correspondingsly as the iterator advances, while the length, or the count > of elements, is decremented. >=20 > This also means that `IntoIter` takes the ownership of the backing > buffer and is responsible to drop the remaining elements and free the > backing buffer, if it's dropped. >=20 > Signed-off-by: Danilo Krummrich > --- > rust/kernel/alloc.rs | 1 + > rust/kernel/alloc/kvec.rs | 184 ++++++++++++++++++++++++++++++++++++++ > 2 files changed, 185 insertions(+) >=20 > diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs > index e88c7e10ee9b..4ff4df4597a3 100644 > --- a/rust/kernel/alloc.rs > +++ b/rust/kernel/alloc.rs > @@ -19,6 +19,7 @@ > pub use self::kbox::KVBox; > pub use self::kbox::VBox; >=20 > +pub use self::kvec::IntoIter; > pub use self::kvec::KVVec; > pub use self::kvec::KVec; > pub use self::kvec::VVec; > diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs > index 89afc0f25bd4..3b79f977b65e 100644 > --- a/rust/kernel/alloc/kvec.rs > +++ b/rust/kernel/alloc/kvec.rs > @@ -11,6 +11,7 @@ > ops::DerefMut, > ops::Index, > ops::IndexMut, > + ptr, > ptr::NonNull, > slice, > slice::SliceIndex, > @@ -627,3 +628,186 @@ fn eq(&self, other: &$rhs) -> bool { self[..] =3D= =3D other[..] } > __impl_slice_eq! { [A: Allocator] [T], Vec } > __impl_slice_eq! { [A: Allocator, const N: usize] Vec, [U; N] } > __impl_slice_eq! { [A: Allocator, const N: usize] Vec, &[U; N] } > + > +impl<'a, T, A> IntoIterator for &'a Vec > +where > + A: Allocator, > +{ > + type Item =3D &'a T; > + type IntoIter =3D slice::Iter<'a, T>; > + > + fn into_iter(self) -> Self::IntoIter { > + self.iter() > + } > +} > + > +impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec > +where > + A: Allocator, > +{ > + type Item =3D &'a mut T; > + type IntoIter =3D slice::IterMut<'a, T>; > + > + fn into_iter(self) -> Self::IntoIter { > + self.iter_mut() > + } > +} > + > +/// An `Iterator` implementation for `Vec` that moves elements out = of a vector. Please make both links. > +/// > +/// This structure is created by the `Vec::into_iter` method on [`Vec`] = (provided by the Ditto. > +/// [`IntoIterator`] trait). > +/// > +/// # Examples > +/// > +/// ``` > +/// let v =3D kernel::kvec![0, 1, 2]?; > +/// let iter =3D v.into_iter(); > +/// > +/// # Ok::<(), Error>(()) > +/// ``` > +pub struct IntoIter { > + ptr: *mut T, > + buf: NonNull, No invariants for these two fields? > + len: usize, > + cap: usize, > + _p: PhantomData, > +} > + > +impl IntoIter > +where > + A: Allocator, > +{ > + fn as_raw_mut_slice(&mut self) -> *mut [T] { > + ptr::slice_from_raw_parts_mut(self.ptr, self.len) > + } > +} > + > +impl Iterator for IntoIter > +where > + A: Allocator, > +{ > + type Item =3D T; > + > + /// # Examples > + /// > + /// ``` > + /// let v =3D kernel::kvec![1, 2, 3]?; > + /// let mut it =3D v.into_iter(); > + /// > + /// assert_eq!(it.next(), Some(1)); > + /// assert_eq!(it.next(), Some(2)); > + /// assert_eq!(it.next(), Some(3)); > + /// assert_eq!(it.next(), None); > + /// > + /// # Ok::<(), Error>(()) > + /// ``` AFAIK documentation on functions in trait implementations won't show up in rustdoc (I just checked this). So I would remove it. > + fn next(&mut self) -> Option { > + if self.len =3D=3D 0 { > + return None; > + } > + > + let ptr =3D self.ptr; > + if !Vec::::is_zst() { > + // SAFETY: We can't overflow; `end` is guaranteed to mark th= e end of the buffer. > + unsafe { self.ptr =3D self.ptr.add(1) }; > + } else { > + // For ZST `ptr` has to stay where it is to remain aligned, = so we just reduce `self.len` > + // by 1. Note that `<*mut T>::add` advances the pointer by `size_of::()` bytes. So in the case that `T` is a ZST, it won't be advanced. So you could remove this `if`. > + } > + self.len -=3D 1; > + > + // SAFETY: `ptr` is guaranteed to point at a valid element withi= n the buffer. > + Some(unsafe { ptr.read() }) > + } > + > + /// # Examples > + /// > + /// ``` > + /// let v: KVec =3D kernel::kvec![1, 2, 3]?; > + /// let mut iter =3D v.into_iter(); > + /// let size =3D iter.size_hint().0; > + /// > + /// iter.next(); > + /// assert_eq!(iter.size_hint().0, size - 1); > + /// > + /// iter.next(); > + /// assert_eq!(iter.size_hint().0, size - 2); > + /// > + /// iter.next(); > + /// assert_eq!(iter.size_hint().0, size - 3); > + /// > + /// # Ok::<(), Error>(()) > + /// ``` > + fn size_hint(&self) -> (usize, Option) { > + (self.len, Some(self.len)) > + } > +} > + > +impl Drop for IntoIter > +where > + A: Allocator, > +{ > + fn drop(&mut self) { > + // SAFETY: Drop the remaining vector's elements in place, before= we free the backing > + // memory. This comment explains why you are doing it, not why it's ok to do it. > + unsafe { ptr::drop_in_place(self.as_raw_mut_slice()) }; > + > + // If `cap =3D=3D 0` we never allocated any memory in the first = place. > + if self.cap !=3D 0 { > + // SAFETY: `self.buf` was previously allocated with `A`. > + unsafe { A::free(self.buf.cast()) }; > + } > + } > +} > + > +impl IntoIterator for Vec > +where > + A: Allocator, > +{ > + type Item =3D T; > + type IntoIter =3D IntoIter; > + > + /// Consumes the `Vec` and creates an `Iterator`, which moves = each value out of the > + /// vector (from start to end). > + /// > + /// # Examples > + /// > + /// ``` > + /// let v =3D kernel::kvec![1, 2]?; > + /// let mut v_iter =3D v.into_iter(); > + /// > + /// let first_element: Option =3D v_iter.next(); > + /// > + /// assert_eq!(first_element, Some(1)); > + /// assert_eq!(v_iter.next(), Some(2)); > + /// assert_eq!(v_iter.next(), None); > + /// > + /// # Ok::<(), Error>(()) > + /// ``` > + /// > + /// ``` > + /// let v =3D kernel::kvec![]; > + /// let mut v_iter =3D v.into_iter(); > + /// > + /// let first_element: Option =3D v_iter.next(); > + /// > + /// assert_eq!(first_element, None); > + /// > + /// # Ok::<(), Error>(()) > + /// ``` I feel a bit bad that you wrote all of this nice documentation for functions that receive their documentation from the trait... --- Cheers, Benno > + #[inline] > + fn into_iter(self) -> Self::IntoIter { > + let (ptr, len, cap) =3D self.into_raw_parts(); > + > + IntoIter { > + ptr, > + // SAFETY: `ptr` is either a dangling pointer or a pointer t= o a valid memory > + // allocation, allocated with `A`. > + buf: unsafe { NonNull::new_unchecked(ptr) }, > + len, > + cap, > + _p: PhantomData::, > + } > + } > +} > -- > 2.46.0 >=20