Skip to content

Commit c6c76e1

Browse files
Darksonnfbq
authored andcommitted
rust: rbtree: add RBTree::entry
This mirrors the entry API [1] from the Rust standard library on `RBTree`. This API can be used to access the entry at a specific key and make modifications depending on whether the key is vacant or occupied. This API is useful because it can often be used to avoid traversing the tree multiple times. This is used by binder to look up and conditionally access or insert a value, depending on whether it is there or not [2]. Link: https://doc.rust-lang.org/stable/std/collections/btree_map/enum.Entry.html [1] Link: https://android-review.googlesource.com/c/kernel/common/+/2849906 [2] Signed-off-by: Alice Ryhl <aliceryhl@google.com> Tested-by: Alice Ryhl <aliceryhl@google.com> Signed-off-by: Matt Gilbride <mattgilbride@google.com> Link: https://lore.kernel.org/r/20240727-b4-rbtree-v8-6-951600ada434@google.com
1 parent b1bcae7 commit c6c76e1

1 file changed

Lines changed: 227 additions & 75 deletions

File tree

rust/kernel/rbtree.rs

Lines changed: 227 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -295,12 +295,19 @@ where
295295
/// key/value pair). Returns [`None`] if a node with the same key didn't already exist.
296296
///
297297
/// This function always succeeds.
298-
pub fn insert(&mut self, RBTreeNode { node }: RBTreeNode<K, V>) -> Option<RBTreeNode<K, V>> {
299-
let node = Box::into_raw(node);
300-
// SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
301-
// the node is removed or replaced.
302-
let node_links = unsafe { addr_of_mut!((*node).links) };
298+
pub fn insert(&mut self, node: RBTreeNode<K, V>) -> Option<RBTreeNode<K, V>> {
299+
match self.raw_entry(&node.node.key) {
300+
RawEntry::Occupied(entry) => Some(entry.replace(node)),
301+
RawEntry::Vacant(entry) => {
302+
entry.insert(node);
303+
None
304+
}
305+
}
306+
}
303307

308+
fn raw_entry(&mut self, key: &K) -> RawEntry<'_, K, V> {
309+
let raw_self: *mut RBTree<K, V> = self;
310+
// The returned `RawEntry` is used to call either `rb_link_node` or `rb_replace_node`.
304311
// The parameters of `rb_link_node` are as follows:
305312
// - `node`: A pointer to an uninitialized node being inserted.
306313
// - `parent`: A pointer to an existing node in the tree. One of its child pointers must be
@@ -319,62 +326,56 @@ where
319326
// in the subtree of `parent` that `child_field_of_parent` points at. Once
320327
// we find an empty subtree, we can insert the new node using `rb_link_node`.
321328
let mut parent = core::ptr::null_mut();
322-
let mut child_field_of_parent: &mut *mut bindings::rb_node = &mut self.root.rb_node;
323-
while !child_field_of_parent.is_null() {
324-
parent = *child_field_of_parent;
329+
let mut child_field_of_parent: &mut *mut bindings::rb_node =
330+
// SAFETY: `raw_self` is a valid pointer to the `RBTree` (created from `self` above).
331+
unsafe { &mut (*raw_self).root.rb_node };
332+
while !(*child_field_of_parent).is_null() {
333+
let curr = *child_field_of_parent;
334+
// SAFETY: All links fields we create are in a `Node<K, V>`.
335+
let node = unsafe { container_of!(curr, Node<K, V>, links) };
325336

326-
// We need to determine whether `node` should be the left or right child of `parent`,
327-
// so we will compare with the `key` field of `parent` a.k.a. `this` below.
328-
//
329-
// SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
330-
// point to the links field of `Node<K, V>` objects.
331-
let this = unsafe { container_of!(parent, Node<K, V>, links) };
332-
333-
// SAFETY: `this` is a non-null node so it is valid by the type invariants. `node` is
334-
// valid until the node is removed.
335-
match unsafe { (*node).key.cmp(&(*this).key) } {
336-
// We would like `node` to be the left child of `parent`. Move to this child to check
337-
// whether we can use it, or continue searching, at the next iteration.
338-
//
339-
// SAFETY: `parent` is a non-null node so it is valid by the type invariants.
340-
Ordering::Less => child_field_of_parent = unsafe { &mut (*parent).rb_left },
341-
// We would like `node` to be the right child of `parent`. Move to this child to check
342-
// whether we can use it, or continue searching, at the next iteration.
343-
//
344-
// SAFETY: `parent` is a non-null node so it is valid by the type invariants.
345-
Ordering::Greater => child_field_of_parent = unsafe { &mut (*parent).rb_right },
337+
// SAFETY: `node` is a non-null node so it is valid by the type invariants.
338+
match key.cmp(unsafe { &(*node).key }) {
339+
// SAFETY: `curr` is a non-null node so it is valid by the type invariants.
340+
Ordering::Less => child_field_of_parent = unsafe { &mut (*curr).rb_left },
341+
// SAFETY: `curr` is a non-null node so it is valid by the type invariants.
342+
Ordering::Greater => child_field_of_parent = unsafe { &mut (*curr).rb_right },
346343
Ordering::Equal => {
347-
// There is an existing node in the tree with this key, and that node is
348-
// parent. Thus, we are replacing parent with a new node.
349-
//
350-
// INVARIANT: We are replacing an existing node with a new one, which is valid.
351-
// It remains valid because we "forgot" it with `Box::into_raw`.
352-
// SAFETY: All pointers are non-null and valid.
353-
unsafe { bindings::rb_replace_node(parent, node_links, &mut self.root) };
354-
355-
// INVARIANT: The node is being returned and the caller may free it, however,
356-
// it was removed from the tree. So the invariants still hold.
357-
return Some(RBTreeNode {
358-
// SAFETY: `this` was a node in the tree, so it is valid.
359-
node: unsafe { Box::from_raw(this.cast_mut()) },
360-
});
344+
return RawEntry::Occupied(OccupiedEntry {
345+
rbtree: self,
346+
node_links: curr,
347+
})
361348
}
362349
}
350+
parent = curr;
363351
}
364352

365-
// INVARIANT: We are linking in a new node, which is valid. It remains valid because we
366-
// "forgot" it with `Box::into_raw`.
367-
// SAFETY: All pointers are non-null and valid (`*child_field_of_parent` is null, but `child_field_of_parent` is a
368-
// mutable reference).
369-
unsafe { bindings::rb_link_node(node_links, parent, child_field_of_parent) };
353+
RawEntry::Vacant(RawVacantEntry {
354+
rbtree: raw_self,
355+
parent,
356+
child_field_of_parent,
357+
_phantom: PhantomData,
358+
})
359+
}
370360

371-
// SAFETY: All pointers are valid. `node` has just been inserted into the tree.
372-
unsafe { bindings::rb_insert_color(node_links, &mut self.root) };
373-
None
361+
/// Gets the given key's corresponding entry in the map for in-place manipulation.
362+
pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
363+
match self.raw_entry(&key) {
364+
RawEntry::Occupied(entry) => Entry::Occupied(entry),
365+
RawEntry::Vacant(entry) => Entry::Vacant(VacantEntry { raw: entry, key }),
366+
}
367+
}
368+
369+
/// Used for accessing the given node, if it exists.
370+
pub fn find_mut(&mut self, key: &K) -> Option<OccupiedEntry<'_, K, V>> {
371+
match self.raw_entry(key) {
372+
RawEntry::Occupied(entry) => Some(entry),
373+
RawEntry::Vacant(_entry) => None,
374+
}
374375
}
375376

