rbtree.rs 48 KB

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