Received: by 2002:ab2:6309:0:b0:1fb:d597:ff75 with SMTP id s9csp466352lqt; Thu, 6 Jun 2024 08:41:35 -0700 (PDT) X-Forwarded-Encrypted: i=3; AJvYcCXE02kXvMITMwiVcC38tk0H7vdpwTjWx2SjFEaazcBcjGOyQ1vweBeX7PR1KnjDcEDg+9xpYHwHkiaqQ1f0Oq/A56JE3APCwAfSVfFZ0w== X-Google-Smtp-Source: AGHT+IEa4Lezufehs9BjKkd/srb2kYiU/VRr9RSQMe2NBkcBE63yy080YkFhytVpYCg4gUQgMd2H X-Received: by 2002:a05:6a20:4310:b0:1b2:1de2:7dfa with SMTP id adf61e73a8af0-1b2b7411647mr6522002637.22.1717688495154; Thu, 06 Jun 2024 08:41:35 -0700 (PDT) ARC-Seal: i=2; a=rsa-sha256; t=1717688495; cv=pass; d=google.com; s=arc-20160816; b=dlJki311xwSwaBXlk4xwwfanPg6U0clJn8y3us69XaeZ0GQQc4ItZ5lJ/7WYgAamxD E6D/WLtWRLXdCRwVm8shkmPx5ky31OqvUy9bKos80OWgC7HQ0nzcSHHpwdY57/2CdmIR u6q64nD2TYdNp1hioszsUFt4ZhGGq9j9AKhND+WnPC+kw8TdAfBZDWUQPXAwPDlCE6th fZC9XThtWhE0JyyMSJVZatv/+jCnITUbWRK/YndIGIoyvosOJe5t6M7k5u0Rf7c+SKum CSaB9/Lk7SZRVl8pKZeOPMeWXMG4bUEzhayJTYpVFIkvopMVh3M75UZjoTbtG9ynfMJL g3Bw== ARC-Message-Signature: i=2; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=cc:to:from:subject:message-id:references:mime-version :list-unsubscribe:list-subscribe:list-id:precedence:in-reply-to:date :dkim-signature; bh=APYLI2P2kRH4kz6ibkFnlfxP/kI8VygXGISUKHVqwxs=; fh=pVyaud/7cb262l8FoFnnT4kzFqomTgyNoeLpQUTnJZ0=; b=MPZ4Acbbjsu2fH1cbCHYVX91tjqROL5I7hK+mkuFrt73JgOQ7/V9yvh6o62GG8jcgF y6R8exE+S2N4HjmWdPLScT9arSkryTHKtXL63EMp1Q58fpagU5J1mgP8uDe0qhC0rSCh 6O4x/YfqcXxhY7V0DtgPs5fqyc4l7hSV9D3x8Su/DTLrkLurBVPDBcrvHYWJWU02gF5w npKajk3EZukF3qd1YUiJ1JgUPnxpZ+bOckYVR/IlXt9lYoVXZkKUhXbu1UMT/qCp5ctG 1D3Z3e1BbE8NJg4Ua+P92rh0Tt6AjksrMuWskttWC1fmhuAhh2eENjT0udDBDxxq8Y5t YvHA==; dara=google.com ARC-Authentication-Results: i=2; mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b="MLZ/EPbf"; arc=pass (i=1 spf=pass spfdomain=flex--mattgilbride.bounces.google.com dkim=pass dkdomain=google.com dmarc=pass fromdomain=google.com); spf=pass (google.com: domain of linux-kernel+bounces-204523-linux.lists.archive=gmail.com@vger.kernel.org designates 147.75.48.161 as permitted sender) smtp.mailfrom="linux-kernel+bounces-204523-linux.lists.archive=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Return-Path: Received: from sy.mirrors.kernel.org (sy.mirrors.kernel.org. [147.75.48.161]) by mx.google.com with ESMTPS id 41be03b00d2f7-6de28959213si928475a12.612.2024.06.06.08.41.34 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Jun 2024 08:41:35 -0700 (PDT) Received-SPF: pass (google.com: domain of linux-kernel+bounces-204523-linux.lists.archive=gmail.com@vger.kernel.org designates 147.75.48.161 as permitted sender) client-ip=147.75.48.161; Authentication-Results: mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b="MLZ/EPbf"; arc=pass (i=1 spf=pass spfdomain=flex--mattgilbride.bounces.google.com dkim=pass dkdomain=google.com dmarc=pass fromdomain=google.com); spf=pass (google.com: domain of linux-kernel+bounces-204523-linux.lists.archive=gmail.com@vger.kernel.org designates 147.75.48.161 as permitted sender) smtp.mailfrom="linux-kernel+bounces-204523-linux.lists.archive=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Received: from smtp.subspace.kernel.org (wormhole.subspace.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by sy.mirrors.kernel.org (Postfix) with ESMTPS id A620AB301EB for ; Thu, 6 Jun 2024 15:11:21 +0000 (UTC) Received: from localhost.localdomain (localhost.localdomain [127.0.0.1]) by smtp.subspace.kernel.org (Postfix) with ESMTP id 540AB1A01CD; Thu, 6 Jun 2024 14:50:28 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="MLZ/EPbf" Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) (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 40C3F19FA8B for ; Thu, 6 Jun 2024 14:50:25 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.202 ARC-Seal:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717685427; cv=none; b=Lq0GexlS+KFylFAwXMjkMtz9Sbf4fxAOmw4zEo9Xyth09KS6BZ1rfzhCqCYndDO/rK9284rxa6P8p/bjLwztKc7gcsorPj+DFrILHBvqUvsVfLcy5y6w3ycQ/dh9rMBbmTJJPIwnKhkCt5uXkE7nD932X4iwG1JuQ8jW2pqv79Y= ARC-Message-Signature:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717685427; c=relaxed/simple; bh=GiIGlIrJEKcpzcm6AfyKbO/fOh2evAOH+6JTlh6KPkw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=UUdIkx4tZsxo1/+dKup4nBBfh6+hWYbHpJxe+S3/yZxe13mcfDb4/n73J+SzorXM7O2I8ewTLC9lyZ3DplZ43TPyE4/GYTeTfVzujdtudoBX+JHs7MI5c6rYQcOpDX1kPeW+7Tcpse5XLKgA9bMsbxzYUZxxVt9HDjSw6yD/iPA= ARC-Authentication-Results:i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=MLZ/EPbf; arc=none smtp.client-ip=209.85.219.202 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--mattgilbride.bounces.google.com Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-dfa77d54cd2so1718559276.3 for ; Thu, 06 Jun 2024 07:50:25 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1717685424; x=1718290224; 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=APYLI2P2kRH4kz6ibkFnlfxP/kI8VygXGISUKHVqwxs=; b=MLZ/EPbfM2E5Czpo+GOauGxbd/5lqZylwY4GO4yTy+DgwKzOftq9+DXQq+nI7q8DZI HNoJsTH/8LtxO8IL83uWsDoCdPK/SpFJDZqA+zYwOv+WsCv2VjqM2m1usLhGYhlbtcz4 P2/ZwqppPAEGoBlP7ZVHQTSZulpsAl81TNc0vkUPAv/ER8IHTwrrIrX8FTamdtxZhHUT ulxz1BdP9a/neM2I0pesAgiiljFZbGLLeJaCqcx1YYm+WdFa49pu5YPagRPvzaaa8BUS 2G+xQCsG6F6sgL0CjTsCWF70eN7fkwr+4anS+Y9cCFXFH0DR+FwTuLwg7EeJUg3ibdno nlNg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717685424; x=1718290224; 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=APYLI2P2kRH4kz6ibkFnlfxP/kI8VygXGISUKHVqwxs=; b=W1Ig9yE+DMUFiryyCe0LoPbHhjN8SoJQbRPGBoPR1GLQL2DrFNkiIC9X46CGlhkNGV qIeoNHdcD7X6Koho+A8i1L5atp0eZgex6NDR1bJfFCRAJM06show6xNra2CIhu9JG6EG ZeR43cVGK3Sh9HtTALnqDIrkH/4YwXd1iA5DaZqlCKGoS9fzU2kVbyjq83WTH9+XRmZ+ Djy80A8EoNU3Hxeybk7QQPc/t/dlbeTgETPpSNlnXsXVPlUndPUO+20tHGHn860IWqoW 3dFQkl5CX/st01Ua+K6hybJ7ZxTYAOGoPRnyi2nzYgVD0pT5u6cQKbyEdk61jAGIVpy+ mCyA== X-Forwarded-Encrypted: i=1; AJvYcCVxRK+saieP9mH/Z1Jv6E/cZcXPvJ4sN66QnCbb7PXF7j2VN2dvGqptQSy4clmMiL4IPYEJAoO587WkUWkrJi+uS+HvkFKSDmH8yCF0 X-Gm-Message-State: AOJu0YyvmoVc6a9OpiDt6ti9jvhJMaxAE03ulgp7B3nYisagGBoiRYID 1mUhiCMkRZSvW3+HduR1beA1Gt+Zw9SMMvw/hI6oStF12Rmp/PSWUrEk4I+38j2uHAul82y3KNT 0P8A+AuCS02MOvH//UboFoSGCpA== X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a05:6902:100a:b0:df7:8c1b:4309 with SMTP id 3f1490d57ef6-dfacab31371mr356780276.3.1717685424222; Thu, 06 Jun 2024 07:50:24 -0700 (PDT) Date: Thu, 06 Jun 2024 14:50:06 +0000 In-Reply-To: <20240606-b4-rbtree-v5-0-96fe1a0e97c0@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240606-b4-rbtree-v5-0-96fe1a0e97c0@google.com> X-Mailer: b4 0.12.4 Message-ID: <20240606-b4-rbtree-v5-3-96fe1a0e97c0@google.com> Subject: [PATCH v5 3/6] rust: rbtree: add iterator From: Matt Gilbride To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?=" , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Christian Brauner Cc: Rob Landley , Davidlohr Bueso , Michel Lespinasse , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matt Gilbride Content-Type: text/plain; charset="utf-8" From: Wedson Almeida Filho - Add Iterator implementation for `RBTree`, allowing iteration over (key, value) pairs in key order. - Add individual `keys()` and `values()` functions to iterate over keys or values alone. - Update doctests to use iteration instead of explicitly getting items. Iteration is needed by the binder driver to enumerate all values in a tree for oneway spam detection [1]. Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-17-08ba9197f637@google.com/ [1] Signed-off-by: Wedson Almeida Filho Reviewed-by: Alice Ryhl Tested-by: Alice Ryhl Signed-off-by: Matt Gilbride --- rust/kernel/rbtree.rs | 130 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 112 insertions(+), 18 deletions(-) diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index a515bfa80113..40db6d3e732b 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -47,14 +47,30 @@ /// assert_eq!(tree.get(&30).unwrap(), &300); /// } /// +/// // Iterate over the nodes we just inserted. +/// { +/// let mut iter = tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &100)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert!(iter.next().is_none()); +/// } +/// +/// // Print all elements. +/// for (key, value) in &tree { +/// pr_info!("{} = {}\n", key, value); +/// } +/// /// // Replace one of the elements. /// tree.try_create_and_insert(10, 1000, flags::GFP_KERNEL)?; /// /// // Check that the tree reflects the replacement. /// { -/// assert_eq!(tree.get(&10).unwrap(), &1000); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &300); +/// let mut iter = tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &1000)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert!(iter.next().is_none()); /// } /// /// // Change the value of one of the elements. @@ -62,9 +78,11 @@ /// /// // Check that the tree reflects the update. /// { -/// assert_eq!(tree.get(&10).unwrap(), &1000); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &3000); +/// let mut iter = tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &1000)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &3000)); +/// assert!(iter.next().is_none()); /// } /// /// // Remove an element. @@ -72,9 +90,10 @@ /// /// // Check that the tree reflects the removal. /// { -/// assert_eq!(tree.get(&10), None); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &3000); +/// let mut iter = tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &3000)); +/// assert!(iter.next().is_none()); /// } /// /// # Ok::<(), Error>(()) @@ -114,9 +133,11 @@ /// /// // Check the nodes we just inserted. /// { -/// assert_eq!(tree.get(&10).unwrap(), &100); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &300); +/// let mut iter = tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &100)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert!(iter.next().is_none()); /// } /// /// // Remove a node, getting back ownership of it. @@ -124,9 +145,10 @@ /// /// // Check that the tree reflects the removal. /// { -/// assert_eq!(tree.get(&10).unwrap(), &100); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30), None); +/// let mut iter = tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &100)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert!(iter.next().is_none()); /// } /// /// // Create a preallocated reservation that we can re-use later. @@ -138,9 +160,11 @@ /// /// // Check that the tree reflect the new insertion. /// { -/// assert_eq!(tree.get(&10).unwrap(), &100); -/// assert_eq!(tree.get(&15).unwrap(), &150); -/// assert_eq!(tree.get(&20).unwrap(), &200); +/// let mut iter = tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &100)); +/// assert_eq!(iter.next().unwrap(), (&15, &150)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert!(iter.next().is_none()); /// } /// /// # Ok::<(), Error>(()) @@ -167,6 +191,26 @@ pub fn new() -> Self { _p: PhantomData, } } + + /// Returns an iterator over the tree nodes, sorted by key. + pub fn iter(&self) -> Iter<'_, K, V> { + // INVARIANT: `bindings::rb_first` returns a valid pointer to a tree node given a valid pointer to a tree root. + Iter { + _tree: PhantomData, + // SAFETY: `self.root` is a valid pointer to the tree root. + next: unsafe { bindings::rb_first(&self.root) }, + } + } + + /// Returns an iterator over the keys of the nodes in the tree, in sorted order. + pub fn keys(&self) -> impl Iterator { + self.iter().map(|(k, _)| k) + } + + /// Returns an iterator over the values of the nodes in the tree, sorted by key. + pub fn values(&self) -> impl Iterator { + self.iter().map(|(_, v)| v) + } } impl RBTree @@ -358,6 +402,56 @@ fn drop(&mut self) { } } +impl<'a, K, V> IntoIterator for &'a RBTree { + type Item = (&'a K, &'a V); + type IntoIter = Iter<'a, K, V>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +/// An iterator over the nodes of a [`RBTree`]. +/// +/// Instances are created by calling [`RBTree::iter`]. +/// +/// # Invariants +/// - `self.next` is a valid pointer. +/// - `self.next` points to a node stored inside of a valid `RBTree`. +pub struct Iter<'a, K, V> { + _tree: PhantomData<&'a RBTree>, + next: *mut bindings::rb_node, +} + +// SAFETY: The [`Iter`] gives out immutable references to K and V, so it has the same +// thread safety requirements as immutable references. +unsafe impl<'a, K: Sync, V: Sync> Send for Iter<'a, K, V> {} + +// SAFETY: The [`Iter`] gives out immutable references to K and V, so it has the same +// thread safety requirements as immutable references. +unsafe impl<'a, K: Sync, V: Sync> Sync for Iter<'a, K, V> {} + +impl<'a, K, V> Iterator for Iter<'a, K, V> { + type Item = (&'a K, &'a V); + + fn next(&mut self) -> Option { + if self.next.is_null() { + return None; + } + + // SAFETY: By the type invariant of `Iter`, `self.next` is a valid node in an `RBTree`, + // and by the type invariant of `RBTree`, all nodes point to the links field of `Node` objects. + let cur = unsafe { container_of!(self.next, Node, links) }; + + // SAFETY: `self.next` is a valid tree node by the type invariants. + self.next = unsafe { bindings::rb_next(self.next) }; + + // SAFETY: By the same reasoning above, it is safe to dereference the node. Additionally, + // it is ok to return a reference to members because the iterator must outlive it. + Some(unsafe { (&(*cur).key, &(*cur).value) }) + } +} + /// A memory reservation for a red-black tree node. /// /// -- 2.45.1.467.gbab1589fc0-goog