376-
/// Returns a node with the given key, if one exists.
377-
fn find(&self, key: &K) -> Option<NonNull<Node<K, V>>> {
377+
/// Returns a reference to the value corresponding to the key.
378+
pub fn get(&self, key: &K) -> Option<&V> {
378379
let mut node = self.root.rb_node;
379380
while !node.is_null() {
380381
// SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
@@ -386,47 +387,30 @@ where
386387
Ordering::Less => unsafe { (*node).rb_left },
387388
// SAFETY: `node` is a non-null node so it is valid by the type invariants.
388389
Ordering::Greater => unsafe { (*node).rb_right },
389-
Ordering::Equal => return NonNull::new(this.cast_mut()),
390+
// SAFETY: `node` is a non-null node so it is valid by the type invariants.
391+
Ordering::Equal => return Some(unsafe { &(*this).value }),
390392
}
391393
}
392394
None
393395
}
394396

395-
/// Returns a reference to the value corresponding to the key.
396-
pub fn get(&self, key: &K) -> Option<&V> {
397-
// SAFETY: The `find` return value is a node in the tree, so it is valid.
398-
self.find(key).map(|node| unsafe { &node.as_ref().value })
399-
}
400-
401397
/// Returns a mutable reference to the value corresponding to the key.
402398
pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
403-
// SAFETY: The `find` return value is a node in the tree, so it is valid.
404-
self.find(key)
405-
.map(|mut node| unsafe { &mut node.as_mut().value })
399+
self.find_mut(key).map(|node| node.into_mut())
406400
}
407401

