From patchwork Fri Aug 16 00:10:56 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765295 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 64448C52D7F for ; Fri, 16 Aug 2024 00:13:43 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D5EF38D001E; Thu, 15 Aug 2024 20:13:42 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D104D8D0002; Thu, 15 Aug 2024 20:13:42 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id BAEEA8D001E; Thu, 15 Aug 2024 20:13:42 -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 9CBE78D0002 for ; Thu, 15 Aug 2024 20:13:42 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 3EDB68188E for ; Fri, 16 Aug 2024 00:13:42 +0000 (UTC) X-FDA: 82456185084.08.66B774A Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf01.hostedemail.com (Postfix) with ESMTP id 8D16440009 for ; Fri, 16 Aug 2024 00:13:40 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=L4WdWJAO; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767148; 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=ifI1R8kHB8XReRuYU85B9zwZeylS0SKtlnh07Y3i92Q=; b=nfEUCR0yahFA8aiStKzuOa6bfOMD4qeWyd1Aj0I9CuVLJYB0eTEAUcjEgXQoakpzj+6u8l rjMia53ntp0ny77dF06VNjR9jjZC9vCZI4EzDTU2fhF2C7wCkpj7euCQrtUmS+BbSjDNy1 Qtbdrv8aoNdfVklZwJhsnVcLrxmICCg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767148; a=rsa-sha256; cv=none; b=oJxWWNuxb8va/htKEFB77u6DLeUdYE1sajxlHmwJNZWpMhyPP1eW+MgjeQokZ7ob/jT/kT 4Roy96HtBQtlbpfe6rTH67NMHV7ziDxDglzlMiIC+OLCuuJD282EV1PlSIVCuV5gEqagmK 7aKpbm3ud5pBnci6MK3W/D5KrlIHzvQ= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=L4WdWJAO; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id C3FA662061; Fri, 16 Aug 2024 00:13:39 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9FFA3C4AF0C; Fri, 16 Aug 2024 00:13:34 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767219; bh=ZRtvys+hWiPU9zH5CUlK8W5COnhh7tIaK0hqtMfStIA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=L4WdWJAOlQqM9I/rWRCl3rYcHiX5vhZnPH9tq5y/k63xcNbqTko4RR82QR9IAvvFq 03ROA7Q3h3LxdWAStZixhF/X2X7uVd2/maZft0FfLTjSqGXqhINTm0cuR8MzIhkvgq FgAOlTDMJB0Hu9euNMLfkdj1mJy7xQiTSO0BpdwxPEMIFypYbdR+QjjipaI4ipKqNP blt03fj/BMIkOJsDr/1k8gBeTWnTf6sjn9uNyUMQanzugpaIogVqNZhnyBI1Afca7h mWGRonHKScQ/b5Cj6ZEgPsTsU1J9IdcJSy1V/vcaZEFVlX7W0Vvy4jwAYISRTq8MsK is1zPHicng5NQ== 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, 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 v6 14/26] rust: alloc: implement `IntoIterator` for `Vec` Date: Fri, 16 Aug 2024 02:10:56 +0200 Message-ID: <20240816001216.26575-15-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 8D16440009 X-Stat-Signature: mu4r165ietpjwczhbukankopg1wtiibj X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1723767220-811183 X-HE-Meta: U2FsdGVkX18mp/zb6C/DvDmk7jCJxV0VL4iLT5vp13dfLlhAPxUadIQY0cwooBUKYTYwGJXQRusN4v8zJbC2KOQr3A3yvHr75VKW5z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eHpF0n5RNO3boiE7SefxKN3A+iPP+TN3J/D/tOcybzBwJ0o8QouYv7D9B4wp3L2VcciEFfKNwgwJmXwUeodycfj6jP7x6CdkGxGzrbZkl8Gvy8Q5Rn8I0jxQanAKYlOusJLPY7IY370IeGkQiY30+qXg== 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 Reviewed-by: Alice Ryhl --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 184 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 185 insertions(+) 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; +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[..] == 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` implementation for `Vec` that moves elements out of a vector. +/// +/// This structure is created by the `Vec::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; + + /// Consumes the `Vec` and creates an `Iterator`, which moves each value out of the + /// vector (from start to end). + /// + /// # 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::, + } + } +}