rbtree.rs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! Red-black trees.
  3. //!
  4. //! C header: [`include/linux/rbtree.h`](srctree/include/linux/rbtree.h)
  5. //!
  6. //! Reference: <https://docs.kernel.org/core-api/rbtree.html>
  7. use crate::{alloc::Flags, bindings, container_of, error::Result, prelude::*};
  8. use alloc::boxed::Box;
  9. use core::{
  10. cmp::{Ord, Ordering},
  11. marker::PhantomData,
  12. mem::MaybeUninit,
  13. ptr::{addr_of_mut, from_mut, NonNull},
  14. };
  15. /// A red-black tree with owned nodes.
  16. ///
  17. /// It is backed by the kernel C red-black trees.
  18. ///
  19. /// # Examples
  20. ///
  21. /// In the example below we do several operations on a tree. We note that insertions may fail if
  22. /// the system is out of memory.
  23. ///
  24. /// ```
  25. /// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNode, RBTreeNodeReservation}};
  26. ///
  27. /// // Create a new tree.
  28. /// let mut tree = RBTree::new();
  29. ///
  30. /// // Insert three elements.
  31. /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
  32. /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
  33. /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
  34. ///
  35. /// // Check the nodes we just inserted.
  36. /// {
  37. /// assert_eq!(tree.get(&10).unwrap(), &100);
  38. /// assert_eq!(tree.get(&20).unwrap(), &200);
  39. /// assert_eq!(tree.get(&30).unwrap(), &300);
  40. /// }
  41. ///
  42. /// // Iterate over the nodes we just inserted.
  43. /// {
  44. /// let mut iter = tree.iter();
  45. /// assert_eq!(iter.next().unwrap(), (&10, &100));
  46. /// assert_eq!(iter.next().unwrap(), (&20, &200));
  47. /// assert_eq!(iter.next().unwrap(), (&30, &300));
  48. /// assert!(iter.next().is_none());
  49. /// }
  50. ///
  51. /// // Print all elements.
  52. /// for (key, value) in &tree {
  53. /// pr_info!("{} = {}\n", key, value);
  54. /// }
  55. ///
  56. /// // Replace one of the elements.
  57. /// tree.try_create_and_insert(10, 1000, flags::GFP_KERNEL)?;
  58. ///
  59. /// // Check that the tree reflects the replacement.
  60. /// {
  61. /// let mut iter = tree.iter();
  62. /// assert_eq!(iter.next().unwrap(), (&10, &1000));
  63. /// assert_eq!(iter.next().unwrap(), (&20, &200));
  64. /// assert_eq!(iter.next().unwrap(), (&30, &300));
  65. /// assert!(iter.next().is_none());
  66. /// }
  67. ///
  68. /// // Change the value of one of the elements.
  69. /// *tree.get_mut(&30).unwrap() = 3000;
  70. ///
  71. /// // Check that the tree reflects the update.
  72. /// {
  73. /// let mut iter = tree.iter();
  74. /// assert_eq!(iter.next().unwrap(), (&10, &1000));
  75. /// assert_eq!(iter.next().unwrap(), (&20, &200));
  76. /// assert_eq!(iter.next().unwrap(), (&30, &3000));
  77. /// assert!(iter.next().is_none());
  78. /// }
  79. ///
  80. /// // Remove an element.
  81. /// tree.remove(&10);
  82. ///
  83. /// // Check that the tree reflects the removal.
  84. /// {
  85. /// let mut iter = tree.iter();
  86. /// assert_eq!(iter.next().unwrap(), (&20, &200));
  87. /// assert_eq!(iter.next().unwrap(), (&30, &3000));
  88. /// assert!(iter.next().is_none());
  89. /// }
  90. ///
  91. /// # Ok::<(), Error>(())
  92. /// ```
  93. ///
  94. /// In the example below, we first allocate a node, acquire a spinlock, then insert the node into
  95. /// the tree. This is useful when the insertion context does not allow sleeping, for example, when
  96. /// holding a spinlock.
  97. ///
  98. /// ```
  99. /// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNode}, sync::SpinLock};
  100. ///
  101. /// fn insert_test(tree: &SpinLock<RBTree<u32, u32>>) -> Result {
  102. /// // Pre-allocate node. This may fail (as it allocates memory).
  103. /// let node = RBTreeNode::new(10, 100, flags::GFP_KERNEL)?;
  104. ///
  105. /// // Insert node while holding the lock. It is guaranteed to succeed with no allocation
  106. /// // attempts.
  107. /// let mut guard = tree.lock();
  108. /// guard.insert(node);
  109. /// Ok(())
  110. /// }
  111. /// ```
  112. ///
  113. /// In the example below, we reuse an existing node allocation from an element we removed.
  114. ///
  115. /// ```
  116. /// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNodeReservation}};
  117. ///
  118. /// // Create a new tree.
  119. /// let mut tree = RBTree::new();
  120. ///
  121. /// // Insert three elements.
  122. /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
  123. /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
  124. /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
  125. ///
  126. /// // Check the nodes we just inserted.
  127. /// {
  128. /// let mut iter = tree.iter();
  129. /// assert_eq!(iter.next().unwrap(), (&10, &100));
  130. /// assert_eq!(iter.next().unwrap(), (&20, &200));
  131. /// assert_eq!(iter.next().unwrap(), (&30, &300));
  132. /// assert!(iter.next().is_none());
  133. /// }
  134. ///
  135. /// // Remove a node, getting back ownership of it.
  136. /// let existing = tree.remove(&30).unwrap();
  137. ///
  138. /// // Check that the tree reflects the removal.
  139. /// {
  140. /// let mut iter = tree.iter();
  141. /// assert_eq!(iter.next().unwrap(), (&10, &100));
  142. /// assert_eq!(iter.next().unwrap(), (&20, &200));
  143. /// assert!(iter.next().is_none());
  144. /// }
  145. ///
  146. /// // Create a preallocated reservation that we can re-use later.
  147. /// let reservation = RBTreeNodeReservation::new(flags::GFP_KERNEL)?;
  148. ///
  149. /// // Insert a new node into the tree, reusing the previous allocation. This is guaranteed to
  150. /// // succeed (no memory allocations).
  151. /// tree.insert(reservation.into_node(15, 150));
  152. ///
  153. /// // Check that the tree reflect the new insertion.
  154. /// {
  155. /// let mut iter = tree.iter();
  156. /// assert_eq!(iter.next().unwrap(), (&10, &100));
  157. /// assert_eq!(iter.next().unwrap(), (&15, &150));
  158. /// assert_eq!(iter.next().unwrap(), (&20, &200));
  159. /// assert!(iter.next().is_none());
  160. /// }
  161. ///
  162. /// # Ok::<(), Error>(())
  163. /// ```
  164. ///
  165. /// # Invariants
  166. ///
  167. /// Non-null parent/children pointers stored in instances of the `rb_node` C struct are always
  168. /// valid, and pointing to a field of our internal representation of a node.
  169. pub struct RBTree<K, V> {
  170. root: bindings::rb_root,
  171. _p: PhantomData<Node<K, V>>,
  172. }
  173. // SAFETY: An [`RBTree`] allows the same kinds of access to its values that a struct allows to its
  174. // fields, so we use the same Send condition as would be used for a struct with K and V fields.
  175. unsafe impl<K: Send, V: Send> Send for RBTree<K, V> {}
  176. // SAFETY: An [`RBTree`] allows the same kinds of access to its values that a struct allows to its
  177. // fields, so we use the same Sync condition as would be used for a struct with K and V fields.
  178. unsafe impl<K: Sync, V: Sync> Sync for RBTree<K, V> {}
  179. impl<K, V> RBTree<K, V> {
  180. /// Creates a new and empty tree.
  181. pub fn new() -> Self {
  182. Self {
  183. // INVARIANT: There are no nodes in the tree, so the invariant holds vacuously.
  184. root: bindings::rb_root::default(),
  185. _p: PhantomData,
  186. }
  187. }
  188. /// Returns an iterator over the tree nodes, sorted by key.
  189. pub fn iter(&self) -> Iter<'_, K, V> {
  190. Iter {
  191. _tree: PhantomData,
  192. // INVARIANT:
  193. // - `self.root` is a valid pointer to a tree root.
  194. // - `bindings::rb_first` produces a valid pointer to a node given `root` is valid.
  195. iter_raw: IterRaw {
  196. // SAFETY: by the invariants, all pointers are valid.
  197. next: unsafe { bindings::rb_first(&self.root) },
  198. _phantom: PhantomData,
  199. },
  200. }
  201. }
  202. /// Returns a mutable iterator over the tree nodes, sorted by key.
  203. pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
  204. IterMut {
  205. _tree: PhantomData,
  206. // INVARIANT:
  207. // - `self.root` is a valid pointer to a tree root.
  208. // - `bindings::rb_first` produces a valid pointer to a node given `root` is valid.
  209. iter_raw: IterRaw {
  210. // SAFETY: by the invariants, all pointers are valid.
  211. next: unsafe { bindings::rb_first(from_mut(&mut self.root)) },
  212. _phantom: PhantomData,
  213. },
  214. }
  215. }
  216. /// Returns an iterator over the keys of the nodes in the tree, in sorted order.
  217. pub fn keys(&self) -> impl Iterator<Item = &'_ K> {
  218. self.iter().map(|(k, _)| k)
  219. }
  220. /// Returns an iterator over the values of the nodes in the tree, sorted by key.
  221. pub fn values(&self) -> impl Iterator<Item = &'_ V> {
  222. self.iter().map(|(_, v)| v)
  223. }
  224. /// Returns a mutable iterator over the values of the nodes in the tree, sorted by key.
  225. pub fn values_mut(&mut self) -> impl Iterator<Item = &'_ mut V> {
  226. self.iter_mut().map(|(_, v)| v)
  227. }
  228. /// Returns a cursor over the tree nodes, starting with the smallest key.
  229. pub fn cursor_front(&mut self) -> Option<Cursor<'_, K, V>> {
  230. let root = addr_of_mut!(self.root);
  231. // SAFETY: `self.root` is always a valid root node
  232. let current = unsafe { bindings::rb_first(root) };
  233. NonNull::new(current).map(|current| {
  234. // INVARIANT:
  235. // - `current` is a valid node in the [`RBTree`] pointed to by `self`.
  236. Cursor {
  237. current,
  238. tree: self,
  239. }
  240. })
  241. }
  242. /// Returns a cursor over the tree nodes, starting with the largest key.
  243. pub fn cursor_back(&mut self) -> Option<Cursor<'_, K, V>> {
  244. let root = addr_of_mut!(self.root);
  245. // SAFETY: `self.root` is always a valid root node
  246. let current = unsafe { bindings::rb_last(root) };
  247. NonNull::new(current).map(|current| {
  248. // INVARIANT:
  249. // - `current` is a valid node in the [`RBTree`] pointed to by `self`.
  250. Cursor {
  251. current,
  252. tree: self,
  253. }
  254. })
  255. }
  256. }
  257. impl<K, V> RBTree<K, V>
  258. where
  259. K: Ord,
  260. {
  261. /// Tries to insert a new value into the tree.
  262. ///
  263. /// It overwrites a node if one already exists with the same key and returns it (containing the
  264. /// key/value pair). Returns [`None`] if a node with the same key didn't already exist.
  265. ///
  266. /// Returns an error if it cannot allocate memory for the new node.
  267. pub fn try_create_and_insert(
  268. &mut self,
  269. key: K,
  270. value: V,
  271. flags: Flags,
  272. ) -> Result<Option<RBTreeNode<K, V>>> {
  273. Ok(self.insert(RBTreeNode::new(key, value, flags)?))
  274. }
  275. /// Inserts a new node into the tree.
  276. ///
  277. /// It overwrites a node if one already exists with the same key and returns it (containing the
  278. /// key/value pair). Returns [`None`] if a node with the same key didn't already exist.
  279. ///
  280. /// This function always succeeds.
  281. pub fn insert(&mut self, node: RBTreeNode<K, V>) -> Option<RBTreeNode<K, V>> {
  282. match self.raw_entry(&node.node.key) {
  283. RawEntry::Occupied(entry) => Some(entry.replace(node)),
  284. RawEntry::Vacant(entry) => {
  285. entry.insert(node);
  286. None
  287. }
  288. }
  289. }
  290. fn raw_entry(&mut self, key: &K) -> RawEntry<'_, K, V> {
  291. let raw_self: *mut RBTree<K, V> = self;
  292. // The returned `RawEntry` is used to call either `rb_link_node` or `rb_replace_node`.
  293. // The parameters of `bindings::rb_link_node` are as follows:
  294. // - `node`: A pointer to an uninitialized node being inserted.
  295. // - `parent`: A pointer to an existing node in the tree. One of its child pointers must be
  296. // null, and `node` will become a child of `parent` by replacing that child pointer
  297. // with a pointer to `node`.
  298. // - `rb_link`: A pointer to either the left-child or right-child field of `parent`. This
  299. // specifies which child of `parent` should hold `node` after this call. The
  300. // value of `*rb_link` must be null before the call to `rb_link_node`. If the
  301. // red/black tree is empty, then it’s also possible for `parent` to be null. In
  302. // this case, `rb_link` is a pointer to the `root` field of the red/black tree.
  303. //
  304. // We will traverse the tree looking for a node that has a null pointer as its child,
  305. // representing an empty subtree where we can insert our new node. We need to make sure
  306. // that we preserve the ordering of the nodes in the tree. In each iteration of the loop
  307. // we store `parent` and `child_field_of_parent`, and the new `node` will go somewhere
  308. // in the subtree of `parent` that `child_field_of_parent` points at. Once
  309. // we find an empty subtree, we can insert the new node using `rb_link_node`.
  310. let mut parent = core::ptr::null_mut();
  311. let mut child_field_of_parent: &mut *mut bindings::rb_node =
  312. // SAFETY: `raw_self` is a valid pointer to the `RBTree` (created from `self` above).
  313. unsafe { &mut (*raw_self).root.rb_node };
  314. while !(*child_field_of_parent).is_null() {
  315. let curr = *child_field_of_parent;
  316. // SAFETY: All links fields we create are in a `Node<K, V>`.
  317. let node = unsafe { container_of!(curr, Node<K, V>, links) };
  318. // SAFETY: `node` is a non-null node so it is valid by the type invariants.
  319. match key.cmp(unsafe { &(*node).key }) {
  320. // SAFETY: `curr` is a non-null node so it is valid by the type invariants.
  321. Ordering::Less => child_field_of_parent = unsafe { &mut (*curr).rb_left },
  322. // SAFETY: `curr` is a non-null node so it is valid by the type invariants.
  323. Ordering::Greater => child_field_of_parent = unsafe { &mut (*curr).rb_right },
  324. Ordering::Equal => {
  325. return RawEntry::Occupied(OccupiedEntry {
  326. rbtree: self,
  327. node_links: curr,
  328. })
  329. }
  330. }
  331. parent = curr;
  332. }
  333. RawEntry::Vacant(RawVacantEntry {
  334. rbtree: raw_self,
  335. parent,
  336. child_field_of_parent,
  337. _phantom: PhantomData,
  338. })
  339. }
  340. /// Gets the given key's corresponding entry in the map for in-place manipulation.
  341. pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
  342. match self.raw_entry(&key) {
  343. RawEntry::Occupied(entry) => Entry::Occupied(entry),
  344. RawEntry::Vacant(entry) => Entry::Vacant(VacantEntry { raw: entry, key }),
  345. }
  346. }
  347. /// Used for accessing the given node, if it exists.
  348. pub fn find_mut(&mut self, key: &K) -> Option<OccupiedEntry<'_, K, V>> {
  349. match self.raw_entry(key) {
  350. RawEntry::Occupied(entry) => Some(entry),
  351. RawEntry::Vacant(_entry) => None,
  352. }
  353. }
  354. /// Returns a reference to the value corresponding to the key.
  355. pub fn get(&self, key: &K) -> Option<&V> {
  356. let mut node = self.root.rb_node;
  357. while !node.is_null() {
  358. // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
  359. // point to the links field of `Node<K, V>` objects.
  360. let this = unsafe { container_of!(node, Node<K, V>, links) };
  361. // SAFETY: `this` is a non-null node so it is valid by the type invariants.
  362. node = match key.cmp(unsafe { &(*this).key }) {
  363. // SAFETY: `node` is a non-null node so it is valid by the type invariants.
  364. Ordering::Less => unsafe { (*node).rb_left },
  365. // SAFETY: `node` is a non-null node so it is valid by the type invariants.
  366. Ordering::Greater => unsafe { (*node).rb_right },
  367. // SAFETY: `node` is a non-null node so it is valid by the type invariants.
  368. Ordering::Equal => return Some(unsafe { &(*this).value }),
  369. }
  370. }
  371. None
  372. }
  373. /// Returns a mutable reference to the value corresponding to the key.
  374. pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
  375. self.find_mut(key).map(|node| node.into_mut())
  376. }
  377. /// Removes the node with the given key from the tree.
  378. ///
  379. /// It returns the node that was removed if one exists, or [`None`] otherwise.
  380. pub fn remove_node(&mut self, key: &K) -> Option<RBTreeNode<K, V>> {
  381. self.find_mut(key).map(OccupiedEntry::remove_node)
  382. }
  383. /// Removes the node with the given key from the tree.
  384. ///
  385. /// It returns the value that was removed if one exists, or [`None`] otherwise.
  386. pub fn remove(&mut self, key: &K) -> Option<V> {
  387. self.find_mut(key).map(OccupiedEntry::remove)
  388. }
  389. /// Returns a cursor over the tree nodes based on the given key.
  390. ///
  391. /// If the given key exists, the cursor starts there.
  392. /// Otherwise it starts with the first larger key in sort order.
  393. /// If there is no larger key, it returns [`None`].
  394. pub fn cursor_lower_bound(&mut self, key: &K) -> Option<Cursor<'_, K, V>>
  395. where
  396. K: Ord,
  397. {
  398. let mut node = self.root.rb_node;
  399. let mut best_match: Option<NonNull<Node<K, V>>> = None;
  400. while !node.is_null() {
  401. // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
  402. // point to the links field of `Node<K, V>` objects.
  403. let this = unsafe { container_of!(node, Node<K, V>, links) }.cast_mut();
  404. // SAFETY: `this` is a non-null node so it is valid by the type invariants.
  405. let this_key = unsafe { &(*this).key };
  406. // SAFETY: `node` is a non-null node so it is valid by the type invariants.
  407. let left_child = unsafe { (*node).rb_left };
  408. // SAFETY: `node` is a non-null node so it is valid by the type invariants.
  409. let right_child = unsafe { (*node).rb_right };
  410. match key.cmp(this_key) {
  411. Ordering::Equal => {
  412. best_match = NonNull::new(this);
  413. break;
  414. }
  415. Ordering::Greater => {
  416. node = right_child;
  417. }
  418. Ordering::Less => {
  419. let is_better_match = match best_match {
  420. None => true,
  421. Some(best) => {
  422. // SAFETY: `best` is a non-null node so it is valid by the type invariants.
  423. let best_key = unsafe { &(*best.as_ptr()).key };
  424. best_key > this_key
  425. }
  426. };
  427. if is_better_match {
  428. best_match = NonNull::new(this);
  429. }
  430. node = left_child;
  431. }
  432. };
  433. }
  434. let best = best_match?;
  435. // SAFETY: `best` is a non-null node so it is valid by the type invariants.
  436. let links = unsafe { addr_of_mut!((*best.as_ptr()).links) };
  437. NonNull::new(links).map(|current| {
  438. // INVARIANT:
  439. // - `current` is a valid node in the [`RBTree`] pointed to by `self`.
  440. Cursor {
  441. current,
  442. tree: self,
  443. }
  444. })
  445. }
  446. }
  447. impl<K, V> Default for RBTree<K, V> {
  448. fn default() -> Self {
  449. Self::new()
  450. }
  451. }
  452. impl<K, V> Drop for RBTree<K, V> {
  453. fn drop(&mut self) {
  454. // SAFETY: `root` is valid as it's embedded in `self` and we have a valid `self`.
  455. let mut next = unsafe { bindings::rb_first_postorder(&self.root) };
  456. // INVARIANT: The loop invariant is that all tree nodes from `next` in postorder are valid.
  457. while !next.is_null() {
  458. // SAFETY: All links fields we create are in a `Node<K, V>`.
  459. let this = unsafe { container_of!(next, Node<K, V>, links) };
  460. // Find out what the next node is before disposing of the current one.
  461. // SAFETY: `next` and all nodes in postorder are still valid.
  462. next = unsafe { bindings::rb_next_postorder(next) };
  463. // INVARIANT: This is the destructor, so we break the type invariant during clean-up,
  464. // but it is not observable. The loop invariant is still maintained.
  465. // SAFETY: `this` is valid per the loop invariant.
  466. unsafe { drop(Box::from_raw(this.cast_mut())) };
  467. }
  468. }
  469. }
  470. /// A bidirectional cursor over the tree nodes, sorted by key.
  471. ///
  472. /// # Examples
  473. ///
  474. /// In the following example, we obtain a cursor to the first element in the tree.
  475. /// The cursor allows us to iterate bidirectionally over key/value pairs in the tree.
  476. ///
  477. /// ```
  478. /// use kernel::{alloc::flags, rbtree::RBTree};
  479. ///
  480. /// // Create a new tree.
  481. /// let mut tree = RBTree::new();
  482. ///
  483. /// // Insert three elements.
  484. /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
  485. /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
  486. /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
  487. ///
  488. /// // Get a cursor to the first element.
  489. /// let mut cursor = tree.cursor_front().unwrap();
  490. /// let mut current = cursor.current();
  491. /// assert_eq!(current, (&10, &100));
  492. ///
  493. /// // Move the cursor, updating it to the 2nd element.
  494. /// cursor = cursor.move_next().unwrap();
  495. /// current = cursor.current();
  496. /// assert_eq!(current, (&20, &200));
  497. ///
  498. /// // Peek at the next element without impacting the cursor.
  499. /// let next = cursor.peek_next().unwrap();
  500. /// assert_eq!(next, (&30, &300));
  501. /// current = cursor.current();
  502. /// assert_eq!(current, (&20, &200));
  503. ///
  504. /// // Moving past the last element causes the cursor to return [`None`].
  505. /// cursor = cursor.move_next().unwrap();
  506. /// current = cursor.current();
  507. /// assert_eq!(current, (&30, &300));
  508. /// let cursor = cursor.move_next();
  509. /// assert!(cursor.is_none());
  510. ///
  511. /// # Ok::<(), Error>(())
  512. /// ```
  513. ///
  514. /// A cursor can also be obtained at the last element in the tree.
  515. ///
  516. /// ```
  517. /// use kernel::{alloc::flags, rbtree::RBTree};
  518. ///
  519. /// // Create a new tree.
  520. /// let mut tree = RBTree::new();
  521. ///
  522. /// // Insert three elements.
  523. /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
  524. /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
  525. /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
  526. ///
  527. /// let mut cursor = tree.cursor_back().unwrap();
  528. /// let current = cursor.current();
  529. /// assert_eq!(current, (&30, &300));
  530. ///
  531. /// # Ok::<(), Error>(())
  532. /// ```
  533. ///
  534. /// Obtaining a cursor returns [`None`] if the tree is empty.
  535. ///
  536. /// ```
  537. /// use kernel::rbtree::RBTree;
  538. ///
  539. /// let mut tree: RBTree<u16, u16> = RBTree::new();
  540. /// assert!(tree.cursor_front().is_none());
  541. ///
  542. /// # Ok::<(), Error>(())
  543. /// ```
  544. ///
  545. /// [`RBTree::cursor_lower_bound`] can be used to start at an arbitrary node in the tree.
  546. ///
  547. /// ```
  548. /// use kernel::{alloc::flags, rbtree::RBTree};
  549. ///
  550. /// // Create a new tree.
  551. /// let mut tree = RBTree::new();
  552. ///
  553. /// // Insert five elements.
  554. /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
  555. /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
  556. /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
  557. /// tree.try_create_and_insert(40, 400, flags::GFP_KERNEL)?;
  558. /// tree.try_create_and_insert(50, 500, flags::GFP_KERNEL)?;
  559. ///
  560. /// // If the provided key exists, a cursor to that key is returned.
  561. /// let cursor = tree.cursor_lower_bound(&20).unwrap();
  562. /// let current = cursor.current();
  563. /// assert_eq!(current, (&20, &200));
  564. ///
  565. /// // If the provided key doesn't exist, a cursor to the first larger element in sort order is returned.
  566. /// let cursor = tree.cursor_lower_bound(&25).unwrap();
  567. /// let current = cursor.current();
  568. /// assert_eq!(current, (&30, &300));
  569. ///
  570. /// // If there is no larger key, [`None`] is returned.
  571. /// let cursor = tree.cursor_lower_bound(&55);
  572. /// assert!(cursor.is_none());
  573. ///
  574. /// # Ok::<(), Error>(())
  575. /// ```
  576. ///
  577. /// The cursor allows mutation of values in the tree.
  578. ///
  579. /// ```
  580. /// use kernel::{alloc::flags, rbtree::RBTree};
  581. ///
  582. /// // Create a new tree.
  583. /// let mut tree = RBTree::new();
  584. ///
  585. /// // Insert three elements.
  586. /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
  587. /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
  588. /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
  589. ///
  590. /// // Retrieve a cursor.
  591. /// let mut cursor = tree.cursor_front().unwrap();
  592. ///
  593. /// // Get a mutable reference to the current value.
  594. /// let (k, v) = cursor.current_mut();
  595. /// *v = 1000;
  596. ///
  597. /// // The updated value is reflected in the tree.
  598. /// let updated = tree.get(&10).unwrap();
  599. /// assert_eq!(updated, &1000);
  600. ///
  601. /// # Ok::<(), Error>(())
  602. /// ```
  603. ///
  604. /// It also allows node removal. The following examples demonstrate the behavior of removing the current node.
  605. ///
  606. /// ```
  607. /// use kernel::{alloc::flags, rbtree::RBTree};
  608. ///
  609. /// // Create a new tree.
  610. /// let mut tree = RBTree::new();
  611. ///
  612. /// // Insert three elements.
  613. /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
  614. /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
  615. /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
  616. ///
  617. /// // Remove the first element.
  618. /// let mut cursor = tree.cursor_front().unwrap();
  619. /// let mut current = cursor.current();
  620. /// assert_eq!(current, (&10, &100));
  621. /// cursor = cursor.remove_current().0.unwrap();
  622. ///
  623. /// // If a node exists after the current element, it is returned.
  624. /// current = cursor.current();
  625. /// assert_eq!(current, (&20, &200));
  626. ///
  627. /// // Get a cursor to the last element, and remove it.
  628. /// cursor = tree.cursor_back().unwrap();
  629. /// current = cursor.current();
  630. /// assert_eq!(current, (&30, &300));
  631. ///
  632. /// // Since there is no next node, the previous node is returned.
  633. /// cursor = cursor.remove_current().0.unwrap();
  634. /// current = cursor.current();
  635. /// assert_eq!(current, (&20, &200));
  636. ///
  637. /// // Removing the last element in the tree returns [`None`].
  638. /// assert!(cursor.remove_current().0.is_none());
  639. ///
  640. /// # Ok::<(), Error>(())
  641. /// ```
  642. ///
  643. /// Nodes adjacent to the current node can also be removed.
  644. ///
  645. /// ```
  646. /// use kernel::{alloc::flags, rbtree::RBTree};
  647. ///
  648. /// // Create a new tree.
  649. /// let mut tree = RBTree::new();
  650. ///
  651. /// // Insert three elements.
  652. /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
  653. /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
  654. /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
  655. ///
  656. /// // Get a cursor to the first element.
  657. /// let mut cursor = tree.cursor_front().unwrap();
  658. /// let mut current = cursor.current();
  659. /// assert_eq!(current, (&10, &100));
  660. ///
  661. /// // Calling `remove_prev` from the first element returns [`None`].
  662. /// assert!(cursor.remove_prev().is_none());
  663. ///
  664. /// // Get a cursor to the last element.
  665. /// cursor = tree.cursor_back().unwrap();
  666. /// current = cursor.current();
  667. /// assert_eq!(current, (&30, &300));
  668. ///
  669. /// // Calling `remove_prev` removes and returns the middle element.
  670. /// assert_eq!(cursor.remove_prev().unwrap().to_key_value(), (20, 200));
  671. ///
  672. /// // Calling `remove_next` from the last element returns [`None`].
  673. /// assert!(cursor.remove_next().is_none());
  674. ///
  675. /// // Move to the first element
  676. /// cursor = cursor.move_prev().unwrap();
  677. /// current = cursor.current();
  678. /// assert_eq!(current, (&10, &100));
  679. ///
  680. /// // Calling `remove_next` removes and returns the last element.
  681. /// assert_eq!(cursor.remove_next().unwrap().to_key_value(), (30, 300));
  682. ///
  683. /// # Ok::<(), Error>(())
  684. ///
  685. /// ```
  686. ///
  687. /// # Invariants
  688. /// - `current` points to a node that is in the same [`RBTree`] as `tree`.
  689. pub struct Cursor<'a, K, V> {
  690. tree: &'a mut RBTree<K, V>,
  691. current: NonNull<bindings::rb_node>,
  692. }
  693. // SAFETY: The [`Cursor`] has exclusive access to both `K` and `V`, so it is sufficient to require them to be `Send`.
  694. // The cursor only gives out immutable references to the keys, but since it has excusive access to those same
  695. // keys, `Send` is sufficient. `Sync` would be okay, but it is more restrictive to the user.
  696. unsafe impl<'a, K: Send, V: Send> Send for Cursor<'a, K, V> {}
  697. // SAFETY: The [`Cursor`] gives out immutable references to K and mutable references to V,
  698. // so it has the same thread safety requirements as mutable references.
  699. unsafe impl<'a, K: Sync, V: Sync> Sync for Cursor<'a, K, V> {}
  700. impl<'a, K, V> Cursor<'a, K, V> {
  701. /// The current node
  702. pub fn current(&self) -> (&K, &V) {
  703. // SAFETY:
  704. // - `self.current` is a valid node by the type invariants.
  705. // - We have an immutable reference by the function signature.
  706. unsafe { Self::to_key_value(self.current) }
  707. }
  708. /// The current node, with a mutable value
  709. pub fn current_mut(&mut self) -> (&K, &mut V) {
  710. // SAFETY:
  711. // - `self.current` is a valid node by the type invariants.
  712. // - We have an mutable reference by the function signature.
  713. unsafe { Self::to_key_value_mut(self.current) }
  714. }
  715. /// Remove the current node from the tree.
  716. ///
  717. /// Returns a tuple where the first element is a cursor to the next node, if it exists,
  718. /// else the previous node, else [`None`] (if the tree becomes empty). The second element
  719. /// is the removed node.
  720. pub fn remove_current(self) -> (Option<Self>, RBTreeNode<K, V>) {
  721. let prev = self.get_neighbor_raw(Direction::Prev);
  722. let next = self.get_neighbor_raw(Direction::Next);
  723. // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
  724. // point to the links field of `Node<K, V>` objects.
  725. let this = unsafe { container_of!(self.current.as_ptr(), Node<K, V>, links) }.cast_mut();
  726. // SAFETY: `this` is valid by the type invariants as described above.
  727. let node = unsafe { Box::from_raw(this) };
  728. let node = RBTreeNode { node };
  729. // SAFETY: The reference to the tree used to create the cursor outlives the cursor, so
  730. // the tree cannot change. By the tree invariant, all nodes are valid.
  731. unsafe { bindings::rb_erase(&mut (*this).links, addr_of_mut!(self.tree.root)) };
  732. let current = match (prev, next) {
  733. (_, Some(next)) => next,
  734. (Some(prev), None) => prev,
  735. (None, None) => {
  736. return (None, node);
  737. }
  738. };
  739. (
  740. // INVARIANT:
  741. // - `current` is a valid node in the [`RBTree`] pointed to by `self.tree`.
  742. Some(Self {
  743. current,
  744. tree: self.tree,
  745. }),
  746. node,
  747. )
  748. }
  749. /// Remove the previous node, returning it if it exists.
  750. pub fn remove_prev(&mut self) -> Option<RBTreeNode<K, V>> {
  751. self.remove_neighbor(Direction::Prev)
  752. }
  753. /// Remove the next node, returning it if it exists.
  754. pub fn remove_next(&mut self) -> Option<RBTreeNode<K, V>> {
  755. self.remove_neighbor(Direction::Next)
  756. }
  757. fn remove_neighbor(&mut self, direction: Direction) -> Option<RBTreeNode<K, V>> {
  758. if let Some(neighbor) = self.get_neighbor_raw(direction) {
  759. let neighbor = neighbor.as_ptr();
  760. // SAFETY: The reference to the tree used to create the cursor outlives the cursor, so
  761. // the tree cannot change. By the tree invariant, all nodes are valid.
  762. unsafe { bindings::rb_erase(neighbor, addr_of_mut!(self.tree.root)) };
  763. // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
  764. // point to the links field of `Node<K, V>` objects.
  765. let this = unsafe { container_of!(neighbor, Node<K, V>, links) }.cast_mut();
  766. // SAFETY: `this` is valid by the type invariants as described above.
  767. let node = unsafe { Box::from_raw(this) };
  768. return Some(RBTreeNode { node });
  769. }
  770. None
  771. }
  772. /// Move the cursor to the previous node, returning [`None`] if it doesn't exist.
  773. pub fn move_prev(self) -> Option<Self> {
  774. self.mv(Direction::Prev)
  775. }
  776. /// Move the cursor to the next node, returning [`None`] if it doesn't exist.
  777. pub fn move_next(self) -> Option<Self> {
  778. self.mv(Direction::Next)
  779. }
  780. fn mv(self, direction: Direction) -> Option<Self> {
  781. // INVARIANT:
  782. // - `neighbor` is a valid node in the [`RBTree`] pointed to by `self.tree`.
  783. self.get_neighbor_raw(direction).map(|neighbor| Self {
  784. tree: self.tree,
  785. current: neighbor,
  786. })
  787. }
  788. /// Access the previous node without moving the cursor.
  789. pub fn peek_prev(&self) -> Option<(&K, &V)> {
  790. self.peek(Direction::Prev)
  791. }
  792. /// Access the previous node without moving the cursor.
  793. pub fn peek_next(&self) -> Option<(&K, &V)> {
  794. self.peek(Direction::Next)
  795. }
  796. fn peek(&self, direction: Direction) -> Option<(&K, &V)> {
  797. self.get_neighbor_raw(direction).map(|neighbor| {
  798. // SAFETY:
  799. // - `neighbor` is a valid tree node.
  800. // - By the function signature, we have an immutable reference to `self`.
  801. unsafe { Self::to_key_value(neighbor) }
  802. })
  803. }
  804. /// Access the previous node mutably without moving the cursor.
  805. pub fn peek_prev_mut(&mut self) -> Option<(&K, &mut V)> {
  806. self.peek_mut(Direction::Prev)
  807. }
  808. /// Access the next node mutably without moving the cursor.
  809. pub fn peek_next_mut(&mut self) -> Option<(&K, &mut V)> {
  810. self.peek_mut(Direction::Next)
  811. }
  812. fn peek_mut(&mut self, direction: Direction) -> Option<(&K, &mut V)> {
  813. self.get_neighbor_raw(direction).map(|neighbor| {
  814. // SAFETY:
  815. // - `neighbor` is a valid tree node.
  816. // - By the function signature, we have a mutable reference to `self`.
  817. unsafe { Self::to_key_value_mut(neighbor) }
  818. })
  819. }
  820. fn get_neighbor_raw(&self, direction: Direction) -> Option<NonNull<bindings::rb_node>> {
  821. // SAFETY: `self.current` is valid by the type invariants.
  822. let neighbor = unsafe {
  823. match direction {
  824. Direction::Prev => bindings::rb_prev(self.current.as_ptr()),
  825. Direction::Next => bindings::rb_next(self.current.as_ptr()),
  826. }
  827. };
  828. NonNull::new(neighbor)
  829. }
  830. /// # Safety
  831. ///
  832. /// - `node` must be a valid pointer to a node in an [`RBTree`].
  833. /// - The caller has immutable access to `node` for the duration of 'b.
  834. unsafe fn to_key_value<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, &'b V) {
  835. // SAFETY: the caller guarantees that `node` is a valid pointer in an `RBTree`.
  836. let (k, v) = unsafe { Self::to_key_value_raw(node) };
  837. // SAFETY: the caller guarantees immutable access to `node`.
  838. (k, unsafe { &*v })
  839. }
  840. /// # Safety
  841. ///
  842. /// - `node` must be a valid pointer to a node in an [`RBTree`].
  843. /// - The caller has mutable access to `node` for the duration of 'b.
  844. unsafe fn to_key_value_mut<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, &'b mut V) {
  845. // SAFETY: the caller guarantees that `node` is a valid pointer in an `RBTree`.
  846. let (k, v) = unsafe { Self::to_key_value_raw(node) };
  847. // SAFETY: the caller guarantees mutable access to `node`.
  848. (k, unsafe { &mut *v })
  849. }
  850. /// # Safety
  851. ///
  852. /// - `node` must be a valid pointer to a node in an [`RBTree`].
  853. /// - The caller has immutable access to the key for the duration of 'b.
  854. unsafe fn to_key_value_raw<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, *mut V) {
  855. // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
  856. // point to the links field of `Node<K, V>` objects.
  857. let this = unsafe { container_of!(node.as_ptr(), Node<K, V>, links) }.cast_mut();
  858. // SAFETY: The passed `node` is the current node or a non-null neighbor,
  859. // thus `this` is valid by the type invariants.
  860. let k = unsafe { &(*this).key };
  861. // SAFETY: The passed `node` is the current node or a non-null neighbor,
  862. // thus `this` is valid by the type invariants.
  863. let v = unsafe { addr_of_mut!((*this).value) };
  864. (k, v)
  865. }
  866. }
  867. /// Direction for [`Cursor`] operations.
  868. enum Direction {
  869. /// the node immediately before, in sort order
  870. Prev,
  871. /// the node immediately after, in sort order
  872. Next,
  873. }
  874. impl<'a, K, V> IntoIterator for &'a RBTree<K, V> {
  875. type Item = (&'a K, &'a V);
  876. type IntoIter = Iter<'a, K, V>;
  877. fn into_iter(self) -> Self::IntoIter {
  878. self.iter()
  879. }
  880. }
  881. /// An iterator over the nodes of a [`RBTree`].
  882. ///
  883. /// Instances are created by calling [`RBTree::iter`].
  884. pub struct Iter<'a, K, V> {
  885. _tree: PhantomData<&'a RBTree<K, V>>,
  886. iter_raw: IterRaw<K, V>,
  887. }
  888. // SAFETY: The [`Iter`] gives out immutable references to K and V, so it has the same
  889. // thread safety requirements as immutable references.
  890. unsafe impl<'a, K: Sync, V: Sync> Send for Iter<'a, K, V> {}
  891. // SAFETY: The [`Iter`] gives out immutable references to K and V, so it has the same
  892. // thread safety requirements as immutable references.
  893. unsafe impl<'a, K: Sync, V: Sync> Sync for Iter<'a, K, V> {}
  894. impl<'a, K, V> Iterator for Iter<'a, K, V> {
  895. type Item = (&'a K, &'a V);
  896. fn next(&mut self) -> Option<Self::Item> {
  897. // SAFETY: Due to `self._tree`, `k` and `v` are valid for the lifetime of `'a`.
  898. self.iter_raw.next().map(|(k, v)| unsafe { (&*k, &*v) })
  899. }
  900. }
  901. impl<'a, K, V> IntoIterator for &'a mut RBTree<K, V> {
  902. type Item = (&'a K, &'a mut V);
  903. type IntoIter = IterMut<'a, K, V>;
  904. fn into_iter(self) -> Self::IntoIter {
  905. self.iter_mut()
  906. }
  907. }
  908. /// A mutable iterator over the nodes of a [`RBTree`].
  909. ///
  910. /// Instances are created by calling [`RBTree::iter_mut`].
  911. pub struct IterMut<'a, K, V> {
  912. _tree: PhantomData<&'a mut RBTree<K, V>>,
  913. iter_raw: IterRaw<K, V>,
  914. }
  915. // SAFETY: The [`IterMut`] has exclusive access to both `K` and `V`, so it is sufficient to require them to be `Send`.
  916. // The iterator only gives out immutable references to the keys, but since the iterator has excusive access to those same
  917. // keys, `Send` is sufficient. `Sync` would be okay, but it is more restrictive to the user.
  918. unsafe impl<'a, K: Send, V: Send> Send for IterMut<'a, K, V> {}
  919. // SAFETY: The [`IterMut`] gives out immutable references to K and mutable references to V, so it has the same
  920. // thread safety requirements as mutable references.
  921. unsafe impl<'a, K: Sync, V: Sync> Sync for IterMut<'a, K, V> {}
  922. impl<'a, K, V> Iterator for IterMut<'a, K, V> {
  923. type Item = (&'a K, &'a mut V);
  924. fn next(&mut self) -> Option<Self::Item> {
  925. self.iter_raw.next().map(|(k, v)|
  926. // SAFETY: Due to `&mut self`, we have exclusive access to `k` and `v`, for the lifetime of `'a`.
  927. unsafe { (&*k, &mut *v) })
  928. }
  929. }
  930. /// A raw iterator over the nodes of a [`RBTree`].
  931. ///
  932. /// # Invariants
  933. /// - `self.next` is a valid pointer.
  934. /// - `self.next` points to a node stored inside of a valid `RBTree`.
  935. struct IterRaw<K, V> {
  936. next: *mut bindings::rb_node,
  937. _phantom: PhantomData<fn() -> (K, V)>,
  938. }
  939. impl<K, V> Iterator for IterRaw<K, V> {
  940. type Item = (*mut K, *mut V);
  941. fn next(&mut self) -> Option<Self::Item> {
  942. if self.next.is_null() {
  943. return None;
  944. }
  945. // SAFETY: By the type invariant of `IterRaw`, `self.next` is a valid node in an `RBTree`,
  946. // and by the type invariant of `RBTree`, all nodes point to the links field of `Node<K, V>` objects.
  947. let cur = unsafe { container_of!(self.next, Node<K, V>, links) }.cast_mut();
  948. // SAFETY: `self.next` is a valid tree node by the type invariants.
  949. self.next = unsafe { bindings::rb_next(self.next) };
  950. // SAFETY: By the same reasoning above, it is safe to dereference the node.
  951. Some(unsafe { (addr_of_mut!((*cur).key), addr_of_mut!((*cur).value)) })
  952. }
  953. }
  954. /// A memory reservation for a red-black tree node.
  955. ///
  956. ///
  957. /// It contains the memory needed to hold a node that can be inserted into a red-black tree. One
  958. /// can be obtained by directly allocating it ([`RBTreeNodeReservation::new`]).
  959. pub struct RBTreeNodeReservation<K, V> {
  960. node: Box<MaybeUninit<Node<K, V>>>,
  961. }
  962. impl<K, V> RBTreeNodeReservation<K, V> {
  963. /// Allocates memory for a node to be eventually initialised and inserted into the tree via a
  964. /// call to [`RBTree::insert`].
  965. pub fn new(flags: Flags) -> Result<RBTreeNodeReservation<K, V>> {
  966. Ok(RBTreeNodeReservation {
  967. node: <Box<_> as BoxExt<_>>::new_uninit(flags)?,
  968. })
  969. }
  970. }
  971. // SAFETY: This doesn't actually contain K or V, and is just a memory allocation. Those can always
  972. // be moved across threads.
  973. unsafe impl<K, V> Send for RBTreeNodeReservation<K, V> {}
  974. // SAFETY: This doesn't actually contain K or V, and is just a memory allocation.
  975. unsafe impl<K, V> Sync for RBTreeNodeReservation<K, V> {}
  976. impl<K, V> RBTreeNodeReservation<K, V> {
  977. /// Initialises a node reservation.
  978. ///
  979. /// It then becomes an [`RBTreeNode`] that can be inserted into a tree.
  980. pub fn into_node(mut self, key: K, value: V) -> RBTreeNode<K, V> {
  981. self.node.write(Node {
  982. key,
  983. value,
  984. links: bindings::rb_node::default(),
  985. });
  986. // SAFETY: We just wrote to it.
  987. let node = unsafe { self.node.assume_init() };
  988. RBTreeNode { node }
  989. }
  990. }
  991. /// A red-black tree node.
  992. ///
  993. /// The node is fully initialised (with key and value) and can be inserted into a tree without any
  994. /// extra allocations or failure paths.
  995. pub struct RBTreeNode<K, V> {
  996. node: Box<Node<K, V>>,
  997. }
  998. impl<K, V> RBTreeNode<K, V> {
  999. /// Allocates and initialises a node that can be inserted into the tree via
  1000. /// [`RBTree::insert`].
  1001. pub fn new(key: K, value: V, flags: Flags) -> Result<RBTreeNode<K, V>> {
  1002. Ok(RBTreeNodeReservation::new(flags)?.into_node(key, value))
  1003. }
  1004. /// Get the key and value from inside the node.
  1005. pub fn to_key_value(self) -> (K, V) {
  1006. (self.node.key, self.node.value)
  1007. }
  1008. }
  1009. // SAFETY: If K and V can be sent across threads, then it's also okay to send [`RBTreeNode`] across
  1010. // threads.
  1011. unsafe impl<K: Send, V: Send> Send for RBTreeNode<K, V> {}
  1012. // SAFETY: If K and V can be accessed without synchronization, then it's also okay to access
  1013. // [`RBTreeNode`] without synchronization.
  1014. unsafe impl<K: Sync, V: Sync> Sync for RBTreeNode<K, V> {}
  1015. impl<K, V> RBTreeNode<K, V> {
  1016. /// Drop the key and value, but keep the allocation.
  1017. ///
  1018. /// It then becomes a reservation that can be re-initialised into a different node (i.e., with
  1019. /// a different key and/or value).
  1020. ///
  1021. /// The existing key and value are dropped in-place as part of this operation, that is, memory
  1022. /// may be freed (but only for the key/value; memory for the node itself is kept for reuse).
  1023. pub fn into_reservation(self) -> RBTreeNodeReservation<K, V> {
  1024. RBTreeNodeReservation {
  1025. node: Box::drop_contents(self.node),
  1026. }
  1027. }
  1028. }
  1029. /// A view into a single entry in a map, which may either be vacant or occupied.
  1030. ///
  1031. /// This enum is constructed from the [`RBTree::entry`].
  1032. ///
  1033. /// [`entry`]: fn@RBTree::entry
  1034. pub enum Entry<'a, K, V> {
  1035. /// This [`RBTree`] does not have a node with this key.
  1036. Vacant(VacantEntry<'a, K, V>),
  1037. /// This [`RBTree`] already has a node with this key.
  1038. Occupied(OccupiedEntry<'a, K, V>),
  1039. }
  1040. /// Like [`Entry`], except that it doesn't have ownership of the key.
  1041. enum RawEntry<'a, K, V> {
  1042. Vacant(RawVacantEntry<'a, K, V>),
  1043. Occupied(OccupiedEntry<'a, K, V>),
  1044. }
  1045. /// A view into a vacant entry in a [`RBTree`]. It is part of the [`Entry`] enum.
  1046. pub struct VacantEntry<'a, K, V> {
  1047. key: K,
  1048. raw: RawVacantEntry<'a, K, V>,
  1049. }
  1050. /// Like [`VacantEntry`], but doesn't hold on to the key.
  1051. ///
  1052. /// # Invariants
  1053. /// - `parent` may be null if the new node becomes the root.
  1054. /// - `child_field_of_parent` is a valid pointer to the left-child or right-child of `parent`. If `parent` is
  1055. /// null, it is a pointer to the root of the [`RBTree`].
  1056. struct RawVacantEntry<'a, K, V> {
  1057. rbtree: *mut RBTree<K, V>,
  1058. /// The node that will become the parent of the new node if we insert one.
  1059. parent: *mut bindings::rb_node,
  1060. /// This points to the left-child or right-child field of `parent`, or `root` if `parent` is
  1061. /// null.
  1062. child_field_of_parent: *mut *mut bindings::rb_node,
  1063. _phantom: PhantomData<&'a mut RBTree<K, V>>,
  1064. }
  1065. impl<'a, K, V> RawVacantEntry<'a, K, V> {
  1066. /// Inserts the given node into the [`RBTree`] at this entry.
  1067. ///
  1068. /// The `node` must have a key such that inserting it here does not break the ordering of this
  1069. /// [`RBTree`].
  1070. fn insert(self, node: RBTreeNode<K, V>) -> &'a mut V {
  1071. let node = Box::into_raw(node.node);
  1072. // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
  1073. // the node is removed or replaced.
  1074. let node_links = unsafe { addr_of_mut!((*node).links) };
  1075. // INVARIANT: We are linking in a new node, which is valid. It remains valid because we
  1076. // "forgot" it with `Box::into_raw`.
  1077. // SAFETY: The type invariants of `RawVacantEntry` are exactly the safety requirements of `rb_link_node`.
  1078. unsafe { bindings::rb_link_node(node_links, self.parent, self.child_field_of_parent) };
  1079. // SAFETY: All pointers are valid. `node` has just been inserted into the tree.
  1080. unsafe { bindings::rb_insert_color(node_links, addr_of_mut!((*self.rbtree).root)) };
  1081. // SAFETY: The node is valid until we remove it from the tree.
  1082. unsafe { &mut (*node).value }
  1083. }
  1084. }
  1085. impl<'a, K, V> VacantEntry<'a, K, V> {
  1086. /// Inserts the given node into the [`RBTree`] at this entry.
  1087. pub fn insert(self, value: V, reservation: RBTreeNodeReservation<K, V>) -> &'a mut V {
  1088. self.raw.insert(reservation.into_node(self.key, value))
  1089. }
  1090. }
  1091. /// A view into an occupied entry in a [`RBTree`]. It is part of the [`Entry`] enum.
  1092. ///
  1093. /// # Invariants
  1094. /// - `node_links` is a valid, non-null pointer to a tree node in `self.rbtree`
  1095. pub struct OccupiedEntry<'a, K, V> {
  1096. rbtree: &'a mut RBTree<K, V>,
  1097. /// The node that this entry corresponds to.
  1098. node_links: *mut bindings::rb_node,
  1099. }
  1100. impl<'a, K, V> OccupiedEntry<'a, K, V> {
  1101. /// Gets a reference to the value in the entry.
  1102. pub fn get(&self) -> &V {
  1103. // SAFETY:
  1104. // - `self.node_links` is a valid pointer to a node in the tree.
  1105. // - We have shared access to the underlying tree, and can thus give out a shared reference.
  1106. unsafe { &(*container_of!(self.node_links, Node<K, V>, links)).value }
  1107. }
  1108. /// Gets a mutable reference to the value in the entry.
  1109. pub fn get_mut(&mut self) -> &mut V {
  1110. // SAFETY:
  1111. // - `self.node_links` is a valid pointer to a node in the tree.
  1112. // - We have exclusive access to the underlying tree, and can thus give out a mutable reference.
  1113. unsafe { &mut (*(container_of!(self.node_links, Node<K, V>, links).cast_mut())).value }
  1114. }
  1115. /// Converts the entry into a mutable reference to its value.
  1116. ///
  1117. /// If you need multiple references to the `OccupiedEntry`, see [`self#get_mut`].
  1118. pub fn into_mut(self) -> &'a mut V {
  1119. // SAFETY:
  1120. // - `self.node_links` is a valid pointer to a node in the tree.
  1121. // - This consumes the `&'a mut RBTree<K, V>`, therefore it can give out a mutable reference that lives for `'a`.
  1122. unsafe { &mut (*(container_of!(self.node_links, Node<K, V>, links).cast_mut())).value }
  1123. }
  1124. /// Remove this entry from the [`RBTree`].
  1125. pub fn remove_node(self) -> RBTreeNode<K, V> {
  1126. // SAFETY: The node is a node in the tree, so it is valid.
  1127. unsafe { bindings::rb_erase(self.node_links, &mut self.rbtree.root) };
  1128. // INVARIANT: The node is being returned and the caller may free it, however, it was
  1129. // removed from the tree. So the invariants still hold.
  1130. RBTreeNode {
  1131. // SAFETY: The node was a node in the tree, but we removed it, so we can convert it
  1132. // back into a box.
  1133. node: unsafe {
  1134. Box::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut())
  1135. },
  1136. }
  1137. }
  1138. /// Takes the value of the entry out of the map, and returns it.
  1139. pub fn remove(self) -> V {
  1140. self.remove_node().node.value
  1141. }
  1142. /// Swap the current node for the provided node.
  1143. ///
  1144. /// The key of both nodes must be equal.
  1145. fn replace(self, node: RBTreeNode<K, V>) -> RBTreeNode<K, V> {
  1146. let node = Box::into_raw(node.node);
  1147. // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
  1148. // the node is removed or replaced.
  1149. let new_node_links = unsafe { addr_of_mut!((*node).links) };
  1150. // SAFETY: This updates the pointers so that `new_node_links` is in the tree where
  1151. // `self.node_links` used to be.
  1152. unsafe {
  1153. bindings::rb_replace_node(self.node_links, new_node_links, &mut self.rbtree.root)
  1154. };
  1155. // SAFETY:
  1156. // - `self.node_ptr` produces a valid pointer to a node in the tree.
  1157. // - Now that we removed this entry from the tree, we can convert the node to a box.
  1158. let old_node =
  1159. unsafe { Box::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut()) };
  1160. RBTreeNode { node: old_node }
  1161. }
  1162. }
  1163. struct Node<K, V> {
  1164. links: bindings::rb_node,
  1165. key: K,
  1166. value: V,
  1167. }