From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from mail-qk1-f202.google.com (mail-qk1-f202.google.com [209.85.222.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 67D8D2D605 for ; Mon, 19 Feb 2024 11:48:38 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.222.202 ARC-Seal:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1708343320; cv=none; b=JerDzwu7JNLoOJDn+JKsQMfejUSuhPpGPAdGZApUD20eAbswvmVfsZ79fOoXTftnc9m8Kj08joVVYmtljRVKZ5b3+MatdgkZSDFIQ/+ea+UJQjxVvGFB+iBzOMCKzlMRMcZiGOXUOgnUK9GGETJLlHu9DB8fvnW+nLP46nqddI0= ARC-Message-Signature:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1708343320; c=relaxed/simple; bh=Gsr8Np304/ZF/8MRD/n+jlVmItVNTviF52shcVw7ERw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=EL3pnuxZplip7a9US11/a3BXwapNhzC9NkS5gP0VkzRlJZdyGQwn3kEgCnRgusHrXOv6FjuTtAToNT3Q89uQdVvTsY7TPMncsyvYt9+0+dHSH403k+UX+jiU2NCbzMkJn3ng6hXFO27J1mqlYmqjzbJwoMutlBQOK4VFfjq/wZE= 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=DZsSTOZz; arc=none smtp.client-ip=209.85.222.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 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="DZsSTOZz" Received: by mail-qk1-f202.google.com with SMTP id af79cd13be357-7873fd60a11so533865685a.1 for ; Mon, 19 Feb 2024 03:48:38 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1708343317; x=1708948117; 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=eQCD4AuKZId7gMhOchvG2XGZrBs0B56ew/r04xotUCQ=; b=DZsSTOZzMjMot2AhkcMGcLko6acOMIDdSj8YEVYpLIsc3Rhy1M6LQhm0bSgYWyzmDI rd4BHMdalqe0XjGUsJetR2YLYWZZ5Cte3vfwxZbO9jqBeMjBMcGLmEh2Vr/zr2lFdTEL vhFaK4dNfY+GVz3fcfc0jEcPq1IiBBWtp/DutXBkTv3YEy4nqzb4cvKbqAwDwTYNCr01 iXW0qqSn/eZvM3gq38S3WFtADYkwuvs4DAGY2zkiOnP5g9bezQG6MgfQbTrGWgvLeUHm gYbEMUFNfh4dhkvPjjyXHDHFdlAL6AJv/Pr60Y1H9ANwaMnQCwxL906LtRwlujkkAF9R YI0w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1708343317; x=1708948117; 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=eQCD4AuKZId7gMhOchvG2XGZrBs0B56ew/r04xotUCQ=; b=qa+HdQfSbwFN7vUuz3C7OcQ8w4pHqOhYC6BzwUO48fc2+OGtv8IAQi2eYzANPGTnt5 Z4nNU476JjWKX1yLw7ohYBVeKjp4iDUoPEv602bmNpU8Ws8nSM83xNVuORo2uUVr/oLb Jn8cSABvITDT4SYshek97Qtx+DBLdKaPkkYK/9rDO5SUmaYyYLs0dhxUyoWNi3AW/X4f 3s+Le/q11yfaRobRHxK7mpnTnWrUxxRzubZ6/5+0zV0Bm2sd8q3plTlRaoOGM7hak2l1 pIWCbm8t9NUTd8iI2LKdiGo44ASl36W2cHytEePsc2NKNSqYwJvR6WScD4Poaz2zmOz8 BNiA== X-Forwarded-Encrypted: i=1; AJvYcCWU9fSQ9JnYncuKNhTbcb8WFtjSL03VfFigVBFxyDdrpX5BKBtu0dz5HTBWBNm76PBUNQOoRaPJdiiahtHJHAWsPx1aCid8CphXN2+KcDo= X-Gm-Message-State: AOJu0YxxWOMd+Q0bq/bn9j2VSc2VfNbWGcvohcGKL4cXVfyVmfii2Tff cXTzIIynrCFsjkfyJ/eYOLdOZ1RvcZ6gXlsoSNTG0zHRsrmHBP4h26I4F16l/eYGAY3lRZkJ1RE 9CuCjYdu2f1HiHuAG2xEJREt7Wg== X-Google-Smtp-Source: AGHT+IF/WFVUGJFcz1k6jq7qhar/F0WayDZnvQAS2c7izu/+vXSmtyAZO8j0stsH0Xjt0E6hPX62r3w4J705wFJKzfE= X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a05:620a:40d0:b0:787:72d9:b7a0 with SMTP id g16-20020a05620a40d000b0078772d9b7a0mr3625qko.3.1708343317417; Mon, 19 Feb 2024 03:48:37 -0800 (PST) Date: Mon, 19 Feb 2024 11:48:10 +0000 In-Reply-To: <20240219-b4-rbtree-v2-0-0b113aab330d@google.com> Precedence: bulk X-Mailing-List: rust-for-linux@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240219-b4-rbtree-v2-0-0b113aab330d@google.com> X-Mailer: b4 0.12.4 Message-ID: <20240219-b4-rbtree-v2-3-0b113aab330d@google.com> Subject: [PATCH v2 3/6] rust: rbtree: add `RBTreeIterator` 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 (`RBTreeIterator`) 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 | 125 ++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 107 insertions(+), 18 deletions(-) diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index a72e9f57e660..b1faac831cfc 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -54,14 +54,30 @@ struct Node { /// 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)?; /// /// // 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. @@ -69,9 +85,11 @@ struct Node { /// /// // 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. @@ -79,9 +97,10 @@ struct Node { /// /// // 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>(()) @@ -121,9 +140,11 @@ struct Node { /// /// // 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. @@ -131,9 +152,10 @@ struct Node { /// /// // 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()); /// } /// /// // Turn the node into a reservation so that we can reuse it with a different key/value. @@ -145,9 +167,11 @@ struct Node { /// /// // 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>(()) @@ -188,6 +212,25 @@ pub fn try_reserve_node() -> Result> { pub fn try_allocate_node(key: K, value: V) -> Result> { Ok(Self::try_reserve_node()?.into_node(key, value)) } + + /// Returns an iterator over the tree nodes, sorted by key. + pub fn iter(&self) -> RBTreeIterator<'_, K, V> { + RBTreeIterator { + _tree: PhantomData, + // SAFETY: `root` is valid as it's embedded in `self` and we have a valid `self`. + 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 @@ -350,6 +393,52 @@ fn drop(&mut self) { } } +impl<'a, K, V> IntoIterator for &'a RBTree { + type Item = (&'a K, &'a V); + type IntoIter = RBTreeIterator<'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`]. +pub struct RBTreeIterator<'a, K, V> { + _tree: PhantomData<&'a RBTree>, + next: *mut bindings::rb_node, +} + +// SAFETY: An [`RBTree`] allows the same kinds of access to its values that a struct allows to its +// fields, so we use the same Send condition as would be used for a struct with K and V fields. +unsafe impl<'a, K: Send, V: Send> Send for RBTreeIterator<'a, K, V> {} + +// SAFETY: An [`RBTree`] allows the same kinds of access to its values that a struct allows to its +// fields, so we use the same Sync condition as would be used for a struct with K and V fields. +unsafe impl<'a, K: Sync, V: Sync> Sync for RBTreeIterator<'a, K, V> {} + +impl<'a, K, V> Iterator for RBTreeIterator<'a, K, V> { + type Item = (&'a K, &'a V); + + fn next(&mut self) -> Option { + if self.next.is_null() { + return None; + } + + // SAFETY: All links fields we create are in a `Node`. + let cur = unsafe { crate::container_of!(self.next, Node, links) }; + + // SAFETY: The reference to the tree used to create the iterator outlives the iterator, so + // the tree cannot change. By the tree invariant, all nodes are valid. + 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. /// /// It contains the memory needed to hold a node that can be inserted into a red-black tree. One -- 2.44.0.rc0.258.g7320e95886-goog