From patchwork Tue Jul 23 18:10:04 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13740266 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 C5B6BC3DA7F for ; Tue, 23 Jul 2024 18:12:21 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 3F5A56B0082; Tue, 23 Jul 2024 14:12:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 37DDE6B00A9; Tue, 23 Jul 2024 14:12:21 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1D1136B00AA; Tue, 23 Jul 2024 14:12:21 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id F0A296B0082 for ; Tue, 23 Jul 2024 14:12:20 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id A834C140336 for ; Tue, 23 Jul 2024 18:12:20 +0000 (UTC) X-FDA: 82371812040.03.BECEC77 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf14.hostedemail.com (Postfix) with ESMTP id 075EC100015 for ; Tue, 23 Jul 2024 18:12:18 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ASoYC5Ro; spf=pass (imf14.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=1721758276; 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=fiQJi6a8L56jq90iVV1ruKgfsSxkPxSv6lIunMWfd/c=; b=mMPaN5wmOjnUrkbQ3agWSviGHaHOlZ3gylDn6W+xJaxopU3YZPZaxOIMnj78viBxBYEpKJ nFHpOjX+T3J1566N+DIznBRk3y+fU9c2jY8A/5nKaZHO+bDdNYRLrGi0Fs/rYFvR5BlL4n K+5RxnCiEb7ns94KbWvpwnzFS1gYkto= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ASoYC5Ro; spf=pass (imf14.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-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758276; a=rsa-sha256; cv=none; b=4HlEw2lXoyLlVK1mNZslACPpA+LBVTTBRBPH9Z5U7Abnqq7ND7Zs1GTL4aOz95ShormzVN A2NR2Ne8PkpuYNtSdsPtwD0GrZgTvrW4g1M9vaRxAQ8vfnu558DwCxOlbIcbpRtuAQIntG PPK3ZfUC862zMcTLr5NHg0faU3ECXbM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 2035E60E00; Tue, 23 Jul 2024 18:12:18 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B70FCC4AF0A; Tue, 23 Jul 2024 18:12:12 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758337; bh=c3QAEBZXl3M1WsOmfNh19vNXUNzyZvBix2UsBjiGOtI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ASoYC5RoyFxVt1qORsF7cKfWeydOo+meew08vpzJjAAxJiB8eIifrdSo9n0K9QN88 IoR3tEeo+y4EqksYwvQz/OPsRDe2OKxBfrdZqgY2g15Rto6/wMtHsHnQVuqZjxJpE3 KH20JQVp77kvTCJtWlrgxNSVDtLNhAbGePPbfNAXZ4ymEhnejSzwc4/FbCVWCKCSTX AyFoOjfoq4hoZtQf4lMM7MoYvUN5hxC3Y8SPnyYCC9yZKsJw+pp5CvjJf9r7+H5ps6 7JHpY+kwXX6Fo9b6XB4J/ZSkQoczgRAQ1O1ijBoprzvvG0tXCxOlUxbM6IfGA8tU2n W4T0bgS7ldmbQ== 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 v2 15/23] rust: alloc: implement `IntoIterator` for `Vec` Date: Tue, 23 Jul 2024 20:10:04 +0200 Message-ID: <20240723181024.21168-16-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 075EC100015 X-Stat-Signature: a1b7a758idm3mt8uik4dg54z1bn1npgm X-Rspam-User: X-HE-Tag: 1721758338-140499 X-HE-Meta: U2FsdGVkX18V7yJeT9vkTwozZry5Rx/q9eqkGfVWsOfhGknvcc8I9EkWsYcZPQc+R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NiQQqS3aGAerf9y/led5diINopceA0lol1do4CTlphHcGXgAgsW2emklGZ0ixLaowNxkJwyA8R+BSgYmNsm+ArExR1uI6AOUSIOeijVIxYF03rekRTI7Y49J3Ruk9cRCyCdjG3w+bxCT6KNXygx79K8wLBewrxbO/O6XP9m6E6i1eygZemdju4PSt7R64YtX5A== 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 | 175 +++++++++++++++++++++++++++++++++++++- 2 files changed, 175 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 827922e1f1d1..19e0ad0bf98b 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 58b3f679ad83..fbfb755b252d 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -12,7 +12,9 @@ ops::DerefMut, ops::Index, ops::IndexMut, - ptr, slice, + ptr, + ptr::NonNull, + slice, slice::SliceIndex, }; @@ -578,3 +580,174 @@ 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>(()) + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let (ptr, len, cap) = self.into_raw_parts(); + + IntoIter { + ptr, + buf: unsafe { NonNull::new_unchecked(ptr) }, + len, + cap, + _p: PhantomData::, + } + } +}