@@ -297,12 +297,18 @@ 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+ // The returned `RawEntry` is used to call either `rb_link_node` or `rb_replace_node`.
306312 // The parameters of `rb_link_node` are as follows:
307313 // - `node`: A pointer to an uninitialized node being inserted.
308314 // - `parent`: A pointer to an existing node in the tree. One of its child pointers must be
@@ -322,61 +328,52 @@ where
322328 // we find an empty subtree, we can insert the new node using `rb_link_node`.
323329 let mut parent = core:: ptr:: null_mut ( ) ;
324330 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+ while !( * child_field_of_parent) . is_null ( ) {
332+ let curr = * child_field_of_parent;
333+ // SAFETY: All links fields we create are in a `Node<K, V>`.
334+ let node = unsafe { container_of ! ( curr, Node <K , V >, links) } ;
327335
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 } ,
336+ // SAFETY: `node` is a non-null node so it is valid by the type invariants.
337+ match key. cmp ( unsafe { & ( * node) . key } ) {
338+ // SAFETY: `curr` is a non-null node so it is valid by the type invariants.
339+ Ordering :: Less => child_field_of_parent = unsafe { & mut ( * curr) . rb_left } ,
340+ // SAFETY: `curr` is a non-null node so it is valid by the type invariants.
341+ Ordering :: Greater => child_field_of_parent = unsafe { & mut ( * curr) . rb_right } ,
348342 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- } ) ;
343+ return RawEntry :: Occupied ( OccupiedEntry {
344+ rbtree : self ,
345+ node_links : curr,
346+ } )
363347 }
364348 }
349+ parent = curr;
365350 }
366351
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) } ;
352+ RawEntry :: Vacant ( RawVacantEntry {
353+ parent,
354+ child_field_of_parent,
355+ rbtree : self ,
356+ } )
357+ }
372358
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
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+ }
376365 }
377366
378- /// Returns a node with the given key, if one exists.
379- fn find ( & self , key : & K ) -> Option < NonNull < Node < K , V > > > {
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+ }
373+ }
374+
375+ /// Returns a reference to the value corresponding to the key.
376+ pub fn get ( & self , key : & K ) -> Option < & V > {
380377 let mut node = self . root . rb_node ;
381378 while !node. is_null ( ) {
382379 // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
@@ -388,47 +385,30 @@ where
388385 Ordering :: Less => unsafe { ( * node) . rb_left } ,
389386 // SAFETY: `node` is a non-null node so it is valid by the type invariants.
390387 Ordering :: Greater => unsafe { ( * node) . rb_right } ,
391- 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 } ) ,
392390 }
393391 }
394392 None
395393 }
396394
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-
403395 /// Returns a mutable reference to the value corresponding to the key.
404396 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 } )
397+ self . find_mut ( key) . map ( |node| node. into_mut ( ) )
408398 }
409399
410400 /// Removes the node with the given key from the tree.
411401 ///
412402 /// 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- } )
403+ pub fn remove_node ( & mut self , key : & K ) -> Option < RBTreeNode < K , V > > {
404+ self . find_mut ( key) . map ( OccupiedEntry :: remove_node)
425405 }
426406
427407 /// Removes the node with the given key from the tree.
428408 ///
429409 /// It returns the value that was removed if one exists, or [`None`] otherwise.
430410 pub fn remove ( & mut self , key : & K ) -> Option < V > {
431- self . remove_node ( key) . map ( |node| node . node . value )
411+ self . find_mut ( key) . map ( OccupiedEntry :: remove )
432412 }
433413
434414 /// Returns a cursor over the tree nodes based on the given key.
@@ -1124,6 +1104,173 @@ unsafe impl<K: Send, V: Send> Send for RBTreeNode<K, V> {}
11241104// [`RBTreeNode`] without synchronization.
11251105unsafe impl < K : Sync , V : Sync > Sync for RBTreeNode < K , V > { }
11261106
1107+ impl < K , V > RBTreeNode < K , V > {
1108+ /// Drop the key and value, but keep the allocation.
1109+ ///
1110+ /// It then becomes a reservation that can be re-initialised into a different node (i.e., with
1111+ /// a different key and/or value).
1112+ ///
1113+ /// The existing key and value are dropped in-place as part of this operation, that is, memory
1114+ /// may be freed (but only for the key/value; memory for the node itself is kept for reuse).
1115+ pub fn into_reservation ( self ) -> RBTreeNodeReservation < K , V > {
1116+ RBTreeNodeReservation {
1117+ node : Box :: drop_contents ( self . node ) ,
1118+ }
1119+ }
1120+ }
1121+
1122+ /// A view into a single entry in a map, which may either be vacant or occupied.
1123+ ///
1124+ /// This enum is constructed from the [`RBTree::entry`].
1125+ ///
1126+ /// [`entry`]: fn@RBTree::entry
1127+ pub enum Entry < ' a , K , V > {
1128+ /// This [`RBTree`] does not have a node with this key.
1129+ Vacant ( VacantEntry < ' a , K , V > ) ,
1130+ /// This [`RBTree`] already has a node with this key.
1131+ Occupied ( OccupiedEntry < ' a , K , V > ) ,
1132+ }
1133+
1134+ /// Like [`Entry`], except that it doesn't have ownership of the key.
1135+ enum RawEntry < ' a , K , V > {
1136+ Vacant ( RawVacantEntry < ' a , K , V > ) ,
1137+ Occupied ( OccupiedEntry < ' a , K , V > ) ,
1138+ }
1139+
1140+ /// A view into a vacant entry in a [`RBTree`]. It is part of the [`Entry`] enum.
1141+ pub struct VacantEntry < ' a , K , V > {
1142+ key : K ,
1143+ raw : RawVacantEntry < ' a , K , V > ,
1144+ }
1145+
1146+ /// Like [`VacantEntry`], but doesn't hold on to the key.a
1147+ ///
1148+ /// # Invariants
1149+ /// - `parent` may be null if the new node becomes the root.
1150+ /// - `child_field_of_parent` is a valid pointer to the left-child or right-child of `parent`. If `parent` is
1151+ /// null, it is a pointer to the root of the [`RBTree`].
1152+ struct RawVacantEntry < ' a , K , V > {
1153+ rbtree : & ' a mut RBTree < K , V > ,
1154+ /// The node that will become the parent of the new node if we insert one.
1155+ parent : * mut bindings:: rb_node ,
1156+ /// This points to the left-child or right-child field of `parent`, or `root` if `parent` is
1157+ /// null.
1158+ child_field_of_parent : * mut * mut bindings:: rb_node ,
1159+ }
1160+
1161+ impl < ' a , K , V > RawVacantEntry < ' a , K , V > {
1162+ /// Inserts the given node into the [`RBTree`] at this entry.
1163+ ///
1164+ /// The `node` must have a key such that inserting it here does not break the ordering of this
1165+ /// [`RBTree`].
1166+ fn insert ( self , node : RBTreeNode < K , V > ) -> & ' a mut V {
1167+ let node = Box :: into_raw ( node. node ) ;
1168+
1169+ // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
1170+ // the node is removed or replaced.
1171+ let node_links = unsafe { addr_of_mut ! ( ( * node) . links) } ;
1172+
1173+ // INVARIANT: We are linking in a new node, which is valid. It remains valid because we
1174+ // "forgot" it with `Box::into_raw`.
1175+ // SAFETY: The type invariants of `RawVacantEntry` are exactly the safety requirements of `rb_link_node`.
1176+ unsafe { bindings:: rb_link_node ( node_links, self . parent , self . child_field_of_parent ) } ;
1177+
1178+ // SAFETY: All pointers are valid. `node` has just been inserted into the tree.
1179+ unsafe { bindings:: rb_insert_color ( node_links, & mut self . rbtree . root ) } ;
1180+
1181+ // SAFETY: The node is valid until we remove it from the tree.
1182+ unsafe { & mut ( * node) . value }
1183+ }
1184+ }
1185+
1186+ impl < ' a , K , V > VacantEntry < ' a , K , V > {
1187+ /// Inserts the given node into the [`RBTree`] at this entry.
1188+ pub fn insert ( self , value : V , reservation : RBTreeNodeReservation < K , V > ) -> & ' a mut V {
1189+ self . raw . insert ( reservation. into_node ( self . key , value) )
1190+ }
1191+ }
1192+
1193+ /// A view into an occupied entry in a [`RBTree`]. It is part of the [`Entry`] enum.
1194+ ///
1195+ /// # Invariants
1196+ /// - `node_links` is a valid, non-null pointer to a tree node in `self.rbtree`
1197+ pub struct OccupiedEntry < ' a , K , V > {
1198+ rbtree : & ' a mut RBTree < K , V > ,
1199+ /// The node that this entry corresponds to.
1200+ node_links : * mut bindings:: rb_node ,
1201+ }
1202+
1203+ impl < ' a , K , V > OccupiedEntry < ' a , K , V > {
1204+ fn node_ptr ( & self ) -> * mut Node < K , V > {
1205+ // SAFETY: By the type invariant of `Self`, all `node_links` pointers stored in `self`
1206+ // point to the links field of `Node<K, V>` objects.
1207+ unsafe { container_of ! ( self . node_links, Node <K , V >, links) } . cast_mut ( )
1208+ }
1209+
1210+ /// Gets a reference to the value in the entry.
1211+ pub fn get ( & self ) -> & V {
1212+ // SAFETY: `self.node_ptr` produces a valid pointer to a node in the tree.
1213+ unsafe { & ( * self . node_ptr ( ) ) . value }
1214+ }
1215+
1216+ /// Gets a mutable reference to the value in the entry.
1217+ pub fn get_mut ( & mut self ) -> & mut V {
1218+ // SAFETY: `self.node_ptr` produces a valid pointer to a node in the tree.
1219+ unsafe { & mut ( * self . node_ptr ( ) ) . value }
1220+ }
1221+
1222+ /// Converts the entry into a mutable reference to its value.
1223+ ///
1224+ /// If you need multiple references to the `OccupiedEntry`, see [`self#get_mut`].
1225+ pub fn into_mut ( self ) -> & ' a mut V {
1226+ // SAFETY: `self.node_ptr` produces a valid pointer to a node in the tree.
1227+ unsafe { & mut ( * self . node_ptr ( ) ) . value }
1228+ }
1229+
1230+ /// Remove this entry from the [`RBTree`].
1231+ pub fn remove_node ( self ) -> RBTreeNode < K , V > {
1232+ // SAFETY: The node is a node in the tree, so it is valid.
1233+ unsafe { bindings:: rb_erase ( self . node_links , & mut self . rbtree . root ) } ;
1234+
1235+ // INVARIANT: The node is being returned and the caller may free it, however, it was
1236+ // removed from the tree. So the invariants still hold.
1237+ RBTreeNode {
1238+ // SAFETY: The node was a node in the tree, but we removed it, so we can convert it
1239+ // back into a box.
1240+ node : unsafe { Box :: from_raw ( self . node_ptr ( ) ) } ,
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 = unsafe { Box :: from_raw ( self . node_ptr ( ) ) } ;
1269+
1270+ RBTreeNode { node : old_node }
1271+ }
1272+ }
1273+
11271274struct Node < K , V > {
11281275 links : bindings:: rb_node ,
11291276 key : K ,
0 commit comments