Received: by 2002:ab2:7903:0:b0:1fb:b500:807b with SMTP id a3csp1063691lqj; Mon, 3 Jun 2024 09:06:12 -0700 (PDT) X-Forwarded-Encrypted: i=3; AJvYcCUdPLNjwELmdZDBotyjNvPRcEfEoQtmkSjiV4Ilfq38D9jHr6HWp7rFzL/X6qKmLdnbfDyvB2XfD4e0aI0v+uJftPyyhge1be7/BDieMA== X-Google-Smtp-Source: AGHT+IE4mnWVSTwN9mBg+Y8vDG1Ge/IG+AzN/xfq4+6uukVio5rK7LhkjqEH1ehNhhhqI0kuwHpO X-Received: by 2002:a05:622a:143:b0:43f:edc8:6528 with SMTP id d75a77b69052e-43ff52596fcmr122483761cf.37.1717430771800; Mon, 03 Jun 2024 09:06:11 -0700 (PDT) ARC-Seal: i=2; a=rsa-sha256; t=1717430771; cv=pass; d=google.com; s=arc-20160816; b=pf2Jd9rBSfqIwAKhgRLbjYl9P+huJkjdqKZmInkbVxXz2vwAdHxfj1yvPRCCyPllNL VBk5sy/s0VJ06t7BfzU9/cifvw9AZdAcevBb52IC6kC7wrjWPEWmzWLBqv1Vm86XvhZs Fc8fS3nnaloDWlgURAlskV0PSHpPcdlW17eOhrjNjHWWECb0BUjF/olypm2i3UoS9sLA pL2Ac1tnkbAS2+5tT5bV7N7gv2WfBd9c4IB7m+LXeKL8h+Rm+xaep0ZRuCQpooXxPIE8 HVvvE+0alYspw5kQFtCWZwKJns/U1QK/YEF0ZBA/N4eqpXd0kN9cpFiRFfOux/MPBoA2 UmLA== 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=6paZo5N2Bj7KOX0jnQD83qN0s5hUal/Z6c5JFeBhY+4=; fh=oOIBd35HO8EgpyREKSPNbeT4SF6OPNUccTWnwMr9GSo=; b=wgQovoVK23POYbgKOAnGkR7q//ml7GXDDWCyIADn6w0yrjBK3HYxp47Ci9ExJIhnPi EEFFQKl/nWd46BR9CKElGMIgnPX2o0j2EL4cjjxpL8dhybX+2+d7GPEr4Ta/VyzjHkeX /2X9MrYKpzz+OxyLTXbY97RLROXWH/WrMN5Rs/xZpzqx6zDjmEo+hio5cGNuMl12tkAE WiTTZRSUlRnWeJlFPio2yZAo8Dp4nEOK+dH0s8kIruBEBlRmqpJYPw67fkDti/r3cUW6 Zq8SwxShsu4wR5oGwaFtMwT1eiNCp86Nf4Z8wuDJvjGm66R6ZLQjdAo2Y4Am6u/l6xnd JoCg==; dara=google.com ARC-Authentication-Results: i=2; mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=XTyb5s3E; 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-199408-linux.lists.archive=gmail.com@vger.kernel.org designates 147.75.199.223 as permitted sender) smtp.mailfrom="linux-kernel+bounces-199408-linux.lists.archive=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Return-Path: Received: from ny.mirrors.kernel.org (ny.mirrors.kernel.org. [147.75.199.223]) by mx.google.com with ESMTPS id d75a77b69052e-43ff257d56dsi73838241cf.400.2024.06.03.09.06.11 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 03 Jun 2024 09:06:11 -0700 (PDT) Received-SPF: pass (google.com: domain of linux-kernel+bounces-199408-linux.lists.archive=gmail.com@vger.kernel.org designates 147.75.199.223 as permitted sender) client-ip=147.75.199.223; Authentication-Results: mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=XTyb5s3E; 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-199408-linux.lists.archive=gmail.com@vger.kernel.org designates 147.75.199.223 as permitted sender) smtp.mailfrom="linux-kernel+bounces-199408-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 ny.mirrors.kernel.org (Postfix) with ESMTPS id 767421C216ED for ; Mon, 3 Jun 2024 16:06:11 +0000 (UTC) Received: from localhost.localdomain (localhost.localdomain [127.0.0.1]) by smtp.subspace.kernel.org (Postfix) with ESMTP id 8F233134414; Mon, 3 Jun 2024 16:05:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="XTyb5s3E" Received: from mail-yb1-f201.google.com (mail-yb1-f201.google.com [209.85.219.201]) (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 B044F136663 for ; Mon, 3 Jun 2024 16:05:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.201 ARC-Seal:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717430731; cv=none; b=Uhq4239zpLv7/MzuirRntjs9LRooi3bNisoGkPdYeFMavpYS6+31pHWEZznUdLM084aXE9MSYUeO+rpcZrSDUiOqjw5kiOSU3ZCW4Pa8WUFCQYrPjxkbkACEfglM+gCYty8g3u3ieb9R5kRY8vG8LJNcFO9KUP9ZJJ8iw4ApT3k= ARC-Message-Signature:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717430731; c=relaxed/simple; bh=3OYBXu3JmXTxowje7u9YRJ3AwCID6d8MnuzpRKwv7LQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=c9XGPLw+4RJ51T9sd+xb1zS6VZCKrcNEqyYGwKYtK09b30wBhJCp9mcWySn4XMJkK3nS6652k07s9beKfy5dAyFhXKYeu+41O5Lrv2PTEfZsUokS2wtOCei9XvnZSNrkDPtW18NO+jE8uE8T+iYkk1+Gmu1Y+hEaYfS+L2XWgo4= 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=XTyb5s3E; arc=none smtp.client-ip=209.85.219.201 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-f201.google.com with SMTP id 3f1490d57ef6-dfa77d54cd2so5247984276.3 for ; Mon, 03 Jun 2024 09:05:29 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1717430729; x=1718035529; 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=6paZo5N2Bj7KOX0jnQD83qN0s5hUal/Z6c5JFeBhY+4=; b=XTyb5s3E6itdT9kuxWQhlgSusIRozmTSpe/trO29KBh225SCkFzt3F2ZkIi+7S3IBf QYwmS9lLvBEFCDNhjikTeV88JsFp833V1LH1KXiiWmQ3P2EAF2U+cc5ZO9mbRHLPC/NZ 9aAwDgQ08eTlTm6/j/XMSOYO990oQbN0q+AITcQKQ2f3yV4FIwbS5OLDG+kMPDpxmlNV 1yzDhZdCOYE+PZ7X8FUqldDJzcX7xFJ6RIwgUXK7wT0Q4BldBG1PzUnlv84obeCMT8H4 o1t/BGY0PfBmyj47sHYK0uy9nT4vFm/9Fc2n8MRIf3wZmnzlqvVJLWMPivfQylIlR2f/ o6Nw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717430729; x=1718035529; 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=6paZo5N2Bj7KOX0jnQD83qN0s5hUal/Z6c5JFeBhY+4=; b=Wv2nY1uS3x0yt4Z6uKeTRKGQFj7CuoiNdML0dWmk7u6yf1fLxB94gLiwRz8I5+TCJD TfWEVVtBMbxEADxwDTYSd1yupL38TXG21Fo/pleJrH6IdtZriE5VYkgqSWsSpTtUP4Gv unD6bO8RCLA0VysDk21WF8dPp7fnCZrCYRyT/Vz8kxkj7cr7NjpOGhdjs6RsvQ4d7pvB 7UIZSamZES6FhqQMcQC/TxSDDjBrGYDaDZepn3iL7IHl+BKDFM0knzgUby7LRycugvWI /Ki5CvOkJOl1SOM234Pv2F5zxX69KRWJgk0tIda430x5/KgQJiusuvgf4EHOL/Aq1iqD +yvg== X-Forwarded-Encrypted: i=1; AJvYcCWhoCpJpBDxkv5EhZ+sX0o76BL22YEpEcpVzvWgNe34va5YW1nxpV8dvuZwuplGs5aemmxs1DlCiqviQueW2elB9oqSYWhm4gR1mnCw X-Gm-Message-State: AOJu0Yxm2QbGaRs7duGjcM7KtMk6YIzIMJdmLsuL3QPSvDcCeEEzXhBR K7wZjtFM5ilAqz/VsmaJLz721NUYQWkTB/zvxJmx6RxoU6B1XQTvDkRKcr1B3o2uQDX1iiBveTN CoCc7qvA15StUaaXNL5anbV/7WA== X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a05:6902:2b85:b0:df4:dfce:ba0 with SMTP id 3f1490d57ef6-dfa73db4ca7mr1013253276.11.1717430728839; Mon, 03 Jun 2024 09:05:28 -0700 (PDT) Date: Mon, 03 Jun 2024 16:05:18 +0000 In-Reply-To: <20240603-b4-rbtree-v4-0-308e43d6abfc@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240603-b4-rbtree-v4-0-308e43d6abfc@google.com> X-Mailer: b4 0.12.4 Message-ID: <20240603-b4-rbtree-v4-3-308e43d6abfc@google.com> Subject: [PATCH v4 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 6c4e259f7516..6ebea833e5a9 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.288.g0e0cd299f1-goog