408402
/// Removes the node with the given key from the tree.
409403
///
410404
/// It returns the node that was removed if one exists, or [`None`] otherwise.
411-
fn remove_node(&mut self, key: &K) -> Option<RBTreeNode<K, V>> {
412-
let mut node = self.find(key)?;
413-
414-
// SAFETY: The `find` return value is a node in the tree, so it is valid.
415-
unsafe { bindings::rb_erase(&mut node.as_mut().links, &mut self.root) };
416-
417-
// INVARIANT: The node is being returned and the caller may free it, however, it was
418-
// removed from the tree. So the invariants still hold.
419-
Some(RBTreeNode {
420-
// SAFETY: The `find` return value was a node in the tree, so it is valid.
421-
node: unsafe { Box::from_raw(node.as_ptr()) },
422-
})
405+
pub fn remove_node(&mut self, key: &K) -> Option<RBTreeNode<K, V>> {
406+
self.find_mut(key).map(OccupiedEntry::remove_node)
423407
}
424408

425409
/// Removes the node with the given key from the tree.
426410
///
427411
/// It returns the value that was removed if one exists, or [`None`] otherwise.
428412
pub fn remove(&mut self, key: &K) -> Option<V> {
429-
self.remove_node(key).map(|node| node.node.value)
413+
self.find_mut(key).map(OccupiedEntry::remove)
430414
}
431415

432416
/// Returns a cursor over the tree nodes based on the given key.
@@ -1129,6 +1113,174 @@ unsafe impl<K: Send, V: Send> Send for RBTreeNode<K, V> {}
11291113
// [`RBTreeNode`] without synchronization.
11301114
unsafe impl<K: Sync, V: Sync> Sync for RBTreeNode<K, V> {}
11311115

1116+
impl<K, V> RBTreeNode<K, V> {
1117+
/// Drop the key and value, but keep the allocation.
1118+
///
1119+
/// It then becomes a reservation that can be re-initialised into a different node (i.e., with
1120+
/// a different key and/or value).
1121+
///
1122+
/// The existing key and value are dropped in-place as part of this operation, that is, memory
1123+
/// may be freed (but only for the key/value; memory for the node itself is kept for reuse).
1124+
pub fn into_reservation(self) -> RBTreeNodeReservation<K, V> {
1125+
RBTreeNodeReservation {
1126+
node: Box::drop_contents(self.node),
1127+
}
1128+
}
1129+
}
1130+
1131+
/// A view into a single entry in a map, which may either be vacant or occupied.
1132+
///
1133+
/// This enum is constructed from the [`RBTree::entry`].
1134+
///
1135+
/// [`entry`]: fn@RBTree::entry
1136+
pub enum Entry<'a, K, V> {
1137+
/// This [`RBTree`] does not have a node with this key.
1138+
Vacant(VacantEntry<'a, K, V>),
1139+
/// This [`RBTree`] already has a node with this key.
1140+
Occupied(OccupiedEntry<'a, K, V>),
1141+
}
1142+
1143+
/// Like [`Entry`], except that it doesn't have ownership of the key.
1144+
enum RawEntry<'a, K, V> {
1145+
Vacant(RawVacantEntry<'a, K, V>),
1146+
Occupied(OccupiedEntry<'a, K, V>),
1147+
}
1148+
1149+
/// A view into a vacant entry in a [`RBTree`]. It is part of the [`Entry`] enum.
1150+
pub struct VacantEntry<'a, K, V> {
1151+
key: K,
1152+
raw: RawVacantEntry<'a, K, V>,
1153+
}
1154+
1155+
/// Like [`VacantEntry`], but doesn't hold on to the key.a
1156+
///
1157+
/// # Invariants
1158+
/// - `parent` may be null if the new node becomes the root.
1159+
/// - `child_field_of_parent` is a valid pointer to the left-child or right-child of `parent`. If `parent` is
1160+
/// null, it is a pointer to the root of the [`RBTree`].
1161+
struct RawVacantEntry<'a, K, V> {
1162+
rbtree: *mut RBTree<K, V>,
1163+
/// The node that will become the parent of the new node if we insert one.
1164+
parent: *mut bindings::rb_node,
1165+
/// This points to the left-child or right-child field of `parent`, or `root` if `parent` is
1166+
/// null.
1167+
child_field_of_parent: *mut *mut bindings::rb_node,
1168+
_phantom: PhantomData<&'a mut RBTree<K, V>>,
1169+
}
1170+
1171+
impl<'a, K, V> RawVacantEntry<'a, K, V> {
1172+
/// Inserts the given node into the [`RBTree`] at this entry.
1173+
///
1174+
/// The `node` must have a key such that inserting it here does not break the ordering of this
1175+
/// [`RBTree`].
1176+
fn insert(self, node: RBTreeNode<K, V>) -> &'a mut V {
1177+
let node = Box::into_raw(node.node);
1178+
1179+
// SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
1180+
// the node is removed or replaced.
1181+
let node_links = unsafe { addr_of_mut!((*node).links) };
1182+
1183+
// INVARIANT: We are linking in a new node, which is valid. It remains valid because we
1184+
// "forgot" it with `Box::into_raw`.
1185+
// SAFETY: The type invariants of `RawVacantEntry` are exactly the safety requirements of `rb_link_node`.
1186+
unsafe { bindings::rb_link_node(node_links, self.parent, self.child_field_of_parent) };
1187+
1188+
// SAFETY: All pointers are valid. `node` has just been inserted into the tree.
1189+
unsafe { bindings::rb_insert_color(node_links, addr_of_mut!((*self.rbtree).root)) };
1190+
1191+
// SAFETY: The node is valid until we remove it from the tree.
1192+
unsafe { &mut (*node).value }
1193+
}
1194+
}
1195+
1196+
impl<'a, K, V> VacantEntry<'a, K, V> {
1197+
/// Inserts the given node into the [`RBTree`] at this entry.
1198+
pub fn insert(self, value: V, reservation: RBTreeNodeReservation<K, V>) -> &'a mut V {
1199+
self.raw.insert(reservation.into_node(self.key, value))
1200+
}
1201+
}
1202+
1203+
/// A view into an occupied entry in a [`RBTree`]. It is part of the [`Entry`] enum.
1204+
///
1205+
/// # Invariants
1206+
/// - `node_links` is a valid, non-null pointer to a tree node in `self.rbtree`
1207+
pub struct OccupiedEntry<'a, K, V> {
1208+
rbtree: &'a mut RBTree<K, V>,
1209+
/// The node that this entry corresponds to.
1210+
node_links: *mut bindings::rb_node,
1211+
}
1212+
1213+
impl<'a, K, V> OccupiedEntry<'a, K, V> {
1214+
fn node_ptr(&self) -> *mut Node<K, V> {
1215+
// SAFETY: By the type invariant of `Self`, all `node_links` pointers stored in `self`
1216+
// point to the links field of `Node<K, V>` objects.
1217+
unsafe { container_of!(self.node_links, Node<K, V>, links) }.cast_mut()
1218+
}
1219+
1220+
/// Gets a reference to the value in the entry.
1221+
pub fn get(&self) -> &V {
1222+
// SAFETY: `self.node_ptr` produces a valid pointer to a node in the tree.
1223+
unsafe { &(*self.node_ptr()).value }
1224+
}
1225+
1226+
/// Gets a mutable reference to the value in the entry.
1227+
pub fn get_mut(&mut self) -> &mut V {
1228+
// SAFETY: `self.node_ptr` produces a valid pointer to a node in the tree.
1229+
unsafe { &mut (*self.node_ptr()).value }
1230+
}
1231+
1232+
/// Converts the entry into a mutable reference to its value.
1233+
///
1234+
/// If you need multiple references to the `OccupiedEntry`, see [`self#get_mut`].
1235+
pub fn into_mut(self) -> &'a mut V {
1236+
// SAFETY: `self.node_ptr` produces a valid pointer to a node in the tree.
1237+
unsafe { &mut (*self.node_ptr()).value }
1238+
}
1239+
1240+
/// Remove this entry from the [`RBTree`].
1241+
pub fn remove_node(self) -> RBTreeNode<K, V> {
1242+
// SAFETY: The node is a node in the tree, so it is valid.
1243+
unsafe { bindings::rb_erase(self.node_links, &mut self.rbtree.root) };
1244+
1245+
// INVARIANT: The node is being returned and the caller may free it, however, it was
1246+
// removed from the tree. So the invariants still hold.
1247+
RBTreeNode {
1248+
// SAFETY: The node was a node in the tree, but we removed it, so we can convert it
1249+
// back into a box.
1250+
node: unsafe { Box::from_raw(self.node_ptr()) },
1251+
}
1252+
}
1253+
1254+
/// Takes the value of the entry out of the map, and returns it.
1255+
pub fn remove(self) -> V {
1256+
self.remove_node().node.value
1257+
}
1258+
1259+
/// Swap the current node for the provided node.
1260+
///
1261+
/// The key of both nodes must be equal.
1262+
fn replace(self, node: RBTreeNode<K, V>) -> RBTreeNode<K, V> {
1263+
let node = Box::into_raw(node.node);
1264+
1265+
// SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
1266+
// the node is removed or replaced.
1267+
let new_node_links = unsafe { addr_of_mut!((*node).links) };
1268+
1269+
// SAFETY: This updates the pointers so that `new_node_links` is in the tree where
1270+
// `self.node_links` used to be.
1271+
unsafe {
1272+
bindings::rb_replace_node(self.node_links, new_node_links, &mut self.rbtree.root)
1273+
};
1274+
1275+
// SAFETY:
1276+
// - `self.node_ptr` produces a valid pointer to a node in the tree.
1277+
// - Now that we removed this entry from the tree, we can convert the node to a box.
1278+
let old_node = unsafe { Box::from_raw(self.node_ptr()) };
1279+
1280+
RBTreeNode { node: old_node }
1281+
}
1282+
}
1283+
11321284
struct Node<K, V> {
11331285
links: bindings::rb_node,
11341286
key: K,

0 commit comments

Comments
 (0)