From patchwork Thu Aug 1 00:02:15 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749355 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 F1342C3DA64 for ; Thu, 1 Aug 2024 00:08:26 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 860476B00B0; Wed, 31 Jul 2024 20:08:26 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 8115A6B00B2; Wed, 31 Jul 2024 20:08:26 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 6AFB26B00B3; Wed, 31 Jul 2024 20:08:26 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 4B1A76B00B0 for ; Wed, 31 Jul 2024 20:08:26 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 0E03D1607DB for ; Thu, 1 Aug 2024 00:08:26 +0000 (UTC) X-FDA: 82401739812.12.7666DFC Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf02.hostedemail.com (Postfix) with ESMTP id C91818000D for ; Thu, 1 Aug 2024 00:08:23 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fb5hc0kR; spf=pass (imf02.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 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=1722470876; 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=FWyc/CXsa+KXeNtwmYJ8C/VRwZSK5FYscCv4PqQAmQ4=; b=pnUQdkrTYUqgIkBJ/Shcv6JlIdt83BhTxnUKBdzTYgZuYh93NmvF50/kLxkrN5KrmJhCHL 1K5DSXczv7szvvtSNa+v6CLjI30Ferai1+MgkwNdjLjayzxVpUJtrH/cQAVxbEJxLxMPVp RGi+VumysCi6yxFQD4mihDjuxhN2AN4= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fb5hc0kR; spf=pass (imf02.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 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=1722470876; a=rsa-sha256; cv=none; b=YIbL0uM8QnsfRIUPj7CxIWkP3BkqLwY8ydBx9CZLokVyEtdccqzBrdhcVTW2TwW6zBpdIo ZDSay7WTIhuF3p0h9FGHV0Nt/QRitFmf9bakZr8qBqrGXFwxfzNKW1AwPTGF6rtEKpn9jn xnyHzLbr25+HRouX8rwMNj8qnKyRTkw= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 0B210CE186A; Thu, 1 Aug 2024 00:08:21 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 53364C4AF0E; Thu, 1 Aug 2024 00:08:15 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470900; bh=jAbO/ocd+GDx9TX4LOAzMK63XGdOeFxsvuJ3d1oWSfI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fb5hc0kRBB53GlmIo7ISRm3ZFGGf2BIUq4w2KkggQ93QJruFcu0+zWcZlEknwxFpd 7gU/6/qKYBi/+KJFxQl6YAej/rg52M/yx/fWUky0taAaqdMr34zqTnsvl72EbQWQaJ kg5d4W2Wjmp7ma17noKc0jvUUAcZGMCuKVBJI6vUPkr5Q9Ru26Utz+J8oLPYFeiLEC lVatKFDoPzsDrZmWVb1qHzOwemrWt4xemw9F4jjjrhCx0T2b1t3soGoiJzZi5ICeow hjJEPfZm8AkPv+DJsF/UXNOHw15IrZ9XHdysw8ds+T11sWKcwO9vR8oBJydXpTTi1A d5IxqmDYCrh+w== 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 v3 16/25] rust: alloc: implement `IntoIterator` for `Vec` Date: Thu, 1 Aug 2024 02:02:15 +0200 Message-ID: <20240801000641.1882-17-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: C91818000D X-Stat-Signature: iz3cmd5cx31hnzxezxw8ou46pc8a9k9n X-HE-Tag: 1722470903-962502 X-HE-Meta: U2FsdGVkX19BbSgkqjreQDDzj/CkMj326+l+sBvucHqfSn/vkR/GY+MP9/T7Q8G6jBVaemEBWgn7q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BP8SyDSXoasYj/5GONk/yQUV0PMclmE7wwHZpOa1fc5c3Rk6EG9k4rssGZS8K5yTxp+2O0MwojrakSYTKI5IptdZWG7nYFEWvyPz7GD9mVPqkJqkKEvNYHI6EOnc51zJXSp3nwcFaj7BAD30nhVsgrdMc45uOhQQiAYEyAQa8qSw== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000001, 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 bd93140f3094..f2998ad57456 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 04cc85f7d92c..50e7705e5686 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, }; @@ -581,3 +583,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::, + } + } +}