Skip to content

Commit 4b34441

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 <[email protected]> Tested-by: Alice Ryhl <[email protected]> Reviewed-by: Boqun Feng <[email protected]> Signed-off-by: Matt Gilbride <[email protected]> Link: https://lore.kernel.org/r/[email protected]
1 parent 9b3fca7 commit 4b34441

File tree

1 file changed

+235
-75
lines changed

1 file changed

+235
-75
lines changed

Diff for: rust/kernel/rbtree.rs

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

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

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

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

373-
// SAFETY: All pointers are valid. `node` has just been inserted into the tree.
374-
unsafe { bindings::rb_insert_color(node_links, &mut self.root) };
375-
None
363+
/// Gets the given key's corresponding entry in the map for in-place manipulation.
364+
pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
365+
match self.raw_entry(&key) {
366+
RawEntry::Occupied(entry) => Entry::Occupied(entry),
367+
RawEntry::Vacant(entry) => Entry::Vacant(VacantEntry { raw: entry, key }),
368+
}
376369
}
377370

378-
/// Returns a node with the given key, if one exists.
379-
fn find(&self, key: &K) -> Option<NonNull<Node<K, V>>> {
371+
/// Used for accessing the given node, if it exists.
372+
pub fn find_mut(&mut self, key: &K) -> Option<OccupiedEntry<'_, K, V>> {
373+
match self.raw_entry(key) {
374+
RawEntry::Occupied(entry) => Some(entry),
375+
RawEntry::Vacant(_entry) => None,
376+
}
377+
}
378+
379+
/// Returns a reference to the value corresponding to the key.
380+
pub fn get(&self, key: &K) -> Option<&V> {
380381
let mut node = self.root.rb_node;
381382
while !node.is_null() {
382383
// SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
@@ -388,47 +389,30 @@ where
388389
Ordering::Less => unsafe { (*node).rb_left },
389390
// SAFETY: `node` is a non-null node so it is valid by the type invariants.
390391
Ordering::Greater => unsafe { (*node).rb_right },
391-
Ordering::Equal => return NonNull::new(this.cast_mut()),
392+
// SAFETY: `node` is a non-null node so it is valid by the type invariants.
393+
Ordering::Equal => return Some(unsafe { &(*this).value }),
392394
}
393395
}
394396
None
395397
}
396398

397-
/// Returns a reference to the value corresponding to the key.
398-
pub fn get(&self, key: &K) -> Option<&V> {
399-
// SAFETY: The `find` return value is a node in the tree, so it is valid.
400-
self.find(key).map(|node| unsafe { &node.as_ref().value })
401-
}
402-
403399
/// Returns a mutable reference to the value corresponding to the key.
404400
pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
405-
// SAFETY: The `find` return value is a node in the tree, so it is valid.
406-
self.find(key)
407-
.map(|mut node| unsafe { &mut node.as_mut().value })
401+
self.find_mut(key).map(|node| node.into_mut())
408402
}
409403

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

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

434418
/// Returns a cursor over the tree nodes based on the given key.
@@ -1136,6 +1120,182 @@ unsafe impl<K: Send, V: Send> Send for RBTreeNode<K, V> {}
11361120
// [`RBTreeNode`] without synchronization.
11371121
unsafe impl<K: Sync, V: Sync> Sync for RBTreeNode<K, V> {}
11381122

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

0 commit comments

Comments
 (0)