From patchwork Tue Oct 1 14:59:53 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818237 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 E8EE3CEACDC for ; Tue, 1 Oct 2024 15:01:58 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 80A07680015; Tue, 1 Oct 2024 11:01:57 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 76894280068; Tue, 1 Oct 2024 11:01:57 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 595C7680015; Tue, 1 Oct 2024 11:01:57 -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 37B61280068 for ; Tue, 1 Oct 2024 11:01:57 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id C64851209B7 for ; Tue, 1 Oct 2024 15:01:56 +0000 (UTC) X-FDA: 82625348232.16.DCE4FAB Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf26.hostedemail.com (Postfix) with ESMTP id 2D18114000E for ; Tue, 1 Oct 2024 15:01:54 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hAVzhdkB; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 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=1727794774; 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=6+isFfEv8NpwPOmMh2hqeoPPB0NtfNAZFG5xltJeSvI=; b=evvwwqktYQRlt6sw6LFAXmZgs+UIENbqa+NtUAE0Ee62hxlyP6os6yA3wOXeAcOslYstPU LF2JShuc01lmwCZRpSACdSVRnfn7gFE8G28YHkg26qg2X78aPW1FgyW8aDILj9Ib0L/4hG KZGfs2xmX1QpZUycz5rVE1MFo3z0RcI= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794774; a=rsa-sha256; cv=none; b=HPzps0TVsQAP5cKXsMUWYuIXunvKeD25pDS8FsqbQHv6zr2AbaB16k1quf7l6R3MYmdiob 22hPNSym9ZAbXs4+yN0XjkHzxiIKNmY1JGoB6e1T8FSW5+/zyTLyA2Pdcvr42MJy0Io5uK gmMMaSle5WI21VAWisxEa4D3vUDFtAY= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hAVzhdkB; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 2B3D1A40104; Tue, 1 Oct 2024 15:01:46 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 40919C4CED4; Tue, 1 Oct 2024 15:01:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794914; bh=MwYQyJaBKHTn8WIWv0eTKw1s4/kooQlsfmpXe9kkPyo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hAVzhdkBlESVit9NBGfGk8d3WQcFwnUF4xU94wv33PIpIpwrVCOYFtxb2ONALejOl dRpEuS817+xztyEb5apQFjgDobbKiPS00hwkbE/bWXtuYtS10wqTTwmc8/uJwWi1wB fIL4SuFy7342DFfdoza/n/8b+cikdtIL+hg44AF9mTZEoFrb4ovaS/6j3K7+kYvLCk eOpDeU6/fKdW0Z0ar5vH4FqT+5hlSoasi+1stEC3470t5xzDOwWDWDJ0Da/WLzwlwr CQSDkMnsEVwfwtLEdV/lvKjhelw8OBZhZcv+o7Mp+sD5S54LR9JkmIEWKaUvked6TO jq9AzXGRUyDYw== 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 v8 18/29] rust: alloc: implement `collect` for `IntoIter` Date: Tue, 1 Oct 2024 16:59:53 +0200 Message-ID: <20241001150008.183102-19-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 2D18114000E X-Stat-Signature: ro3ias6qq16r7wbkns7xurx1apnwsynb X-Rspam-User: X-HE-Tag: 1727794914-195682 X-HE-Meta: U2FsdGVkX1/Bea/jDM3Vlsp53mC1gUTgQ3Qk714BMEzgL+lUPgB6VsYFjMwyAIP8FMvQNtES1AcuZfGcLuqIfrc8ss3OZasi8Z21QXy8VD0XYb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V7UZajnv4AfDsulE3j+n+YBFj4FuP9n0x87YqBVlLgB0pOePFz+StzjlCZFLJ6ZvMecK+IB1CVlAKldwZAeyuaLSF6kG7AXYk1lkq5QjkjA/JpK0KBeEoZiA0Z11yF+kMs1A8eeU= 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: Currently, we can't implement `FromIterator`. There are a couple of issues with this trait in the kernel, namely: - Rust's specialization feature is unstable. This prevents us to optimze for the special case where `I::IntoIter` equals `Vec`'s `IntoIter` type. - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` doesn't require this type to be `'static`. - `FromIterator::from_iter` does return `Self` instead of `Result`, hence we can't properly handle allocation failures. - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation flags. Instead, provide `IntoIter::collect`, such that we can at least convert `IntoIter` into a `Vec` again. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/kvec.rs | 94 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index ff1c152d3423..0ee320ed99a0 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -681,6 +681,100 @@ pub struct IntoIter { _p: PhantomData, } +impl IntoIter +where + A: Allocator, +{ + fn into_raw_parts(self) -> (*mut T, NonNull, usize, usize) { + let me = ManuallyDrop::new(self); + let ptr = me.ptr; + let buf = me.buf; + let len = me.len; + let cap = me.layout.len(); + (ptr, buf, len, cap) + } + + /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`. + /// + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2, 3]?; + /// let mut it = v.into_iter(); + /// + /// assert_eq!(it.next(), Some(1)); + /// + /// let v = it.collect(GFP_KERNEL); + /// assert_eq!(v, [2, 3]); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// # Implementation Details + /// + /// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait + /// in the kernel, namely: + /// + /// - Rust's specialization feature is unstable. This prevents us to optimze for the special + /// case where `I::IntoIter` equals `Vec`'s `IntoIter` type. + /// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` + /// doesn't require this type to be `'static`. + /// - `FromIterator::from_iter` does return `Self` instead of `Result`, hence + /// we can't properly handle allocation failures. + /// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation + /// flags. + /// + /// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a + /// `Vec` again. + /// + /// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing + /// buffer. However, this backing buffer may be shrunk to the actual count of elements. + pub fn collect(self, flags: Flags) -> Vec { + let old_layout = self.layout; + let (mut ptr, buf, len, mut cap) = self.into_raw_parts(); + let has_advanced = ptr != buf.as_ptr(); + + if has_advanced { + // Copy the contents we have advanced to at the beginning of the buffer. + // + // SAFETY: + // - `ptr` is valid for reads of `len * size_of::()` bytes, + // - `buf.as_ptr()` is valid for writes of `len * size_of::()` bytes, + // - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to + // each other, + // - both `ptr` and `buf.ptr()` are properly aligned. + unsafe { ptr::copy(ptr, buf.as_ptr(), len) }; + ptr = buf.as_ptr(); + + // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()`. + let layout = unsafe { ArrayLayout::::new_unchecked(len) }; + + // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed to be + // smaller than `cap`. Depending on `alloc` this operation may shrink the buffer or leaves + // it as it is. + ptr = match unsafe { + A::realloc(Some(buf.cast()), layout.into(), old_layout.into(), flags) + } { + // If we fail to shrink, which likely can't even happen, continue with the existing + // buffer. + Err(_) => ptr, + Ok(ptr) => { + cap = len; + ptr.as_ptr().cast() + } + }; + } + + // SAFETY: If the iterator has been advanced, the advanced elements have been copied to + // the beginning of the buffer and `len` has been adjusted accordingly. + // + // - `ptr` is guaranteed to point to the start of the backing buffer. + // - `cap` is either the original capacity or, after shrinking the buffer, equal to `len`. + // - `alloc` is guaranteed to be unchanged since `into_iter` has been called on the original + // `Vec`. + unsafe { Vec::from_raw_parts(ptr, len, cap) } + } +} + impl Iterator for IntoIter where A: Allocator,