Received: by 2002:ab2:6309:0:b0:1fb:d597:ff75 with SMTP id s9csp453401lqt; Thu, 6 Jun 2024 08:20:04 -0700 (PDT) X-Forwarded-Encrypted: i=3; AJvYcCUZu+xR3usuqxAd89YvoZ68I+R4S8cz1V9YZrhWvUvUIhsiKCE6b/nYs5IGEtyFYtnTUX6Z9Q60pxWJGnA995scA20znxoekT/or/9FJA== X-Google-Smtp-Source: AGHT+IH64cdRLKOhEXG9HfOmsXfAQy0SCrmp2jnBv8gN46YoeXdhuqCSyG9Wxl+oRg08z9GAhja/ X-Received: by 2002:a05:6a21:81a4:b0:1b0:27dd:3355 with SMTP id adf61e73a8af0-1b2b6f1d821mr6298251637.21.1717687203569; Thu, 06 Jun 2024 08:20:03 -0700 (PDT) ARC-Seal: i=2; a=rsa-sha256; t=1717687203; cv=pass; d=google.com; s=arc-20160816; b=DQ7K2RTziWkV1dQbjmnjijas9meoAqRfsOOKA0EUcjuEmD4idnGeLNwlQzTpSd6udK WsGssJZxTChN7hlYO0EMZroH084RRKIH3d8BI6TbILg8Bv+RKE8i82Wf7rDkOgeFXKhl nCk51ZmiDLU5yfzCVn0w+KBqwhzV+tu8LIbkP9ZmW7OFgOINC5jdk/YhixObhbAPngjU Y8U0jihZgND0Nfj0LBY8Zt4VgJbsKh/i1vY88Z2Q/LbUvD9Tw7BrpQkrkdI2Gqr7VrN6 c3Z4l5Ixc/vwamqpbodaSUBLhbXfV3fBSsHzoEdSNtEHyoNR2T/sgRScT3ziAsdMpguS 3agA== ARC-Message-Signature: i=2; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=content-transfer-encoding:cc:to:from:subject:message-id:references :mime-version:list-unsubscribe:list-subscribe:list-id:precedence :in-reply-to:date:dkim-signature; bh=DrjmPFnT4bYE1Co9n92KYk16NE4T3PvT8gqOB2zT4QE=; fh=7pGFD5CG7SB75lMGtUTMdCGrs4PaXNIv7hGVrnh8TCQ=; b=u89bK+NwSPvAqPe0NymT2XCpOCmhDOjwYeNJXSmkw8qRP88uUHqP6oIPQ1g4gqG04w REm4jyzO6CUgWPvlc06DNKstF8o9MlIMjlbo7iO/dB9w7sWNxp3m6T3zquRoBJyvXjx/ tCdI6uVd/JcNUrlwA667r4W2brFU+T7o+tmTUWhCUwXtK4AiJXyy8NedLUTlR9q4HRIh DmHEQuN9JHIBTekpIHF68hZVnJu/hL4Hh1TayBJZf5iGdSknN0fhPjMSMPH3yLe7Htk4 Gxi6ykldHh1PIiyDNeZM6Se5Au0lx3Ko4BhWwBmWNwzdzNPPnJwF8pxmQqnAx/X881Zj umRg==; dara=google.com ARC-Authentication-Results: i=2; mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=c2U2786I; 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-204522-linux.lists.archive=gmail.com@vger.kernel.org designates 139.178.88.99 as permitted sender) smtp.mailfrom="linux-kernel+bounces-204522-linux.lists.archive=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Return-Path: Received: from sv.mirrors.kernel.org (sv.mirrors.kernel.org. [139.178.88.99]) by mx.google.com with ESMTPS id 41be03b00d2f7-6de21972170si254a12.233.2024.06.06.08.20.03 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Jun 2024 08:20:03 -0700 (PDT) Received-SPF: pass (google.com: domain of linux-kernel+bounces-204522-linux.lists.archive=gmail.com@vger.kernel.org designates 139.178.88.99 as permitted sender) client-ip=139.178.88.99; Authentication-Results: mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=c2U2786I; 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-204522-linux.lists.archive=gmail.com@vger.kernel.org designates 139.178.88.99 as permitted sender) smtp.mailfrom="linux-kernel+bounces-204522-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 sv.mirrors.kernel.org (Postfix) with ESMTPS id 6CC8D283E08 for ; Thu, 6 Jun 2024 15:11:19 +0000 (UTC) Received: from localhost.localdomain (localhost.localdomain [127.0.0.1]) by smtp.subspace.kernel.org (Postfix) with ESMTP id 29582199396; 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="c2U2786I" 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 E17E819FA6A for ; Thu, 6 Jun 2024 14:50:23 +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=1717685426; cv=none; b=VAA7WQ74NQGUQsphWlWZYWWXbOCSC9+Fs8/QVh+YA6TVHInveOLLqP/Se3Atvz2NiaEjqgyPVkSTppiga04PqzY/8/CWrcuabLANymnor5wBBxTWw2gqMeCIyG9iS/MCP60WMlSFImr6bvpExFq4i84/M8h0D0gJ1wWkWdcdVHA= ARC-Message-Signature:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717685426; c=relaxed/simple; bh=cVU6ZqEsjHcTxeBD5/5BvhhHawOxuHl5POylft0doTw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=ZjVCMg+hysmMQ3hgRQoGxTbsq5ZVjMVIQkvR+brZcQf62LJm9/tjYTzoU4CwNNdTgBC/MGdj0N+vFwGnWGVBg4waJMCH1yAV51a5QrdmVhndMEw9Byud1VWCyrB7iBCCBUDlxvsOwraFrn6eH8r357udd6thJCr1+BXX9fr2cAw= 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=c2U2786I; 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-dfa7464759cso1655015276.0 for ; Thu, 06 Jun 2024 07:50:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1717685423; x=1718290223; darn=vger.kernel.org; h=content-transfer-encoding:cc:to:from:subject:message-id:references :mime-version:in-reply-to:date:from:to:cc:subject:date:message-id :reply-to; bh=DrjmPFnT4bYE1Co9n92KYk16NE4T3PvT8gqOB2zT4QE=; b=c2U2786IYTekefGsYwDBWI76T4jX0uxUJsiG8/BuZQ0sb2o/gCL8fUJ/Yf/AuhqBmh MJOYQCLCWkXkvh7xnYDHAnKEcgAtJpkXL2XJnAD8oVUCrWtOn+TOavYVcSa2atJC4thO cx/d8if26YXtHnjGWsWnD7wWxJSseF0LeUDkotSh4K9vE3sAxzj1lGJg7EAVIJBufJX5 4tm8Jl6rgwuVUFMuxD6H87LwtqYDIquZqbMJE8HbS3SWpj61UHc6mg2e8bsiLQ9HanzA etTfCe/pXMAJAB+CELFO7dXZ1fu0lJFSLqmE2PGNYAaHVLBGcG22jbAFlSKKM8hRfHuY 7bCQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717685423; x=1718290223; h=content-transfer-encoding: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=DrjmPFnT4bYE1Co9n92KYk16NE4T3PvT8gqOB2zT4QE=; b=IRtW2wXhJI7suGtBBGXy5Si9awei2dsuTsRParS4jB6DZTgxTTA/h3Zo5gxEkpMyQH /nqhO+iJhLt95gQ2bfLEM5Nm6tit9yE2EB5FqV+/0UQkhZwe9CrjZZ84p3EwcdeT3hoV zkmqyOtPKZBMpUXAEvt5Yll9KQ/sxQ+CVfhqUJ+tPyfjqtqQ3akVTyh30eKMxczO7PL+ 5RIq9nfFRKkBxMfFVsL3WQ2e7doRYaLiTGzsWh4tOWZNYV0LqVg5wsAqnSU0K0mv9HYl Kd+BNVepa39HvL7seO8pZnZjASvZGY+N9ydbBv12cLsV6bKze/rdCYFY/gwUapuXGPFy SvFA== X-Forwarded-Encrypted: i=1; AJvYcCUwY/3wizff+y+WWQENH/XzOXfeE5IYf1jdcYY9RTdu5qTDmDL3hCikHNT/XZ0bRJrOY/pE1OVpr7ZK1B9yAW037ImXpr+4s8mR0L/c X-Gm-Message-State: AOJu0Yzi6JastaK2FLp8V1frPnjMjnr82ucAfZ2NVauNZy+em6BjTwGl FhDRIulanUP7XZRE8N3HGuVIG386kDraJ1p+qzF0Eb63CPUFSSOM/LQNtYV42Sgu+HZpra+jzhv wRbL0mVp5DzFS14gMr7HQWtVQZQ== X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a25:d6cc:0:b0:df4:d5f2:b8 with SMTP id 3f1490d57ef6-dfacad0deb6mr150513276.12.1717685422768; Thu, 06 Jun 2024 07:50:22 -0700 (PDT) Date: Thu, 06 Jun 2024 14:50:05 +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-2-96fe1a0e97c0@google.com> Subject: [PATCH v5 2/6] rust: rbtree: add red-black tree implementation backed by the C version 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" Content-Transfer-Encoding: quoted-printable From: Wedson Almeida Filho The rust rbtree exposes a map-like interface over keys and values, backed by the kernel red-black tree implementation. Values can be inserted, deleted, and retrieved from a `RBTree` by key. This base abstraction is used by binder to store key/value pairs and perform lookups, for example the patch "[PATCH RFC 03/20] rust_binder: add threading support" in the binder RFC [1]. Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-3-08ba= 9197f637@google.com/ [1] Signed-off-by: Wedson Almeida Filho Reviewed-by: Alice Ryhl Tested-by: Alice Ryhl Signed-off-by: Matt Gilbride --- rust/helpers.c | 7 + rust/kernel/lib.rs | 1 + rust/kernel/rbtree.rs | 432 ++++++++++++++++++++++++++++++++++++++++++++++= ++++ 3 files changed, 440 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 4c8b7b92a4f4..608b38c0b3e8 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -157,6 +157,13 @@ void rust_helper_init_work_with_key(struct work_struct= *work, work_func_t func, } EXPORT_SYMBOL_GPL(rust_helper_init_work_with_key); =20 +void rust_helper_rb_link_node(struct rb_node *node, struct rb_node *parent= , + struct rb_node **rb_link) +{ + rb_link_node(node, parent, rb_link); +} +EXPORT_SYMBOL_GPL(rust_helper_rb_link_node); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indi= ces. diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 9a943d99c71a..dc2678803637 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -37,6 +37,7 @@ pub mod net; pub mod prelude; pub mod print; +pub mod rbtree; mod static_assert; #[doc(hidden)] pub mod std_vendor; diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs new file mode 100644 index 000000000000..a515bfa80113 --- /dev/null +++ b/rust/kernel/rbtree.rs @@ -0,0 +1,432 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Red-black trees. +//! +//! C header: [`include/linux/rbtree.h`](srctree/include/linux/rbtree.h) +//! +//! Reference: + +use crate::{alloc::Flags, bindings, container_of, error::Result, prelude::= *}; +use alloc::boxed::Box; +use core::{ + cmp::{Ord, Ordering}, + marker::PhantomData, + mem::MaybeUninit, + ptr::{addr_of_mut, NonNull}, +}; + +/// A red-black tree with owned nodes. +/// +/// It is backed by the kernel C red-black trees. +/// +/// # Invariants +/// +/// Non-null parent/children pointers stored in instances of the `rb_node`= C struct are always +/// valid, and pointing to a field of our internal representation [`Node`]= . +/// +/// # Examples +/// +/// In the example below we do several operations on a tree. We note that = insertions may fail if +/// the system is out of memory. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNode, RBTreeNodeRese= rvation}}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert three elements. +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// +/// // 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); +/// } +/// +/// // 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); +/// } +/// +/// // Change the value of one of the elements. +/// *tree.get_mut(&30).unwrap() =3D 3000; +/// +/// // 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); +/// } +/// +/// // Remove an element. +/// tree.remove(&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); +/// } +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// In the example below, we first allocate a node, acquire a spinlock, th= en insert the node into +/// the tree. This is useful when the insertion context does not allow sle= eping, for example, when +/// holding a spinlock. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNode}, sync::SpinLoc= k}; +/// +/// fn insert_test(tree: &SpinLock>) -> Result { +/// // Pre-allocate node. This may fail (as it allocates memory). +/// let node =3D RBTreeNode::new(10, 100, flags::GFP_KERNEL)?; +/// +/// // Insert node while holding the lock. It is guaranteed to succeed= with no allocation +/// // attempts. +/// let mut guard =3D tree.lock(); +/// guard.insert(node); +/// Ok(()) +/// } +/// ``` +/// +/// In the example below, we reuse an existing node allocation from an ele= ment we removed. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNodeReservation}}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert three elements. +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// +/// // 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); +/// } +/// +/// // Remove a node, getting back ownership of it. +/// let existing =3D tree.remove(&30).unwrap(); +/// +/// // 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); +/// } +/// +/// // Create a preallocated reservation that we can re-use later. +/// let reservation =3D RBTreeNodeReservation::new(flags::GFP_KERNEL)?; +/// +/// // Insert a new node into the tree, reusing the previous allocation. T= his is guaranteed to +/// // succeed (no memory allocations). +/// tree.insert(reservation.into_node(15, 150)); +/// +/// // 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); +/// } +/// +/// # Ok::<(), Error>(()) +/// ``` +pub struct RBTree { + root: bindings::rb_root, + _p: PhantomData>, +} + +// SAFETY: An [`RBTree`] allows the same kinds of access to its values tha= t 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 Send for RBTree {} + +// SAFETY: An [`RBTree`] allows the same kinds of access to its values tha= t 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 Sync for RBTree {} + +impl RBTree { + /// Creates a new and empty tree. + pub fn new() -> Self { + Self { + // INVARIANT: There are no nodes in the tree, so the invariant= holds vacuously. + root: bindings::rb_root::default(), + _p: PhantomData, + } + } +} + +impl RBTree +where + K: Ord, +{ + /// Tries to insert a new value into the tree. + /// + /// It overwrites a node if one already exists with the same key and r= eturns it (containing the + /// key/value pair). Returns [`None`] if a node with the same key didn= 't already exist. + /// + /// Returns an error if it cannot allocate memory for the new node. + pub fn try_create_and_insert( + &mut self, + key: K, + value: V, + flags: Flags, + ) -> Result>> { + Ok(self.insert(RBTreeNode::new(key, value, flags)?)) + } + + /// Inserts a new node into the tree. + /// + /// It overwrites a node if one already exists with the same key and r= eturns it (containing the + /// key/value pair). Returns [`None`] if a node with the same key didn= 't already exist. + /// + /// This function always succeeds. + pub fn insert(&mut self, RBTreeNode { node }: RBTreeNode) -> Opt= ion> { + let node =3D Box::into_raw(node); + // SAFETY: `node` is valid at least until we call `Box::from_raw`,= which only happens when + // the node is removed or replaced. + let node_links =3D unsafe { addr_of_mut!((*node).links) }; + + // The parameters of `rb_link_node` are as follows: + // - `node`: A pointer to an uninitialized node being inserted. + // - `parent`: A pointer to an existing node in the tree. One of i= ts child pointers must be + // null, and `node` will become a child of `parent` by re= placing that child pointer + // with a pointer to `node`. + // - `rb_link`: A pointer to either the left-child or right-child = field of `parent`. This + // specifies which child of `parent` should hold `node` a= fter this call. The + // value of `*rb_link` must be null before the call to `r= b_link_node`. If the + // red/black tree is empty, then it=E2=80=99s also possib= le for `parent` to be null. In + // this case, `rb_link` is a pointer to the `root` field = of the red/black tree. + // + // We will traverse the tree looking for a node that has a null po= inter as its child, + // representing an empty subtree where we can insert our new node.= We need to make sure + // that we preserve the ordering of the nodes in the tree. In each= iteration of the loop + // we store `parent` and `child_field_of_parent`, and the new `nod= e` will go somewhere + // in the subtree of `parent` that `child_field_of_parent` points = at. Once + // we find an empty subtree, we can insert the new node using `rb_= link_node`. + let mut parent =3D core::ptr::null_mut(); + let mut child_field_of_parent: &mut *mut bindings::rb_node =3D &mu= t self.root.rb_node; + while !child_field_of_parent.is_null() { + parent =3D *child_field_of_parent; + + // We need to determine whether `node` should be the left or r= ight child of `parent`, + // so we will compare with the `key` field of `parent` a.k.a. = `this` below. + // + // SAFETY: By the type invariant of `Self`, all non-null `rb_n= ode` pointers stored in `self` + // point to the links field of `Node` objects. + let this =3D unsafe { container_of!(parent, Node, links)= }; + + // SAFETY: `this` is a non-null node so it is valid by the typ= e invariants. `node` is + // valid until the node is removed. + match unsafe { (*node).key.cmp(&(*this).key) } { + // We would like `node` to be the left child of `parent`. = Move to this child to check + // whether we can use it, or continue searching, at the ne= xt iteration. + // + // SAFETY: `parent` is a non-null node so it is valid by t= he type invariants. + Ordering::Less =3D> child_field_of_parent =3D unsafe { &mu= t (*parent).rb_left }, + // We would like `node` to be the right child of `parent`.= Move to this child to check + // whether we can use it, or continue searching, at the ne= xt iteration. + // + // SAFETY: `parent` is a non-null node so it is valid by t= he type invariants. + Ordering::Greater =3D> child_field_of_parent =3D unsafe { = &mut (*parent).rb_right }, + Ordering::Equal =3D> { + // There is an existing node in the tree with this key= , and that node is + // parent. Thus, we are replacing parent with a new n= ode. + // + // INVARIANT: We are replacing an existing node with a= new one, which is valid. + // It remains valid because we "forgot" it with `Box::= into_raw`. + // SAFETY: All pointers are non-null and valid. + unsafe { bindings::rb_replace_node(parent, node_links,= &mut self.root) }; + + // INVARIANT: The node is being returned and the calle= r may free it, however, + // it was removed from the tree. So the invariants sti= ll hold. + return Some(RBTreeNode { + // SAFETY: `this` was a node in the tree, so it is= valid. + node: unsafe { Box::from_raw(this.cast_mut()) }, + }); + } + } + } + + // INVARIANT: We are linking in a new node, which is valid. It rem= ains valid because we + // "forgot" it with `Box::into_raw`. + // SAFETY: All pointers are non-null and valid (`*child_field_of_p= arent` is null, but `child_field_of_parent` is a + // mutable reference). + unsafe { bindings::rb_link_node(node_links, parent, child_field_of= _parent) }; + + // SAFETY: All pointers are valid. `node` has just been inserted i= nto the tree. + unsafe { bindings::rb_insert_color(node_links, &mut self.root) }; + None + } + + /// Returns a node with the given key, if one exists. + fn find(&self, key: &K) -> Option>> { + let mut node =3D self.root.rb_node; + while !node.is_null() { + // SAFETY: By the type invariant of `Self`, all non-null `rb_n= ode` pointers stored in `self` + // point to the links field of `Node` objects. + let this =3D unsafe { container_of!(node, Node, links) }= ; + // SAFETY: `this` is a non-null node so it is valid by the typ= e invariants. + node =3D match key.cmp(unsafe { &(*this).key }) { + // SAFETY: `node` is a non-null node so it is valid by the= type invariants. + Ordering::Less =3D> unsafe { (*node).rb_left }, + // SAFETY: `node` is a non-null node so it is valid by the= type invariants. + Ordering::Greater =3D> unsafe { (*node).rb_right }, + Ordering::Equal =3D> return NonNull::new(this.cast_mut()), + } + } + None + } + + /// Returns a reference to the value corresponding to the key. + pub fn get(&self, key: &K) -> Option<&V> { + // SAFETY: The `find` return value is a node in the tree, so it is= valid. + self.find(key).map(|node| unsafe { &node.as_ref().value }) + } + + /// Returns a mutable reference to the value corresponding to the key. + pub fn get_mut(&mut self, key: &K) -> Option<&mut V> { + // SAFETY: The `find` return value is a node in the tree, so it is= valid. + self.find(key) + .map(|mut node| unsafe { &mut node.as_mut().value }) + } + + /// Removes the node with the given key from the tree. + /// + /// It returns the node that was removed if one exists, or [`None`] ot= herwise. + fn remove_node(&mut self, key: &K) -> Option> { + let mut node =3D self.find(key)?; + + // SAFETY: The `find` return value is a node in the tree, so it is= valid. + unsafe { bindings::rb_erase(&mut node.as_mut().links, &mut self.ro= ot) }; + + // INVARIANT: The node is being returned and the caller may free i= t, however, it was + // removed from the tree. So the invariants still hold. + Some(RBTreeNode { + // SAFETY: The `find` return value was a node in the tree, so = it is valid. + node: unsafe { Box::from_raw(node.as_ptr()) }, + }) + } + + /// Removes the node with the given key from the tree. + /// + /// It returns the value that was removed if one exists, or [`None`] o= therwise. + pub fn remove(&mut self, key: &K) -> Option { + self.remove_node(key).map(|node| node.node.value) + } +} + +impl Default for RBTree { + fn default() -> Self { + Self::new() + } +} + +impl Drop for RBTree { + fn drop(&mut self) { + // SAFETY: `root` is valid as it's embedded in `self` and we have = a valid `self`. + let mut next =3D unsafe { bindings::rb_first_postorder(&self.root)= }; + + // INVARIANT: The loop invariant is that all tree nodes from `next= ` in postorder are valid. + while !next.is_null() { + // SAFETY: All links fields we create are in a `Node`. + let this =3D unsafe { container_of!(next, Node, links) }= ; + + // Find out what the next node is before disposing of the curr= ent one. + // SAFETY: `next` and all nodes in postorder are still valid. + next =3D unsafe { bindings::rb_next_postorder(next) }; + + // INVARIANT: This is the destructor, so we break the type inv= ariant during clean-up, + // but it is not observable. The loop invariant is still maint= ained. + + // SAFETY: `this` is valid per the loop invariant. + unsafe { drop(Box::from_raw(this.cast_mut())) }; + } + } +} + +/// 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 +/// can be obtained by directly allocating it ([`RBTreeNodeReservation::ne= w`]). +pub struct RBTreeNodeReservation { + node: Box>>, +} + +impl RBTreeNodeReservation { + /// Allocates memory for a node to be eventually initialised and inser= ted into the tree via a + /// call to [`RBTree::insert`]. + pub fn new(flags: Flags) -> Result> { + Ok(RBTreeNodeReservation { + node: Box::new_uninit(flags)?, + }) + } +} + +// SAFETY: This doesn't actually contain K or V, and is just a memory allo= cation. Those can always +// be moved across threads. +unsafe impl Send for RBTreeNodeReservation {} + +// SAFETY: This doesn't actually contain K or V, and is just a memory allo= cation. +unsafe impl Sync for RBTreeNodeReservation {} + +impl RBTreeNodeReservation { + /// Initialises a node reservation. + /// + /// It then becomes an [`RBTreeNode`] that can be inserted into a tree= . + pub fn into_node(self, key: K, value: V) -> RBTreeNode { + let node =3D Box::write( + self.node, + Node { + key, + value, + links: bindings::rb_node::default(), + }, + ); + RBTreeNode { node } + } +} + +/// A red-black tree node. +/// +/// The node is fully initialised (with key and value) and can be inserted= into a tree without any +/// extra allocations or failure paths. +pub struct RBTreeNode { + node: Box>, +} + +impl RBTreeNode { + /// Allocates and initialises a node that can be inserted into the tre= e via + /// [`RBTree::insert`]. + pub fn new(key: K, value: V, flags: Flags) -> Result>= { + Ok(RBTreeNodeReservation::new(flags)?.into_node(key, value)) + } +} + +// SAFETY: If K and V can be sent across threads, then it's also okay to s= end [`RBTreeNode`] across +// threads. +unsafe impl Send for RBTreeNode {} + +// SAFETY: If K and V can be accessed without synchronization, then it's a= lso okay to access +// [`RBTreeNode`] without synchronization. +unsafe impl Sync for RBTreeNode {} + +struct Node { + links: bindings::rb_node, + key: K, + value: V, +} --=20 2.45.1.467.gbab1589fc0-goog