From nobody Fri Dec 19 21:47:58 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id DE0C11EE02F for ; Tue, 21 Jan 2025 10:14:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737454499; cv=none; b=MPflyIRvHpVwhrvMf5SgGaZsInqGqpp4LOcxEnAItH7nMP8KvLeFDKW87rxnFfqpuR0p5ps8GtfLpkP/Gyl39SYOa6lQt6zwy0hjGcibj0eEIWvsDX19yH9MzCPOu75NlFcr96oEsGKTRttOD8rHFOPF5eNXj9Jpo4OzRoV3sKs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737454499; c=relaxed/simple; bh=QcvMePb01qsI3uDCbJIiUKFZQvo7bTT+ZxSEpObE9CA=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=rbv9Ovm/wk5RGoJ/QOgBgMcbuTsFt80WOrt3MhdryWWixdH4PiVLqTIfE486+2I+X/yJ4RPgECJqGH3ltcTPMISuqzHs44tSStDdODVZmFGh6t1P6+rpOlUdPAlMC1cFyDNqbZQo+XU/6sHVZY3NVFlUOjOjE0Fvl56iZoIdbu4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=mV2u46R/; arc=none smtp.client-ip=209.85.128.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="mV2u46R/" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-436248d1240so26776795e9.0 for ; Tue, 21 Jan 2025 02:14:57 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1737454496; x=1738059296; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=9QT/leOgkzm+5YCLe0q+PoCNw1wR649abqBqykClqDg=; b=mV2u46R/yJmug6gkc8+KrR7Iij6ZZ7rTdh3A5hYVHVGvD/yZH4HJtSBIOKsZKSoX2y Ci4k07u2AEe6gr/vgIA6WIe2Lci6Iq4ruRcgxLA3dttnb5b4xQz/bCaMKINfbgyT0Oxm JUtwMWQoIEOKzUFqDRb9PJvRsQQuFnOdsbOsAFzJH7qoRXXibbm3vhX98eNE25mfL9xh 7Ij4bdpSNRvEAc7hklZlKaHSZrJ6HpoBjoMXiLIaozECAh4nJ151R7J/A5BKQNSG5lCd bs69Ua1H3QVXnrClB4GEDZc5QGAn4zW1h8o5Jn5cHzshFqgJneJUL2fKOZpH/Qz4l7In Jc+Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1737454496; x=1738059296; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=9QT/leOgkzm+5YCLe0q+PoCNw1wR649abqBqykClqDg=; b=DSpeY0U2lY5i4U32B04YWzbNF43pYt/3dN32bVF4QAzdibNjMUUxR4fmzvN7hSnwpG BCARhIE7DuD0onqdS3Uo10T/jxpgTbfoSZrG+0LL2pyeTss0jdm8Q30LKg8mNwnLbETE kWrFwn//ZB4slsfw45MXkD5dhH3Nj5xunXLotGgq7tBHBIRI3uCoZriDmhSaUwcPYczZ +BVsW3emEQ0EuzjQKXrNKWb9o5HdzgFv2WWvsu8yyVcThXoYvCa/Mh4Z+bkfoy2mA+Jn /HagOm+NU66eX5Pz4m5/1oPl51Pbf5xsQ2/U0kAOOUYjFfgNMtN70rF4THTfChUxmZ+t L01w== X-Forwarded-Encrypted: i=1; AJvYcCVeNunokxfMefP/h45COltZoMmtKKKDX5OSeAvpSRX7e1gGAhRBXeVBUBjC0V0TBU0BZDYAcsHO6bYD6L0=@vger.kernel.org X-Gm-Message-State: AOJu0YyXgk7InqqJY6zJ6h6jZBsxmXuJqf8VK3Ls82yBrRUPk5P+T/Iu rNHmgIxwGNTl6ENG5ZWRLGWThQKEG1BHjoLAKY6d3buXfM7IC+b92AaJ1t37G9hTHnws11UXzZq KhXwcPV4EzvRzNg== X-Google-Smtp-Source: AGHT+IGAUonogQFaQBQyAo/7xnuOYmVSLh876dgCFpC+TJFN3LLkuSlpp0Gdz/d57A82Abr9Ui+X2mDUkliYI3Y= X-Received: from wmbe24.prod.google.com ([2002:a05:600c:5918:b0:436:7123:f80a]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1c21:b0:434:fd01:2e5f with SMTP id 5b1f17b1804b1-438914391bbmr161655435e9.29.1737454496385; Tue, 21 Jan 2025 02:14:56 -0800 (PST) Date: Tue, 21 Jan 2025 10:14:23 +0000 In-Reply-To: <20250121-cursor-between-v2-0-1b24cd377618@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250121-cursor-between-v2-0-1b24cd377618@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5148; i=aliceryhl@google.com; h=from:subject:message-id; bh=QcvMePb01qsI3uDCbJIiUKFZQvo7bTT+ZxSEpObE9CA=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnj3OaZ7fiB0Cn8y/oE8RCThYSe73mEvafaqVKF jtF2Ulb0diJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ49zmgAKCRAEWL7uWMY5 RhqqD/9uurj4xTaNFCDM699pbobOVw4NN+RkB+Xx+qLQgr+ru6XnIqfJqnsitee7LGQqaEhmtlO BfrZgbzNgf9eGkY3MemRA7ZA3EY+KBWAAMfYDKqbgsP8JDeKVqUutcaLggueNc/UuRiM/3Xbg5L XVWb5lIIRWZ+X9/3g9OciY8f8ihG1UrkT3KgbZlj3hWOfO0vLLTGb5FaX9K6V5owBgWpQBqZoM7 EZqUniAid2MzE57ZnRSbq+/VVyWwWOS+UQPPSlEIXGJnCmM5DGbxoyIpBIT2Z+VTDD8qsGjwcCv HjD+W241r4OM5GHkmsDc7oak3XEauQEMFR7gy0RgFuJFB5QLvC6iubQW379SOXOpCkAlc8sgGRo 2zX+fflk34UmtrG244FLSOa4VybaZ1if/AW8q13cD+l75+V/7K5zAymTS7EsA3V5msnUDjNeQnc 8rF7rVbUTRJF7ABuFOvrFTMO4rwO1zRTA+VUbSbX6oCZAt6QXX1OKV1i5O1yVrd06hpgpv+tfoy j18+NNZWQE4gHxy2ADGZr16ZOwTWZqI7/IA7FVePdbNPjuaE0JnIL1JzV0XZn7/p4ntO54Nd/XK EXw3pg8APLqZCGleHiE6jjMjuxTIsRyo/ra1WPDI7ytSshejBEsuqiz11SUTZF9kvaPUxf0qXVD SsP7kaz1TxVffBA== X-Mailer: b4 0.13.0 Message-ID: <20250121-cursor-between-v2-1-1b24cd377618@google.com> Subject: [PATCH v2 1/2] rust: list: extract common code for insertion From: Alice Ryhl To: Miguel Ojeda Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable To prepare for a new cursor API that has the ability to insert elements into the list, extract the common code needed for this operation into a new `insert_inner` method. Both `push_back` and `push_front` are updated to use the new function. Signed-off-by: Alice Ryhl Reviewed-by: Andreas Hindborg --- rust/kernel/list.rs | 70 ++++++++++++++++++++++++-------------------------= ---- 1 file changed, 32 insertions(+), 38 deletions(-) diff --git a/rust/kernel/list.rs b/rust/kernel/list.rs index fb93330f4af4..97b3599b7207 100644 --- a/rust/kernel/list.rs +++ b/rust/kernel/list.rs @@ -245,8 +245,20 @@ pub fn is_empty(&self) -> bool { self.first.is_null() } =20 - /// Add the provided item to the back of the list. - pub fn push_back(&mut self, item: ListArc) { + /// Inserts `item` before `next` in the cycle. + /// + /// Returns a pointer to the newly inserted element. Never changes `se= lf.first` unless the list + /// is empty. + /// + /// # Safety + /// + /// * `next` must be an element in this list or null. + /// * if `next` is null, then the list must be empty. + unsafe fn insert_inner( + &mut self, + item: ListArc, + next: *mut ListLinksFields, + ) -> *mut ListLinksFields { let raw_item =3D ListArc::into_raw(item); // SAFETY: // * We just got `raw_item` from a `ListArc`, so it's in an `Arc`. @@ -259,16 +271,16 @@ pub fn push_back(&mut self, item: ListArc) { // SAFETY: We have not yet called `post_remove`, so `list_links` i= s still valid. let item =3D unsafe { ListLinks::fields(list_links) }; =20 - if self.first.is_null() { - self.first =3D item; + // Check if the list is empty. + if next.is_null() { // SAFETY: The caller just gave us ownership of these fields. // INVARIANT: A linked list with one item should be cyclic. unsafe { (*item).next =3D item; (*item).prev =3D item; } + self.first =3D item; } else { - let next =3D self.first; // SAFETY: By the type invariant, this pointer is valid or nul= l. We just checked that // it's not null, so it must be valid. let prev =3D unsafe { (*next).prev }; @@ -282,45 +294,27 @@ pub fn push_back(&mut self, item: ListArc) { (*next).prev =3D item; } } + + item + } + + /// Add the provided item to the back of the list. + pub fn push_back(&mut self, item: ListArc) { + // SAFETY: + // * `self.first` is null or in the list. + // * `self.first` is only null if the list is empty. + unsafe { self.insert_inner(item, self.first) }; } =20 /// Add the provided item to the front of the list. pub fn push_front(&mut self, item: ListArc) { - let raw_item =3D ListArc::into_raw(item); // SAFETY: - // * We just got `raw_item` from a `ListArc`, so it's in an `Arc`. - // * If this requirement is violated, then the previous caller of = `prepare_to_insert` - // violated the safety requirement that they can't give up owner= ship of the `ListArc` - // until they call `post_remove`. - // * We own the `ListArc`. - // * Removing items] from this list is always done using `remove_i= nternal_inner`, which - // calls `post_remove` before giving up ownership. - let list_links =3D unsafe { T::prepare_to_insert(raw_item) }; - // SAFETY: We have not yet called `post_remove`, so `list_links` i= s still valid. - let item =3D unsafe { ListLinks::fields(list_links) }; + // * `self.first` is null or in the list. + // * `self.first` is only null if the list is empty. + let new_elem =3D unsafe { self.insert_inner(item, self.first) }; =20 - if self.first.is_null() { - // SAFETY: The caller just gave us ownership of these fields. - // INVARIANT: A linked list with one item should be cyclic. - unsafe { - (*item).next =3D item; - (*item).prev =3D item; - } - } else { - let next =3D self.first; - // SAFETY: We just checked that `next` is non-null. - let prev =3D unsafe { (*next).prev }; - // SAFETY: Pointers in a linked list are never dangling, and t= he caller just gave us - // ownership of the fields on `item`. - // INVARIANT: This correctly inserts `item` between `prev` and= `next`. - unsafe { - (*item).next =3D next; - (*item).prev =3D prev; - (*prev).next =3D item; - (*next).prev =3D item; - } - } - self.first =3D item; + // INVARIANT: `new_elem` is in the list because we just inserted i= t. + self.first =3D new_elem; } =20 /// Removes the last item from this list. --=20 2.48.0.rc2.279.g1de40edade-goog From nobody Fri Dec 19 21:47:58 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D404A1EE7CB for ; Tue, 21 Jan 2025 10:14:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737454502; cv=none; b=Eo3a3CyskxEY/5cFVSsqDCpcDsOvCgPVYGthK3IqOTMCOn6fHA0p3zPl3YOY02ExlAnV987ppE5xh1EGdCwE5y6yOIAm2AHuRUDdDCs+/IunqcbGq7Y1hG7mZTA0TapJgsVU1rocu/9dZHBu2/6lYvgL3KoKq3I/yRuHGQYj8vU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737454502; c=relaxed/simple; bh=YAa0Xd/y5nA6HKIEWD6ZAFpkLjnkYG1Be72E8SZ47wI=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=mannT46cefG5oQXOD/Q4T7bL9B1E1esa85WtvygHgEbxoyhD2n8Q+pkVykKPa+5tFqGc3DhYOf0CAZYoXlbgYvccN+6+1MbhivhXlXDEvWWbTNmWs3gXWY4qi6+l6WPn5IePKcxJAZ/5koXkYB4eZ7g+QMZoya3x0ynC8pOQRCc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=OFZLtqDe; arc=none smtp.client-ip=209.85.128.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="OFZLtqDe" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-4362552ce62so28303065e9.0 for ; Tue, 21 Jan 2025 02:14:59 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1737454498; x=1738059298; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=D4ya++wD2l9KD/DO+Dbw2L7cYN6dIxoseiq0xEJfP9Y=; b=OFZLtqDegXHRDGmtuGbqz0/c9Sp8qoMzp0qL3TPzOzMjA4TfNbcmSivWyrico7VGAL qoBQ3DCb/W585AQDAacpZIeznHuG9vHaKO03iCHOM48/7l9DfXi7HJ97CtwNIlTkBqRx mqS+Wrw7dYSFG1Gj/ZZixrQ/agdQCUkIWXt9FaYFHD2qeh1/vritHNOmNxZcWNWSAPEn 14LABY//qAOJ4snVQPvW00LezFO/M9mVr3HWuKx4hItijd/+BwXHRpQfEHFUqMlCZA8H 3veJAG19ymrn6JaE3+78r1mR9cZKFoMr2cBgthbkTouGbg9GfpmkY/X6giv+JrVjqmpz lDfw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1737454498; x=1738059298; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=D4ya++wD2l9KD/DO+Dbw2L7cYN6dIxoseiq0xEJfP9Y=; b=dQFEl6Hb0HbudHPsTeZRFS0I50Uncgez2aYV5w6Me4jfGsP6yTLf5B6Nioe8HdFFyQ mcb+32omJsTlorKznlb3VU9i3+ZTMrTVCM/DagnTnyzJT1IKmsU83u2ntu5hxcJ69Rqv dAYDy0wOu2gWoiH9GrorHFzjjOjI2/64AV40FGxevdyKCvXDLbiiqGvCVbvHC44eCu+B hkztiiQa3OBQEjeySaBt3gC+4JU0rM61SHRxpcA78dARcCSguxPlY9t9/mV1AGXS6lWE aNFg2b+3RBI1Gcbl19PNMKQ4cvo27y4La5dClEVztpoKr62gZRX4R5o4tZYNyWlcn4Sz fs4g== X-Forwarded-Encrypted: i=1; AJvYcCU2qSGS3NCKxeKnKD2nZ8yT4q0Wz1HYqnigOp6/aBE2McaiG0pw5lVJpxSG0u2ePp+gBhUBRRsHhGRUBTI=@vger.kernel.org X-Gm-Message-State: AOJu0YwFQcwKgy8a1VyAS4on71o2XhnHoYqbEce8NjVrRUt2YjV2zUNV shNH50pq4Vfzrna8V9o3hrOZZlRhXAp6+ASxSJxr17DOEr20L/GAdQMpGJ72TeQObYb47/tYUGk 4TZ0j7XbqJdh8pg== X-Google-Smtp-Source: AGHT+IF3qsqoT9CNqHCtxLfPHjzzz7x9atGPwDDcwjJGt2AYlCg3OxDpZ1GGwalDoDiFaUzfsXNhfEqV2DX2uYw= X-Received: from wmbjx9.prod.google.com ([2002:a05:600c:5789:b0:436:e723:5be0]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1e1c:b0:434:f0df:9f6 with SMTP id 5b1f17b1804b1-438913bf655mr160034015e9.3.1737454498359; Tue, 21 Jan 2025 02:14:58 -0800 (PST) Date: Tue, 21 Jan 2025 10:14:24 +0000 In-Reply-To: <20250121-cursor-between-v2-0-1b24cd377618@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250121-cursor-between-v2-0-1b24cd377618@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=16101; i=aliceryhl@google.com; h=from:subject:message-id; bh=YAa0Xd/y5nA6HKIEWD6ZAFpkLjnkYG1Be72E8SZ47wI=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnj3ObFF6rcWiF70NSLcer9quCzPbwUoU/fUGEW ydSn6l30M6JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ49zmwAKCRAEWL7uWMY5 RgaXD/9yvCMoEPSs8L+c/STBPgBIpncOHEF3Su6WtJQZsswMIE6qh21B8mpSm6IKbLKvjPu4N6z 7j/KryTw8ZfyMyBHWjWe0CSfGoGmHc6M+zz+r05LOMMnTOzwo5H3ZeaED7s5T0/Qnu4dl6SOVkd s5MW6fBNANEVVdhH3gy19D3BMTzo/wT39qf+m2N+neHFUNwaVQzEDyT2H/YpBNV0jBhiDIiAjWs 4BzUa9eYsyMAqQWkPVA7UetrKRJBljJRbAyKeBzANR7pk5/vm7efFuuWU2rLdyY+AW4o+TPxCVe ZAxC+6xFSdL49JnQ8XW62TKW4UsIdNwxvRedkHLZR6htzyF8H7yYK2hDXDgyXKrnw+EWRtF2kxi itrdt1Z09RgpLqm71BSy8G870sLV1AcTQGHWkHAd8BZZnsFsqZAkovmByROX2EFB82D9PwZOHRA VY9CRj28yBzqlWE0h7ExciR4+vSLYNnmfc8jvcegax5KNC6mIALBZaAda8K+oUYPedcucQi93Up iKMGCX1OrES3CrX5zNMsb8N+/7ljn1IAe5K32o35Dg9pstJRYwgRvVpGfr/LEossWOIZCaqonf8 aiNayQWzt/DmEWbLfSo7iqBp+g16WbOne7iF97b3oY+vxSjQKw+EV6qn8CKXi9a4Wc7xpRCoa32 mwDmQSCZxhGFMvw== X-Mailer: b4 0.13.0 Message-ID: <20250121-cursor-between-v2-2-1b24cd377618@google.com> Subject: [PATCH v2 2/2] rust: list: make the cursor point between elements From: Alice Ryhl To: Miguel Ojeda Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable I've been using the linked list cursor for a few different things, and I find it inconvenient to use because all of the functions have signatures along the lines of `Self -> Option`. The root cause of these signatures is that the cursor points *at* an element, rather than *between* two elements. Thus, change the cursor API to point between two elements. This is inspired by the stdlib linked list (well, really by this guy [1]), which also uses cursors that point between elements. The `peek_next` method returns a helper that lets you look at and optionally remove the element, as one common use-case of cursors is to iterate a list to look for an element, then remove that element. For many of the methods, this will reduce how many we need since they now just need a prev/next method, instead of the current state where you may end up needing all of curr/prev/next. Also, if we decide to add a function for splitting a list into two lists at the cursor, then a cursor that points between elements is exactly what makes the most sense. Another advantage is that this means you can now have a cursor into an empty list. Link: https://rust-unofficial.github.io/too-many-lists/sixth-cursors-intro.= html [1] Signed-off-by: Alice Ryhl Reviewed-by: Andreas Hindborg --- rust/kernel/list.rs | 331 +++++++++++++++++++++++++++++++++++++++++++-----= ---- 1 file changed, 276 insertions(+), 55 deletions(-) diff --git a/rust/kernel/list.rs b/rust/kernel/list.rs index 97b3599b7207..314222d12bfc 100644 --- a/rust/kernel/list.rs +++ b/rust/kernel/list.rs @@ -483,17 +483,21 @@ pub fn push_all_back(&mut self, other: &mut List) { other.first =3D ptr::null_mut(); } =20 - /// Returns a cursor to the first element of the list. - /// - /// If the list is empty, this returns `None`. - pub fn cursor_front(&mut self) -> Option> { - if self.first.is_null() { - None - } else { - Some(Cursor { - current: self.first, - list: self, - }) + /// Returns a cursor that points before the first element of the list. + pub fn cursor_front(&mut self) -> Cursor<'_, T, ID> { + // INVARIANT: `self.first` is in this list. + Cursor { + next: self.first, + list: self, + } + } + + /// Returns a cursor that points after the last element in the list. + pub fn cursor_back(&mut self) -> Cursor<'_, T, ID> { + // INVARIANT: `next` is allowed to be null. + Cursor { + next: core::ptr::null_mut(), + list: self, } } =20 @@ -573,69 +577,286 @@ fn next(&mut self) -> Option> { =20 /// A cursor into a [`List`]. /// +/// A cursor always rests between two elements in the list. This means tha= t a cursor has a previous +/// and next element, but no current element. It also means that it's poss= ible to have a cursor +/// into an empty list. +/// +/// # Examples +/// +/// ``` +/// use kernel::list::{List, ListArc, ListLinks}; +/// +/// #[pin_data] +/// struct ListItem { +/// value: u32, +/// #[pin] +/// links: ListLinks, +/// } +/// +/// kernel::list::impl_has_list_links! { +/// impl HasListLinks<0> for ListItem { self.links } +/// } +/// kernel::list::impl_list_arc_safe! { +/// impl ListArcSafe<0> for ListItem { untracked; } +/// } +/// kernel::list::impl_list_item! { +/// impl ListItem<0> for ListItem { using ListLinks; } +/// } +/// +/// // Use a cursor to remove the first element with the given value. +/// fn remove_first(list: &mut List, value: u32) -> Option> { +/// let mut cursor =3D list.cursor_front(); +/// while let Some(next) =3D cursor.peek_next() { +/// if next.value =3D=3D value { +/// return Some(next.remove()); +/// } +/// cursor.move_next(); +/// } +/// None +/// } +/// +/// // Use a cursor to remove all elements with the given value. The remov= ed elements are moved to +/// // a new list. +/// fn remove_all(list: &mut List, value: u32) -> List= { +/// let mut out =3D List::new(); +/// let mut cursor =3D list.cursor_front(); +/// while let Some(next) =3D cursor.peek_next() { +/// if next.value =3D=3D value { +/// out.push_back(next.remove()); +/// } else { +/// cursor.move_next(); +/// } +/// } +/// out +/// } +/// +/// // Use a cursor to insert a value at a specific index. Returns an erro= r if the index is out of +/// // bounds. +/// fn insert_at(list: &mut List, new: ListArc, idx: u= size) -> Result { +/// let mut cursor =3D list.cursor_front(); +/// for _ in 0..idx { +/// if !cursor.move_next() { +/// return Err(EINVAL); +/// } +/// } +/// cursor.insert_next(new); +/// Ok(()) +/// } +/// +/// // Merge two sorted lists into a single sorted list. +/// fn merge_sorted(list: &mut List, merge: List) { +/// let mut cursor =3D list.cursor_front(); +/// for to_insert in merge { +/// while let Some(next) =3D cursor.peek_next() { +/// if to_insert.value < next.value { +/// break; +/// } +/// cursor.move_next(); +/// } +/// cursor.insert_prev(to_insert); +/// } +/// } +/// ``` +/// /// # Invariants /// -/// The `current` pointer points a value in `list`. +/// The `next` pointer is null or points a value in `list`. pub struct Cursor<'a, T: ?Sized + ListItem, const ID: u64 =3D 0> { - current: *mut ListLinksFields, list: &'a mut List, + /// Points at the element after this cursor, or null if the cursor is = after the last element. + next: *mut ListLinksFields, } =20 impl<'a, T: ?Sized + ListItem, const ID: u64> Cursor<'a, T, ID> { - /// Access the current element of this cursor. - pub fn current(&self) -> ArcBorrow<'_, T> { - // SAFETY: The `current` pointer points a value in the list. - let me =3D unsafe { T::view_value(ListLinks::from_fields(self.curr= ent)) }; - // SAFETY: - // * All values in a list are stored in an `Arc`. - // * The value cannot be removed from the list for the duration of= the lifetime annotated - // on the returned `ArcBorrow`, because removing it from the lis= t would require mutable - // access to the cursor or the list. However, the `ArcBorrow` ho= lds an immutable borrow - // on the cursor, which in turn holds a mutable borrow on the li= st, so any such - // mutable access requires first releasing the immutable borrow = on the cursor. - // * Values in a list never have a `UniqueArc` reference, because = the list has a `ListArc` - // reference, and `UniqueArc` references must be unique. - unsafe { ArcBorrow::from_raw(me) } + /// Returns a pointer to the element before the cursor. + /// + /// Returns null if there is no element before the cursor. + fn prev_ptr(&self) -> *mut ListLinksFields { + let mut next =3D self.next; + let first =3D self.list.first; + if next =3D=3D first { + // We are before the first element. + return core::ptr::null_mut(); + } + + if next.is_null() { + // We are after the last element, so we need a pointer to the = last element, which is + // the same as `(*first).prev`. + next =3D first; + } + + // SAFETY: `next` can't be null, because then `first` must also be= null, but in that case + // we would have exited at the `next =3D=3D first` check. Thus, `n= ext` is an element in the + // list, so we can access its `prev` pointer. + unsafe { (*next).prev } } =20 - /// Move the cursor to the next element. - pub fn next(self) -> Option> { - // SAFETY: The `current` field is always in a list. - let next =3D unsafe { (*self.current).next }; + /// Access the element after this cursor. + pub fn peek_next(&mut self) -> Option>= { + if self.next.is_null() { + return None; + } + + // INVARIANT: + // * We just checked that `self.next` is non-null, so it must be i= n `self.list`. + // * `ptr` is equal to `self.next`. + Some(CursorPeek { + ptr: self.next, + cursor: self, + }) + } + + /// Access the element before this cursor. + pub fn peek_prev(&mut self) -> Option= > { + let prev =3D self.prev_ptr(); + + if prev.is_null() { + return None; + } + + // INVARIANT: + // * We just checked that `prev` is non-null, so it must be in `se= lf.list`. + // * `self.prev_ptr()` never returns `self.next`. + Some(CursorPeek { + ptr: prev, + cursor: self, + }) + } + + /// Move the cursor one element forward. + /// + /// If the cursor is after the last element, then this call does nothi= ng. This call returns + /// `true` if the cursor's position was changed. + pub fn move_next(&mut self) -> bool { + if self.next.is_null() { + return false; + } + + // SAFETY: `self.next` is an element in the list and we borrow the= list mutably, so we can + // access the `next` field. + let mut next =3D unsafe { (*self.next).next }; =20 if next =3D=3D self.list.first { - None - } else { - // INVARIANT: Since `self.current` is in the `list`, its `next= ` pointer is also in the - // `list`. - Some(Cursor { - current: next, - list: self.list, - }) + next =3D core::ptr::null_mut(); } + + // INVARIANT: `next` is either null or the next element after an e= lement in the list. + self.next =3D next; + true } =20 - /// Move the cursor to the previous element. - pub fn prev(self) -> Option> { - // SAFETY: The `current` field is always in a list. - let prev =3D unsafe { (*self.current).prev }; + /// Move the cursor one element backwards. + /// + /// If the cursor is before the first element, then this call does not= hing. This call returns + /// `true` if the cursor's position was changed. + pub fn move_prev(&mut self) -> bool { + if self.next =3D=3D self.list.first { + return false; + } =20 - if self.current =3D=3D self.list.first { - None + // INVARIANT: `prev_ptr()` always returns a pointer that is null o= r in the list. + self.next =3D self.prev_ptr(); + true + } + + /// Inserts an element where the cursor is pointing and get a pointer = to the new element. + fn insert_inner(&mut self, item: ListArc) -> *mut ListLinksFiel= ds { + let ptr =3D if self.next.is_null() { + self.list.first } else { - // INVARIANT: Since `self.current` is in the `list`, its `prev= ` pointer is also in the - // `list`. - Some(Cursor { - current: prev, - list: self.list, - }) - } + self.next + }; + // SAFETY: + // * `ptr` is an element in the list or null. + // * if `ptr` is null, then `self.list.first` is null so the list = is empty. + unsafe { self.list.insert_inner(item, ptr) } + } + + /// Inserts an element after this cursor. + pub fn insert_next(&mut self, item: ListArc) { + self.next =3D self.insert_inner(item); + } + + /// Inserts an element before this cursor. + pub fn insert_prev(&mut self, item: ListArc) { + self.insert_inner(item); } =20 - /// Remove the current element from the list. + /// Remove the next element from the list. + pub fn remove_next(&mut self) -> Option> { + self.peek_next().map(|v| v.remove()) + } + + /// Remove the previous element from the list. + pub fn remove_prev(&mut self) -> Option> { + self.peek_prev().map(|v| v.remove()) + } +} + +/// References the element in the list next to the cursor. +/// +/// # Invariants +/// +/// * `ptr` is an element in `self.cursor.list`. +/// * `ISNEXT =3D=3D (self.ptr =3D=3D self.cursor.next)`. +pub struct CursorPeek<'a, 'b, T: ?Sized + ListItem, const ISNEXT: bool= , const ID: u64> { + cursor: &'a mut Cursor<'b, T, ID>, + ptr: *mut ListLinksFields, +} + +impl<'a, 'b, T: ?Sized + ListItem, const ISNEXT: bool, const ID: u64> + CursorPeek<'a, 'b, T, ISNEXT, ID> +{ + /// Remove the element from the list. pub fn remove(self) -> ListArc { - // SAFETY: The `current` pointer always points at a member of the = list. - unsafe { self.list.remove_internal(self.current) } + if ISNEXT { + self.cursor.move_next(); + } + + // INVARIANT: `self.ptr` is not equal to `self.cursor.next` due to= the above `move_next` + // call. + // SAFETY: By the type invariants of `Self`, `next` is not null, s= o `next` is an element of + // `self.cursor.list` by the type invariants of `Cursor`. + unsafe { self.cursor.list.remove_internal(self.ptr) } + } + + /// Access this value as an [`ArcBorrow`]. + pub fn arc(&self) -> ArcBorrow<'_, T> { + // SAFETY: `self.ptr` points at an element in `self.cursor.list`. + let me =3D unsafe { T::view_value(ListLinks::from_fields(self.ptr)= ) }; + // SAFETY: + // * All values in a list are stored in an `Arc`. + // * The value cannot be removed from the list for the duration of= the lifetime annotated + // on the returned `ArcBorrow`, because removing it from the lis= t would require mutable + // access to the `CursorPeek`, the `Cursor` or the `List`. Howev= er, the `ArcBorrow` holds + // an immutable borrow on the `CursorPeek`, which in turn holds = a mutable borrow on the + // `Cursor`, which in turn holds a mutable borrow on the `List`,= so any such mutable + // access requires first releasing the immutable borrow on the `= CursorPeek`. + // * Values in a list never have a `UniqueArc` reference, because = the list has a `ListArc` + // reference, and `UniqueArc` references must be unique. + unsafe { ArcBorrow::from_raw(me) } + } +} + +impl<'a, 'b, T: ?Sized + ListItem, const ISNEXT: bool, const ID: u64> = core::ops::Deref + for CursorPeek<'a, 'b, T, ISNEXT, ID> +{ + // This can't use `ArcBorrow<'a, T>` as the target type because 'a is = too long. It would let + // you obtain an `ArcBorrow<'a, T>` and then call `CursorPeek::remove`= without giving up the + // `ArcBorrow<'a, T>`. + type Target =3D T; + + fn deref(&self) -> &T { + // SAFETY: `self.ptr` points at an element in `self.cursor.list`. + let me =3D unsafe { T::view_value(ListLinks::from_fields(self.curs= or.next)) }; + + // SAFETY: The value cannot be removed from the list for the durat= ion of the lifetime + // annotated on the returned `&T`, because removing it from the li= st would require mutable + // access to the `CursorPeek`, the `Cursor` or the `List`. However= , the `&T` holds an + // immutable borrow on the `CursorPeek`, which in turn holds a mut= able borrow on the + // `Cursor`, which in turn holds a mutable borrow on the `List`, s= o any such mutable access + // requires first releasing the immutable borrow on the `CursorPee= k`. + unsafe { &*me } } } =20 --=20 2.48.0.rc2.279.g1de40edade-goog