Insert a key-value pair and handle splitting if necessary.
(&mut self, key: K, value: V)
| 305 | |
| 306 | /// Insert a key-value pair and handle splitting if necessary. |
| 307 | pub fn insert(&mut self, key: K, value: V) -> InsertResult<K, V> { |
| 308 | // Do binary search once and use the result throughout |
| 309 | match self.binary_search_keys(&key) { |
| 310 | Ok(index) => { |
| 311 | // Key already exists, update the value |
| 312 | if let Some(old_val) = self.get_value_mut(index) { |
| 313 | let old_value = std::mem::replace(old_val, value); |
| 314 | InsertResult::Updated(Some(old_value)) |
| 315 | } else { |
| 316 | InsertResult::Updated(None) |
| 317 | } |
| 318 | } |
| 319 | Err(index) => { |
| 320 | // Key doesn't exist, need to insert |
| 321 | // Check if split is needed BEFORE inserting |
| 322 | if !self.is_full() { |
| 323 | // Room to insert without splitting |
| 324 | self.insert_at_index(index, key, value); |
| 325 | // Simple insertion - no split needed |
| 326 | return InsertResult::Updated(None); |
| 327 | } |
| 328 | |
| 329 | // Node is full, need to split |
| 330 | // Don't insert first. That causes the Vecs to overflow. |
| 331 | // Split the full node |
| 332 | let mut new_right = self.split(); |
| 333 | // Insert into the correct node |
| 334 | if index <= self.keys.len() { |
| 335 | self.insert_at_index(index, key, value); |
| 336 | } else { |
| 337 | new_right.insert_at_index(index - self.keys.len(), key, value); |
| 338 | } |
| 339 | |
| 340 | // Determine the separator key (first key of right node) |
| 341 | let separator_key = new_right.first_key().unwrap().clone(); |
| 342 | |
| 343 | InsertResult::Split { |
| 344 | old_value: None, |
| 345 | new_node_data: SplitNodeData::Leaf(new_right), |
| 346 | separator_key, |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | /// Insert a key-value pair at the specified index. |
| 353 | pub fn insert_at_index(&mut self, index: usize, key: K, value: V) { |