@@ -293,12 +293,19 @@ where
293
293
/// key/value pair). Returns [`None`] if a node with the same key didn't already exist.
294
294
///
295
295
/// This function always succeeds.
296
- pub fn insert(&mut self, RBTreeNode { node }: RBTreeNode<K, V>) -> Option<RBTreeNode<K, V>> {
297
- let node = Box::into_raw(node);
298
- // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
299
- // the node is removed or replaced.
300
- let node_links = unsafe { addr_of_mut!((*node).links) };
296
+ pub fn insert(&mut self, node: RBTreeNode<K, V>) -> Option<RBTreeNode<K, V>> {
297
+ match self.raw_entry(&node.node.key) {
298
+ RawEntry::Occupied(entry) => Some(entry.replace(node)),
299
+ RawEntry::Vacant(entry) => {
300
+ entry.insert(node);
301
+ None
302
+ }
303
+ }
304
+ }
301
305
306
+ fn raw_entry(&mut self, key: &K) -> RawEntry<'_, K, V> {
307
+ let raw_self: *mut RBTree<K, V> = self;
308
+ // The returned `RawEntry` is used to call either `rb_link_node` or `rb_replace_node`.
302
309
// The parameters of `bindings::rb_link_node` are as follows:
303
310
// - `node`: A pointer to an uninitialized node being inserted.
304
311
// - `parent`: A pointer to an existing node in the tree. One of its child pointers must be
@@ -317,62 +324,56 @@ where
317
324
// in the subtree of `parent` that `child_field_of_parent` points at. Once
318
325
// we find an empty subtree, we can insert the new node using `rb_link_node`.
319
326
let mut parent = core::ptr::null_mut();
320
- let mut child_field_of_parent: &mut *mut bindings::rb_node = &mut self.root.rb_node;
321
- while !child_field_of_parent.is_null() {
322
- parent = *child_field_of_parent;
327
+ let mut child_field_of_parent: &mut *mut bindings::rb_node =
328
+ // SAFETY: `raw_self` is a valid pointer to the `RBTree` (created from `self` above).
329
+ unsafe { &mut (*raw_self).root.rb_node };
330
+ while !(*child_field_of_parent).is_null() {
331
+ let curr = *child_field_of_parent;
332
+ // SAFETY: All links fields we create are in a `Node<K, V>`.
333
+ let node = unsafe { container_of!(curr, Node<K, V>, links) };
323
334
324
- // We need to determine whether `node` should be the left or right child of `parent`,
325
- // so we will compare with the `key` field of `parent` a.k.a. `this` below.
326
- //
327
- // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
328
- // point to the links field of `Node<K, V>` objects.
329
- let this = unsafe { container_of!(parent, Node<K, V>, links) };
330
-
331
- // SAFETY: `this` is a non-null node so it is valid by the type invariants. `node` is
332
- // valid until the node is removed.
333
- match unsafe { (*node).key.cmp(&(*this).key) } {
334
- // We would like `node` to be the left child of `parent`. Move to this child to check
335
- // whether we can use it, or continue searching, at the next iteration.
336
- //
337
- // SAFETY: `parent` is a non-null node so it is valid by the type invariants.
338
- Ordering::Less => child_field_of_parent = unsafe { &mut (*parent).rb_left },
339
- // We would like `node` to be the right child of `parent`. Move to this child to check
340
- // whether we can use it, or continue searching, at the next iteration.
341
- //
342
- // SAFETY: `parent` is a non-null node so it is valid by the type invariants.
343
- Ordering::Greater => child_field_of_parent = unsafe { &mut (*parent).rb_right },
335
+ // SAFETY: `node` is a non-null node so it is valid by the type invariants.
336
+ match key.cmp(unsafe { &(*node).key }) {
337
+ // SAFETY: `curr` is a non-null node so it is valid by the type invariants.
338
+ Ordering::Less => child_field_of_parent = unsafe { &mut (*curr).rb_left },
339
+ // SAFETY: `curr` is a non-null node so it is valid by the type invariants.
340
+ Ordering::Greater => child_field_of_parent = unsafe { &mut (*curr).rb_right },
344
341
Ordering::Equal => {
345
- // There is an existing node in the tree with this key, and that node is
346
- // `parent`. Thus, we are replacing parent with a new node.
347
- //
348
- // INVARIANT: We are replacing an existing node with a new one, which is valid.
349
- // It remains valid because we "forgot" it with `Box::into_raw`.
350
- // SAFETY: All pointers are non-null and valid.
351
- unsafe { bindings::rb_replace_node(parent, node_links, &mut self.root) };
352
-
353
- // INVARIANT: The node is being returned and the caller may free it, however,
354
- // it was removed from the tree. So the invariants still hold.
355
- return Some(RBTreeNode {
356
- // SAFETY: `this` was a node in the tree, so it is valid.
357
- node: unsafe { Box::from_raw(this.cast_mut()) },
358
- });
342
+ return RawEntry::Occupied(OccupiedEntry {
343
+ rbtree: self,
344
+ node_links: curr,
345
+ })
359
346
}
360
347
}
348
+ parent = curr;
361
349
}
362
350
363
- // INVARIANT: We are linking in a new node, which is valid. It remains valid because we
364
- // "forgot" it with `Box::into_raw`.
365
- // SAFETY: All pointers are non-null and valid (`*child_field_of_parent` is null, but `child_field_of_parent` is a
366
- // mutable reference).
367
- unsafe { bindings::rb_link_node(node_links, parent, child_field_of_parent) };
351
+ RawEntry::Vacant(RawVacantEntry {
352
+ rbtree: raw_self,
353
+ parent,
354
+ child_field_of_parent,
355
+ _phantom: PhantomData,
356
+ })
357
+ }
368
358
369
- // SAFETY: All pointers are valid. `node` has just been inserted into the tree.
370
- unsafe { bindings::rb_insert_color(node_links, &mut self.root) };
371
- None
359
+ /// Gets the given key's corresponding entry in the map for in-place manipulation.
360
+ pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
361
+ match self.raw_entry(&key) {
362
+ RawEntry::Occupied(entry) => Entry::Occupied(entry),
363
+ RawEntry::Vacant(entry) => Entry::Vacant(VacantEntry { raw: entry, key }),
364
+ }
365
+ }
366
+
367
+ /// Used for accessing the given node, if it exists.
368
+ pub fn find_mut(&mut self, key: &K) -> Option<OccupiedEntry<'_, K, V>> {
369
+ match self.raw_entry(key) {
370
+ RawEntry::Occupied(entry) => Some(entry),
371
+ RawEntry::Vacant(_entry) => None,
372
+ }
372
373
}
373
374
374
- /// Returns a node with the given key, if one exists .
375
- fn find (&self, key: &K) -> Option<NonNull<Node<K, V>> > {
375
+ /// Returns a reference to the value corresponding to the key .
376
+ pub fn get (&self, key: &K) -> Option<&V > {
376
377
let mut node = self.root.rb_node;
377
378
while !node.is_null() {
378
379
// SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
@@ -384,47 +385,30 @@ where
384
385
Ordering::Less => unsafe { (*node).rb_left },
385
386
// SAFETY: `node` is a non-null node so it is valid by the type invariants.
386
387
Ordering::Greater => unsafe { (*node).rb_right },
387
- Ordering::Equal => return NonNull::new(this.cast_mut()),
388
+ // SAFETY: `node` is a non-null node so it is valid by the type invariants.
389
+ Ordering::Equal => return Some(unsafe { &(*this).value }),
388
390
}
389
391
}
390
392
None
391
393
}
392
394
393
- /// Returns a reference to the value corresponding to the key.
394
- pub fn get(&self, key: &K) -> Option<&V> {
395
- // SAFETY: The `find` return value is a node in the tree, so it is valid.
396
- self.find(key).map(|node| unsafe { &node.as_ref().value })
397
- }
398
-
399
395
/// Returns a mutable reference to the value corresponding to the key.
400
396
pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
401
- // SAFETY: The `find` return value is a node in the tree, so it is valid.
402
- self.find(key)
403
- .map(|mut node| unsafe { &mut node.as_mut().value })
397
+ self.find_mut(key).map(|node| node.into_mut())
404
398
}
405
399
406
400
/// Removes the node with the given key from the tree.
407
401
///
408
402
/// It returns the node that was removed if one exists, or [`None`] otherwise.
409
- fn remove_node(&mut self, key: &K) -> Option<RBTreeNode<K, V>> {
410
- let mut node = self.find(key)?;
411
-
412
- // SAFETY: The `find` return value is a node in the tree, so it is valid.
413
- unsafe { bindings::rb_erase(&mut node.as_mut().links, &mut self.root) };
414
-
415
- // INVARIANT: The node is being returned and the caller may free it, however, it was
416
- // removed from the tree. So the invariants still hold.
417
- Some(RBTreeNode {
418
- // SAFETY: The `find` return value was a node in the tree, so it is valid.
419
- node: unsafe { Box::from_raw(node.as_ptr()) },
420
- })
403
+ pub fn remove_node(&mut self, key: &K) -> Option<RBTreeNode<K, V>> {
404
+ self.find_mut(key).map(OccupiedEntry::remove_node)
421
405
}
422
406
423
407
/// Removes the node with the given key from the tree.
424
408
///
425
409
/// It returns the value that was removed if one exists, or [`None`] otherwise.
426
410
pub fn remove(&mut self, key: &K) -> Option<V> {
427
- self.remove_node (key).map(|node| node.node.value )
411
+ self.find_mut (key).map(OccupiedEntry::remove )
428
412
}
429
413
430
414
/// Returns a cursor over the tree nodes based on the given key.
@@ -1117,6 +1101,177 @@ unsafe impl<K: Send, V: Send> Send for RBTreeNode<K, V> {}
1117
1101
// [`RBTreeNode`] without synchronization.
1118
1102
unsafe impl<K: Sync, V: Sync> Sync for RBTreeNode<K, V> {}
1119
1103
1104
+ impl<K, V> RBTreeNode<K, V> {
1105
+ /// Drop the key and value, but keep the allocation.
1106
+ ///
1107
+ /// It then becomes a reservation that can be re-initialised into a different node (i.e., with
1108
+ /// a different key and/or value).
1109
+ ///
1110
+ /// The existing key and value are dropped in-place as part of this operation, that is, memory
1111
+ /// may be freed (but only for the key/value; memory for the node itself is kept for reuse).
1112
+ pub fn into_reservation(self) -> RBTreeNodeReservation<K, V> {
1113
+ RBTreeNodeReservation {
1114
+ node: Box::drop_contents(self.node),
1115
+ }
1116
+ }
1117
+ }
1118
+
1119
+ /// A view into a single entry in a map, which may either be vacant or occupied.
1120
+ ///
1121
+ /// This enum is constructed from the [`RBTree::entry`].
1122
+ ///
1123
+ /// [`entry`]: fn@RBTree::entry
1124
+ pub enum Entry<'a, K, V> {
1125
+ /// This [`RBTree`] does not have a node with this key.
1126
+ Vacant(VacantEntry<'a, K, V>),
1127
+ /// This [`RBTree`] already has a node with this key.
1128
+ Occupied(OccupiedEntry<'a, K, V>),
1129
+ }
1130
+
1131
+ /// Like [`Entry`], except that it doesn't have ownership of the key.
1132
+ enum RawEntry<'a, K, V> {
1133
+ Vacant(RawVacantEntry<'a, K, V>),
1134
+ Occupied(OccupiedEntry<'a, K, V>),
1135
+ }
1136
+
1137
+ /// A view into a vacant entry in a [`RBTree`]. It is part of the [`Entry`] enum.
1138
+ pub struct VacantEntry<'a, K, V> {
1139
+ key: K,
1140
+ raw: RawVacantEntry<'a, K, V>,
1141
+ }
1142
+
1143
+ /// Like [`VacantEntry`], but doesn't hold on to the key.
1144
+ ///
1145
+ /// # Invariants
1146
+ /// - `parent` may be null if the new node becomes the root.
1147
+ /// - `child_field_of_parent` is a valid pointer to the left-child or right-child of `parent`. If `parent` is
1148
+ /// null, it is a pointer to the root of the [`RBTree`].
1149
+ struct RawVacantEntry<'a, K, V> {
1150
+ rbtree: *mut RBTree<K, V>,
1151
+ /// The node that will become the parent of the new node if we insert one.
1152
+ parent: *mut bindings::rb_node,
1153
+ /// This points to the left-child or right-child field of `parent`, or `root` if `parent` is
1154
+ /// null.
1155
+ child_field_of_parent: *mut *mut bindings::rb_node,
1156
+ _phantom: PhantomData<&'a mut RBTree<K, V>>,
1157
+ }
1158
+
1159
+ impl<'a, K, V> RawVacantEntry<'a, K, V> {
1160
+ /// Inserts the given node into the [`RBTree`] at this entry.
1161
+ ///
1162
+ /// The `node` must have a key such that inserting it here does not break the ordering of this
1163
+ /// [`RBTree`].
1164
+ fn insert(self, node: RBTreeNode<K, V>) -> &'a mut V {
1165
+ let node = Box::into_raw(node.node);
1166
+
1167
+ // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
1168
+ // the node is removed or replaced.
1169
+ let node_links = unsafe { addr_of_mut!((*node).links) };
1170
+
1171
+ // INVARIANT: We are linking in a new node, which is valid. It remains valid because we
1172
+ // "forgot" it with `Box::into_raw`.
1173
+ // SAFETY: The type invariants of `RawVacantEntry` are exactly the safety requirements of `rb_link_node`.
1174
+ unsafe { bindings::rb_link_node(node_links, self.parent, self.child_field_of_parent) };
1175
+
1176
+ // SAFETY: All pointers are valid. `node` has just been inserted into the tree.
1177
+ unsafe { bindings::rb_insert_color(node_links, addr_of_mut!((*self.rbtree).root)) };
1178
+
1179
+ // SAFETY: The node is valid until we remove it from the tree.
1180
+ unsafe { &mut (*node).value }
1181
+ }
1182
+ }
1183
+
1184
+ impl<'a, K, V> VacantEntry<'a, K, V> {
1185
+ /// Inserts the given node into the [`RBTree`] at this entry.
1186
+ pub fn insert(self, value: V, reservation: RBTreeNodeReservation<K, V>) -> &'a mut V {
1187
+ self.raw.insert(reservation.into_node(self.key, value))
1188
+ }
1189
+ }
1190
+
1191
+ /// A view into an occupied entry in a [`RBTree`]. It is part of the [`Entry`] enum.
1192
+ ///
1193
+ /// # Invariants
1194
+ /// - `node_links` is a valid, non-null pointer to a tree node in `self.rbtree`
1195
+ pub struct OccupiedEntry<'a, K, V> {
1196
+ rbtree: &'a mut RBTree<K, V>,
1197
+ /// The node that this entry corresponds to.
1198
+ node_links: *mut bindings::rb_node,
1199
+ }
1200
+
1201
+ impl<'a, K, V> OccupiedEntry<'a, K, V> {
1202
+ /// Gets a reference to the value in the entry.
1203
+ pub fn get(&self) -> &V {
1204
+ // SAFETY:
1205
+ // - `self.node_links` is a valid pointer to a node in the tree.
1206
+ // - We have shared access to the underlying tree, and can thus give out a shared reference.
1207
+ unsafe { &(*container_of!(self.node_links, Node<K, V>, links)).value }
1208
+ }
1209
+
1210
+ /// Gets a mutable reference to the value in the entry.
1211
+ pub fn get_mut(&mut self) -> &mut V {
1212
+ // SAFETY:
1213
+ // - `self.node_links` is a valid pointer to a node in the tree.
1214
+ // - We have exclusive access to the underlying tree, and can thus give out a mutable reference.
1215
+ unsafe { &mut (*(container_of!(self.node_links, Node<K, V>, links).cast_mut())).value }
1216
+ }
1217
+
1218
+ /// Converts the entry into a mutable reference to its value.
1219
+ ///
1220
+ /// If you need multiple references to the `OccupiedEntry`, see [`self#get_mut`].
1221
+ pub fn into_mut(self) -> &'a mut V {
1222
+ // SAFETY:
1223
+ // - `self.node_links` is a valid pointer to a node in the tree.
1224
+ // - This consumes the `&'a mut RBTree<K, V>`, therefore it can give out a mutable reference that lives for `'a`.
1225
+ unsafe { &mut (*(container_of!(self.node_links, Node<K, V>, links).cast_mut())).value }
1226
+ }
1227
+
1228
+ /// Remove this entry from the [`RBTree`].
1229
+ pub fn remove_node(self) -> RBTreeNode<K, V> {
1230
+ // SAFETY: The node is a node in the tree, so it is valid.
1231
+ unsafe { bindings::rb_erase(self.node_links, &mut self.rbtree.root) };
1232
+
1233
+ // INVARIANT: The node is being returned and the caller may free it, however, it was
1234
+ // removed from the tree. So the invariants still hold.
1235
+ RBTreeNode {
1236
+ // SAFETY: The node was a node in the tree, but we removed it, so we can convert it
1237
+ // back into a box.
1238
+ node: unsafe {
1239
+ Box::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut())
1240
+ },
1241
+ }
1242
+ }
1243
+
1244
+ /// Takes the value of the entry out of the map, and returns it.
1245
+ pub fn remove(self) -> V {
1246
+ self.remove_node().node.value
1247
+ }
1248
+
1249
+ /// Swap the current node for the provided node.
1250
+ ///
1251
+ /// The key of both nodes must be equal.
1252
+ fn replace(self, node: RBTreeNode<K, V>) -> RBTreeNode<K, V> {
1253
+ let node = Box::into_raw(node.node);
1254
+
1255
+ // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
1256
+ // the node is removed or replaced.
1257
+ let new_node_links = unsafe { addr_of_mut!((*node).links) };
1258
+
1259
+ // SAFETY: This updates the pointers so that `new_node_links` is in the tree where
1260
+ // `self.node_links` used to be.
1261
+ unsafe {
1262
+ bindings::rb_replace_node(self.node_links, new_node_links, &mut self.rbtree.root)
1263
+ };
1264
+
1265
+ // SAFETY:
1266
+ // - `self.node_ptr` produces a valid pointer to a node in the tree.
1267
+ // - Now that we removed this entry from the tree, we can convert the node to a box.
1268
+ let old_node =
1269
+ unsafe { Box::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut()) };
1270
+
1271
+ RBTreeNode { node: old_node }
1272
+ }
1273
+ }
1274
+
1120
1275
struct Node<K, V> {
1121
1276
links: bindings::rb_node,
1122
1277
key: K,
0 commit comments