From patchwork Mon Aug 5 15:19:35 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753725 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 D5AC8C3DA7F for ; Mon, 5 Aug 2024 15:21:46 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5A6D86B00AD; Mon, 5 Aug 2024 11:21:46 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 336D06B00AE; Mon, 5 Aug 2024 11:21:46 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 186966B00AF; Mon, 5 Aug 2024 11:21:46 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id EBC296B00AD for ; Mon, 5 Aug 2024 11:21:45 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 55E24160382 for ; Mon, 5 Aug 2024 15:21:45 +0000 (UTC) X-FDA: 82418556570.17.380F64D Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf20.hostedemail.com (Postfix) with ESMTP id 9C0631C0003 for ; Mon, 5 Aug 2024 15:21:43 +0000 (UTC) Authentication-Results: imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=gYzOyUPG; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf20.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871258; a=rsa-sha256; cv=none; b=69ZOamafBSk47+rb2QeOvOz1w36ri7wZCVmpCIwlaDuaMAZdgz/oD/5J/iN4vAWFnCxgqt ovL1lkgxjYStxJCYqEU36yAEUIXlTpWh52A7417WK7BMKm/F4hDRRZ50WLl7Nmddj21pxD 5reP+Kxsq5gDsK3eiyvpC4erAM0kRJ4= ARC-Authentication-Results: i=1; imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=gYzOyUPG; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf20.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722871258; 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-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=Pn11VUbkvJ6GW4qxPbHU7GLU2uJVUSDKIUWvFado2sM=; b=LQW7D25iAz8yu6kR81oe/HUvBsbrmr6qhRssJkwkliK5lJZ6NX2NKgCL35xDSmtyz6EQ9P l13Gx2s0KKMMxq/V8Gn634ZrQ0BxsGIRQpJyRpquUrI5BxHzHM4rq8UDBI0zLoBUOIRQfH PwkFzetFEVNScz/TBeJn+vRAfy2Edeo= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id AB49960CFA; Mon, 5 Aug 2024 15:21:42 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5138BC4AF0E; Mon, 5 Aug 2024 15:21:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871302; bh=EOv825N2AZNtDITSBB60LhXsn2pwxBz/HyLjwhp7xNk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=gYzOyUPGGvzsiMCuH+V0ldzMfE7hiGbdGKAbK0Tqa6euhkVivoi0+hDENWQHThRWX 2w3a6tls/UCFaVEKHsLRO/Q6FcpFslG5N1YkJRZedT/KojKDdDCeuiEd/Xq5ddWU6r /Iis8UdRt68YDCxh1Agab0XRwfReNwszxWXPVnUoxXuigGnHnZa2i985IhIIqWqtTM UzhIiI6lhVyQ8iLU3RHkQAsSZlfUwQ/7VGf5ejaE1bFFHRvERoofuYrFSFeCxqkNFe 1vesmYCILN1fNzoBV69DgiNt2r/AcfQyaEAz3pCUSha/OFhcumt5MJUu+VIjUPcpv+ 4TBxhXiqojWPQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@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, Danilo Krummrich Subject: [PATCH v4 16/28] rust: alloc: implement `IntoIterator` for `Vec` Date: Mon, 5 Aug 2024 17:19:35 +0200 Message-ID: <20240805152004.5039-17-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 9C0631C0003 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: zn7ok9r4pip5ryu8zpayhap1hoscmfd5 X-HE-Tag: 1722871303-967220 X-HE-Meta: U2FsdGVkX1/kjIo6wAuWkYrd++PyEJ3P2xa2ZmjwLD5QXZBIRvRUV18eHEsomrndf9yu+RiK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ayllTw9Y9J1NkUOqNzn24cUyyadOhHTvVPr8QNbNkMDqVGmXU8137RZ3up7u6949M/mXqFU0ccA3XAShD+vLdePdjezRmPWHLPA5Dxhzp/pe8dYO/5KdDX3hB53OEUMXeqN4rwF2f77y+N46/5HouadEHTlu5rCSEmJGyZGuPqU+BOs1hunRQ== 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: Implement `IntoIterator` for `Vec`, `Vec`'s `IntoIter` type, as well as `Iterator` for `IntoIter`. `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. 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. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 186 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 187 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 28c186906e1b..86648037b3dc 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; +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 6cf62e7dd36f..51426e0b28e0 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -12,6 +12,8 @@ ops::DerefMut, ops::Index, ops::IndexMut, + ptr, + ptr::NonNull, slice, slice::SliceIndex, }; @@ -589,3 +591,187 @@ fn eq(&self, other: &$rhs) -> bool { self[..] == 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 = &'a T; + type IntoIter = 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 = &'a mut T; + type IntoIter = slice::IterMut<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +/// An iterator that moves out of a vector. +/// +/// This `struct` is created by the `into_iter` method on [`Vec`] (provided by the [`IntoIterator`] +/// trait). +/// +/// # Examples +/// +/// ``` +/// let v = kernel::kvec![0, 1, 2]?; +/// let iter = v.into_iter(); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub struct IntoIter { + ptr: *mut T, + buf: NonNull, + 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 = T; + + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2, 3]?; + /// let mut it = 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>(()) + /// ``` + fn next(&mut self) -> Option { + if self.len == 0 { + return None; + } + + let ptr = self.ptr; + if !Vec::::is_zst() { + // SAFETY: We can't overflow; `end` is guaranteed to mark the end of the buffer. + unsafe { self.ptr = 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. + } + self.len -= 1; + + // SAFETY: `ptr` is guaranteed to point at a valid element within the buffer. + Some(unsafe { ptr.read() }) + } + + /// # Examples + /// + /// ``` + /// let v: KVec = kernel::kvec![1, 2, 3]?; + /// let mut iter = v.into_iter(); + /// let size = 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. + unsafe { ptr::drop_in_place(self.as_raw_mut_slice()) }; + + // If `cap == 0` we never allocated any memory in the first place. + if self.cap != 0 { + // SAFETY: `self.buf` was previously allocated with `A`. + unsafe { A::free(self.buf.cast()) }; + } + } +} + +impl IntoIterator for Vec +where + A: Allocator, +{ + type Item = T; + type IntoIter = IntoIter; + + /// Creates a consuming iterator, that is, one that moves each value out of + /// the vector (from start to end). The vector cannot be used after calling + /// this. + /// + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2]?; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = 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 = kernel::kvec![]; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = v_iter.next(); + /// + /// assert_eq!(first_element, None); + /// + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let (ptr, len, cap) = self.into_raw_parts(); + + IntoIter { + ptr, + // SAFETY: `ptr` is either a dangling pointer or a pointer to a valid memory + // allocation, allocated with `A`. + buf: unsafe { NonNull::new_unchecked(ptr) }, + len, + cap, + _p: PhantomData::, + } + } +}