From nobody Sat Feb 7 18:03:38 2026 Received: from mail-wr1-f74.google.com (mail-wr1-f74.google.com [209.85.221.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 ABE8B20DD6D for ; Thu, 23 Jan 2025 11:01:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737630106; cv=none; b=Fl+wtZY3lykZ7o7Qzn9+3TqEbqjUfdH8B0UhcW/h73zxxCtKPOejqHPcOR2ygWJuYpZk8rTFlc7Bh4Ib9HgCEFH6UXevpS5u24b0Bl1HtSWxILWtZKnTUYbSbcIjCkXquX09YvjDMsqEoywM8ccspbxPexoJ5Z4UUAm6hpiMMl8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737630106; c=relaxed/simple; bh=ttAjlADe2z9qvjo9BjzNh0c6cDOy6zkyaaJyDb6M7mE=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=EiLxJaB95mahxeg4zIHZH1gEBQ1lhRiJsCz7ffvFOIs4sauVyZBkOOC5XNVGm2FYyfjnIn6KPVPUDw6/H5syplOwMlBZga461Xr1Ju74TfW0Q67Gpd+8lGetyQP2lxYCrDsh3DGmRLrZNP7SXpR0PmCvkjCTrgctj9tjvppfzNs= 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=NzBjoqGK; arc=none smtp.client-ip=209.85.221.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="NzBjoqGK" Received: by mail-wr1-f74.google.com with SMTP id ffacd0b85a97d-385d7611ad3so415498f8f.2 for ; Thu, 23 Jan 2025 03:01:44 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1737630103; x=1738234903; 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=+dndn/M1tpjjYj5fSrp/cB2j25FLB5R2IYqQNLwoLE8=; b=NzBjoqGK40bFjLOrKE49tcMhP+UjyhD9SHoUsohjQ+GlzCZB1eAbl+Li6JHdEsjSPr RxKKpyrqPI8+bEr42dTsJJqrTjHtHKGpmWy/WnEia5d/usWSfLo7GtoDlGyaL4XcDVvz WMTnedzOHlsgk/StOoeani2FKRYKZZmyrnIyl4IL7a5EEQ6DIkSRRPv+sEE2r1JWcmQ2 J3ngy8SYVWidTYNEHfTKhUs8YMVduex3y5e0m9YesL2ftNXOUawX137Ad8Ot9+iNTdrd b19WGGAem7o/Qy9T389ASSCc46NemPb+Sf8VLS/MuYRl2Twkx77WMtHL+L3NLvKyrOlR BJQQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1737630103; x=1738234903; 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=+dndn/M1tpjjYj5fSrp/cB2j25FLB5R2IYqQNLwoLE8=; b=srvc2taawLZzQPRQkwYft+05c+v1olIfIh1jILLC8jAPyX/WK1jRX50QBVL1yqDemm ZPbBqjPUK7huLmOPKjvxX9SNg+rwBIg+sq6sJbZCFrYSjpBec9mDgDReD+A2cnrYB0RH YmQECZuBEvLmtDfOf3BISaQT5l2B4PkTlQO+GtMmXFfPrByyy3UIj27LhaHwn5NAxAD1 28Co2ZIpWhXrwgXSDDFFhD8HQ1E6C6VAO3P8L9TDJC1I6YJw95Cp/05716BmIDq0Of7Z TSug73P+UY7JSYT6P5XMxPth+h55rDggRxI4QgMvHlRofZhP9+5um/IKEdT0qzJf3gJc MssQ== X-Forwarded-Encrypted: i=1; AJvYcCX7KEMp5N1V1HbpZN7rXnxry2QKqrAM8KCwH0OYiWapSjcRGlJvQYWnaLX3QsQRFIOg0h1mH00OtkFtJQ8=@vger.kernel.org X-Gm-Message-State: AOJu0YzUbNAR2e8x9y1+xOJZW0kxChKAYwIpssA94eqT4LIdOXEXxooZ q2cEWyoz6YP2t5ZBKDeVbeFiCO6xvdcJXaPGXObG4xxTAUdicYm0k65EXz8Diva7BLElPFzSBL/ rmaDQYG28er2GOA== X-Google-Smtp-Source: AGHT+IFcs1NysCk7NTXt1fPRf4X8MeFSRHghuPWe4NuWV9VPmxI5sbdWCwMoJN2N9m3N3ouEjegtdl3e3AGopJE= X-Received: from wmo11.prod.google.com ([2002:a05:600c:230b:b0:434:fe2b:fea7]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a5d:64a1:0:b0:385:f44a:a53 with SMTP id ffacd0b85a97d-38bf5655b07mr19847881f8f.4.1737630103125; Thu, 23 Jan 2025 03:01:43 -0800 (PST) Date: Thu, 23 Jan 2025 11:01:08 +0000 In-Reply-To: <20250123-cursor-between-v4-0-cb06698db94c@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250123-cursor-between-v4-0-cb06698db94c@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5247; i=aliceryhl@google.com; h=from:subject:message-id; bh=ttAjlADe2z9qvjo9BjzNh0c6cDOy6zkyaaJyDb6M7mE=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnkiGR9pgp4rz9AM9cR7S7X9DMcbuThaKSZozy0 GzAVhD7tFOJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ5IhkQAKCRAEWL7uWMY5 RjVqD/91c9X6u2GDownNFNq7HuXmbGZP2azaKllUkWXG8Fwniz5/bNCPWopMNZ3occ9Ce71bKjw IDqDDTiA88XTTO5uSVm1izMiwjrM5GDxL1EXlV6yVEVkA0wcKlmoa8Z1Izj/6PehbfvCIOQn097 Biebmwt6l34XOQBoLaDXzzzAjdl8AQdytQzQd0vtw2PVin+XRnu2F5FUnuT3993JGdg/ZQAF7d0 HkPepBc+WIX6eSFx1D1ZsZ0DVH8v5HGMZMoJyLW02P84zajTPxxSjXHZO+OVDcsoMqOqUtEfsR2 G3TVQ2/qr6jz0Rtmaope/DKKPyWnr/HvwzTSkIlgmpvfad9Kppo0ly/x+bzLsYtEbia3FDujAYa IlK4UochJXh0tYSJFWuOk2tsUbNVh6zI3tSpfu9JbU/gynYCwq36t9S5zh23xuIA7IXtK0SkpPX ZhRoPdElE3OrKt6D0wMdBrTJyZWmom8TWoqWRPv9/OhqRHv8CJSnQxRt/Ldde1LF9k4Mx5U+ppw BUjymF8KYgz1/XAIs1QmTGgIWr66zm7q5pGj9J76n7V+9sbG0WuElG61cG3cagzEzeWcjK5dvf8 +eoNudGRBkL91SdXVhiX3YRMzEXfhv2jeyEJbhHjoSIMWB89/e8tfHXRDqGWakaagLF4U7eEWt1 cD4sKgtCLhCKqWw== X-Mailer: b4 0.13.0 Message-ID: <20250123-cursor-between-v4-1-cb06698db94c@google.com> Subject: [PATCH v4 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. Reviewed-by: Andreas Hindborg Reviewed-by: Boqun Feng Signed-off-by: Alice Ryhl --- 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.1.262.g85cc9f2d1e-goog From nobody Sat Feb 7 18:03:38 2026 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (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 74E8120E021 for ; Thu, 23 Jan 2025 11:01:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737630108; cv=none; b=iPjWufeY5wf1bloyCuAUj0K1EEz+ElTa5j6KH6rDQ0ZgyhN8WvREholulcavJTE5xogByz7OQBuNwo7d79idxsHt7vMEgkoRdDg7H/Ozm+sJUihEdUTqsqW/2iTOkAgb3o7LtH40bLQI7ksgnICzhrXJ3DxVQ4FW7Z0/lU+Beu0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737630108; c=relaxed/simple; bh=8gUAK7/7eXcXwtwPNMbFGWORoWgSfmFE26RlCQmmpnw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=XxkKrc5RU+ta0pY8r5+M+WLfQJc4qYjen9iNM/ZVs3CncZRCrhf2joc3MM94owG0xb5Qm5Es3EkBrGoIr2Hf9vJIZCo+ZCI8A6jAA9bEMrnbbUqNsOuJdeH5iB4YP7aroUkW28WeI250Btx4+4qnsC4oqnnExo/SwcfTbLjXQ0A= 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=juG0wD6u; arc=none smtp.client-ip=209.85.128.73 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="juG0wD6u" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-4388eee7073so9172055e9.0 for ; Thu, 23 Jan 2025 03:01:46 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1737630105; x=1738234905; 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=9XTXYCK7WnevgyfO2tx5d7nnFYECwGZUA9UP3HhSJ3c=; b=juG0wD6uSi1ixFZFBj6pgyT1fKZsI090ol6wu8212jfNgGppF7uN2oBPNsohMkTSCA w4XuDjyjJWnckzEsz02nM3jdN+EyIPVPfgXYpRLdXgD3VgGBfP7S1+OrAb6eo8kksIHz 56e8MAWKkcy9rHi249NyHhz2lYCW7DBEJAw5gsBBS5UfN5qYOFvJKTEu7r9Ig/eUaZyo zBttKtHVePJ9LM04xOJ/lgpzSHpEM75TSIl/wFNLa+cV88xVpbQ947B658djmNghZ6aS uhfvJo5K0qEY3VG7VXf/RNYygDY51XRvVaSL71+CQ8O+xrREoN0VVH6ObtopmJ+87Qbo /jdg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1737630105; x=1738234905; 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=9XTXYCK7WnevgyfO2tx5d7nnFYECwGZUA9UP3HhSJ3c=; b=UHF+xPQ5WZSMecr7sPy/kOUs9isa6Ginja+FyiQg6NvZ3xB1GrffEjpCQrbPiNSUDJ eANXdhjOixnh8siX5kAV67h1ewBfrXr/MUtnuXqd+tE2GUGA7Gsd9NHKqvUcyOx7jhXK MPpd1W7ceXWEhSwCo7c7IH6Xks/OwqLhKKwWv/9zM73V9HG8oZQMYY75R2sZ2vRN5L5Y F6WztGJG7i10WtZpNW1CD3giMK3/7W8dW3kbG57cN+HPM7aVte3e6nsEZDQcBMtKSD13 5mA4Dqr40vCCNNu0xk0gb0uAIXplooRf4NR/Qe84AUDu4VXhFITFkAMKZT3JlwGXQh0u CChg== X-Forwarded-Encrypted: i=1; AJvYcCWR+NuvVSUhpYYvyV29dUkFIkZoh9XVZOtAVP8Zyxq9HK0AUJqYJNXCL/n4XTmisv3ltV9Rh8q0o53OqmA=@vger.kernel.org X-Gm-Message-State: AOJu0YyD39FiEAx+xOzytsr2TTDxPvZTKxLTvuTzlATkxEQLNxz07RPT 6cJZcPkYBG5x4FA28jAfqO7Ggz2qhpG4Xby1iu3eainCKhv/CdsgT2tlhkFf0l9xic8TiSLg7wz 1aEWOad3l47m7ow== X-Google-Smtp-Source: AGHT+IFGOL6rkA2a1sZ96eXbtU/9c+XWA017wOY71visxxWNewAjASw+pzsy5OmsGtJdXwFXhjEiPx+QpLQb3pQ= X-Received: from wmoq19.prod.google.com ([2002:a05:600c:46d3:b0:434:a8d7:e59b]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3206:b0:436:fdac:26eb with SMTP id 5b1f17b1804b1-438b885272dmr25175625e9.7.1737630105185; Thu, 23 Jan 2025 03:01:45 -0800 (PST) Date: Thu, 23 Jan 2025 11:01:09 +0000 In-Reply-To: <20250123-cursor-between-v4-0-cb06698db94c@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250123-cursor-between-v4-0-cb06698db94c@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=17643; i=aliceryhl@google.com; h=from:subject:message-id; bh=8gUAK7/7eXcXwtwPNMbFGWORoWgSfmFE26RlCQmmpnw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnkiGRTBq1ywyRxnIwDvvx8jPAn7F+e82BxGi+c 8//gkh3OyqJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ5IhkQAKCRAEWL7uWMY5 Rg3eD/4+d13MaW2GO261lQ3SbPSoUATkzDaq1Q546bOD7tsn9xL7z+eFKBfOSLfoptfFiZD1azt JLWyTzoXNLtcclWHg9omPeHWnRSUYEEKa6VJ1pNQPMaGUlRgUP0j2KcKe4RlGPMJ7RGqI0Mb1PD whgTQwPhcmm8lkIuKg84lyx6/B+yqYiPmluqmw4jDL2kmljyAMVugxcmlyACWOFyDn7aHEIPYVQ P2jli2QWu4YUyoq6wAO3oDvLDykeU+H4tMTo+dQUN8g9xrT7mpG497Z+XSUg9exdYOx8WQ+feMi JJNqJiYjV6M841YYfVLDooZJFDC9lOKEZCchOCR1nLjRps0uhsHLbNqbjIqumKxlyWdBraPnzrX z0v8ZwMI3475Yb8dYt54xsyA+LEJcxmZG3wjngw+F08lzU/x25zqlYu8j4UALq2rU6Dl0ZnewDe NxQ3OrNBrtBxbULjE/rrZ9vphuklR063UoBmFOM4QII2xOVjqRE3D4AoaP2LKEaWKzZeEuWdtWg vTWcGZkIzSx2msI/qeQfQ5LvoaXr+lhh5Tdc2qe1/Fu+0IOkzR/kqCzDilBbfECn/HFr821kn1X EOi7kY2RvSpFFRrsJy/JreP3bST/O3xM+B3N3VzRSJNpJip6QpaK/sDmLySN+5DKnXjTPyv8PEf /11PrYVsDF+Smeg== X-Mailer: b4 0.13.0 Message-ID: <20250123-cursor-between-v4-2-cb06698db94c@google.com> Subject: [PATCH v4 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] Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl Reviewed-by: Boqun Feng --- rust/kernel/list.rs | 370 ++++++++++++++++++++++++++++++++++++++++++++----= ---- 1 file changed, 315 insertions(+), 55 deletions(-) diff --git a/rust/kernel/list.rs b/rust/kernel/list.rs index 97b3599b7207..b83016e5bcd9 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,325 @@ 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::prelude::*; +/// use kernel::list::{List, ListArc, ListLinks}; +/// +/// #[pin_data] +/// struct ListItem { +/// value: u32, +/// #[pin] +/// links: ListLinks, +/// } +/// +/// impl ListItem { +/// fn new(value: u32) -> Result> { +/// ListArc::pin_init(try_pin_init!(Self { +/// value, +/// links <- ListLinks::new(), +/// }), GFP_KERNEL) +/// } +/// } +/// +/// 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); +/// } +/// } +/// +/// let mut list =3D List::new(); +/// list.push_back(ListItem::new(14)?); +/// list.push_back(ListItem::new(12)?); +/// list.push_back(ListItem::new(10)?); +/// list.push_back(ListItem::new(12)?); +/// list.push_back(ListItem::new(14)?); +/// assert_eq!(remove_all(&mut list, 12).iter().count(), 2); +/// // [14, 10, 14] +/// assert!(remove_first(&mut list, 14).is_some()); +/// // [10, 14] +/// insert_at(&mut list, ListItem::new(12)?, 1)?; +/// // [10, 12, 14] +/// +/// let mut list2 =3D List::new(); +/// list.push_back(ListItem::new(11)?); +/// list.push_back(ListItem::new(13)?); +/// merge_sorted(&mut list, list2); +/// +/// let mut items =3D list.into_iter(); +/// assert_eq!(items.next().unwrap().value, 10); +/// assert_eq!(items.next().unwrap().value, 11); +/// assert_eq!(items.next().unwrap().value, 12); +/// assert_eq!(items.next().unwrap().value, 13); +/// assert_eq!(items.next().unwrap().value, 14); +/// assert!(items.next().is_none()); +/// # Result::<(), Error>::Ok(()) +/// ``` +/// /// # 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); + } + + /// 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, +} =20 - /// Remove the current element from the list. +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> +{ + // If you change the `ptr` field to have type `ArcBorrow<'a, T>`, it m= ight seem like you could + // get rid of the `CursorPeek::arc` method and change the deref target= to `ArcBorrow<'a, T>`. + // However, that doesn't work because 'a is too long. You could obtain= an `ArcBorrow<'a, T>` + // and then call `CursorPeek::remove` without giving up the `ArcBorrow= <'a, T>`, which would be + // unsound. + 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.ptr)= ) }; + + // 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.1.262.g85cc9f2d1e-goog