Insert a key-value pair into the tree. If the key already exists, the old value is returned and replaced. If the key is new, `None` is returned. # Arguments `key` - The key to insert `value` - The value to associate with the key # Returns The previous value associated with the key, if any. # Examples ``` use bplustree::BPlusTreeMap; let mut tree = BPlusTreeMap::new(16).unwrap(); assert_eq!
(&mut self, key: K, value: V)
| 228 | /// assert_eq!(tree.insert(1, "second"), Some("first")); |
| 229 | /// ``` |
| 230 | pub fn insert(&mut self, key: K, value: V) -> Option<V> { |
| 231 | // Use insert_recursive to handle the insertion |
| 232 | let result = self.insert_recursive(&self.root.clone(), key, value); |
| 233 | |
| 234 | match result { |
| 235 | InsertResult::Updated(old_value) => old_value, |
| 236 | InsertResult::Error(_error) => { |
| 237 | // Log the error but maintain API compatibility |
| 238 | // This should never happen with correct split logic |
| 239 | eprintln!("BPlusTree internal error during insert - data integrity violation"); |
| 240 | None |
| 241 | } |
| 242 | InsertResult::Split { |
| 243 | old_value, |
| 244 | new_node_data, |
| 245 | separator_key, |
| 246 | } => { |
| 247 | // Root split - need to create a new root |
| 248 | let new_node_ref = match new_node_data { |
| 249 | SplitNodeData::Leaf(new_leaf_data) => { |
| 250 | let new_id = self.allocate_leaf(new_leaf_data); |
| 251 | |
| 252 | // Update linked list pointers for root leaf split |
| 253 | if let Some(leaf) = matches!(&self.root, NodeRef::Leaf(_, _)) |
| 254 | .then(|| self.root.id()) |
| 255 | .and_then(|original_id| self.get_leaf_mut(original_id)) |
| 256 | { |
| 257 | leaf.next = new_id; |
| 258 | } |
| 259 | |
| 260 | NodeRef::Leaf(new_id, PhantomData) |
| 261 | } |
| 262 | SplitNodeData::Branch(new_branch_data) => { |
| 263 | let new_id = self.allocate_branch(new_branch_data); |
| 264 | NodeRef::Branch(new_id, PhantomData) |
| 265 | } |
| 266 | SplitNodeData::AllocatedLeaf(new_id) => { |
| 267 | // Node already allocated, just create NodeRef |
| 268 | NodeRef::Leaf(new_id, PhantomData) |
| 269 | } |
| 270 | SplitNodeData::AllocatedBranch(new_id) => { |
| 271 | // Node already allocated, just create NodeRef |
| 272 | NodeRef::Branch(new_id, PhantomData) |
| 273 | } |
| 274 | }; |
| 275 | |
| 276 | // Create new root with the split nodes |
| 277 | let new_root = self.new_root(new_node_ref, separator_key); |
| 278 | let root_id = self.allocate_branch(new_root); |
| 279 | self.root = NodeRef::Branch(root_id, PhantomData); |
| 280 | |
| 281 | old_value |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | #[cfg(test)] |
nothing calls this directly
no test coverage detected