1use arrayvec::ArrayVec;
2use std::{mem, sync::Arc};
3
4#[derive(Clone, Debug)]
6pub struct BTreeMap<K, V> {
7 root: Arc<Node<K, V>>,
8 length: usize,
9}
10
11impl<K, V> BTreeMap<K, V> {
12 #[must_use]
14 pub fn new() -> Self {
15 Self {
16 root: Arc::new(Node::Leaf(NodeLeaf {
17 keys: ArrayVec::new(),
18 values: ArrayVec::new(),
19 })),
20 length: 0,
21 }
22 }
23
24 pub fn insert(&mut self, key: K, value: V) -> Option<V>
26 where
27 K: Clone + Ord,
28 V: Clone,
29 {
30 let root = Arc::make_mut(&mut self.root);
31 match root.insert(key, value) {
32 NodeInsertResult::Replaced(previous_value) => Some(previous_value),
33 NodeInsertResult::Inserted => {
34 self.length += 1;
35 None
36 }
37 NodeInsertResult::Split(parent_key, child_right) => {
41 let child_left = {
44 let parent = Node::Branch(NodeBranch {
45 keys: ArrayVec::new(),
46 children: ArrayVec::new(),
47 });
48 mem::replace(root, parent)
49 };
50
51 let child_left_max = &child_left.keys()[child_left.keys().len() - 1];
52 let child_right_min = &child_right.keys()[0];
53 assert!(child_left_max < child_right_min, "Left child < right child");
54 assert!(*child_left_max < parent_key, "Left child max < parent key");
55 assert!(
56 child_right.is_branch() || *child_right_min == parent_key,
57 "Right child min == parent key"
58 );
59
60 let Node::Branch(parent) = root else {
61 unreachable!()
62 };
63 parent.keys.push(parent_key);
64 parent.children.push(Arc::new(child_left));
65 parent.children.push(Arc::new(child_right));
66
67 self.length += 1;
68 None
69 }
70 }
71 }
72
73 pub fn remove(&mut self, key: &K) -> Option<V>
80 where
81 K: Clone + Ord,
82 V: Clone,
83 {
84 if !self.contains_key(key) {
86 return None;
87 }
88 let root = Arc::make_mut(&mut self.root);
89 if let Some(value) = root.remove(key) {
90 self.length -= 1;
91 Some(value)
92 } else {
93 None
94 }
95 }
96
97 pub fn get(&self, key: &K) -> Option<&V>
99 where
100 K: Ord,
101 {
102 self.root.get(key)
103 }
104
105 pub fn get_mut(&mut self, key: &K) -> Option<&mut V>
107 where
108 K: Clone + Ord,
109 V: Clone,
110 {
111 if !self.contains_key(key) {
113 return None;
114 }
115 let root = Arc::make_mut(&mut self.root);
116 root.get_mut(key)
117 }
118
119 pub fn contains_key(&self, key: &K) -> bool
121 where
122 K: Ord,
123 {
124 self.root.contains_key(key)
125 }
126
127 #[must_use]
129 pub fn len(&self) -> usize {
130 self.length
131 }
132
133 #[must_use]
135 pub fn is_empty(&self) -> bool {
136 self.len() == 0
137 }
138
139 #[expect(dead_code)]
140 fn assert_invariants(&self)
141 where
142 K: Ord,
143 {
144 self.root.assert_invariants("root", 0);
145 }
146}
147
148impl<K, V> Default for BTreeMap<K, V> {
149 fn default() -> Self {
150 Self::new()
151 }
152}
153
154impl<K, V> Extend<(K, V)> for BTreeMap<K, V>
155where
156 K: Clone + Ord,
157 V: Clone,
158{
159 fn extend<I>(&mut self, iter: I)
160 where
161 I: IntoIterator<Item = (K, V)>,
162 {
163 for (key, value) in iter {
166 self.insert(key, value);
167 }
168 }
169}
170
171#[cfg(not(test))]
172const D: usize = 42; #[cfg(test)]
174const D: usize = 2;
175
176const H_MAX: usize = 38;
186const _: () = assert!(D >= 2, "`H_MAX` assumes `D` >= 2");
187
188#[cfg_attr(not(test), expect(clippy::large_enum_variant))]
189#[derive(Clone, Debug)]
190enum Node<K, V> {
191 Branch(NodeBranch<K, V>),
192 Leaf(NodeLeaf<K, V>),
193}
194
195impl<K, V> Node<K, V> {
196 fn insert(&mut self, key: K, value: V) -> NodeInsertResult<K, V>
197 where
198 K: Clone + Ord,
199 V: Clone,
200 {
201 match self {
202 Self::Branch(branch) => branch.insert(key, value),
203 Self::Leaf(leaf) => leaf.insert(key, value),
204 }
205 }
206
207 fn remove(&mut self, key: &K) -> Option<V>
208 where
209 K: Clone + Ord,
210 V: Clone,
211 {
212 match self {
213 Self::Branch(branch) => branch.remove(key),
214 Self::Leaf(leaf) => leaf.remove(key),
215 }
216 }
217
218 fn get(&self, key: &K) -> Option<&V>
219 where
220 K: Ord,
221 {
222 match self {
223 Self::Branch(branch) => branch.get(key),
224 Self::Leaf(leaf) => leaf.get(key),
225 }
226 }
227
228 fn get_mut(&mut self, key: &K) -> Option<&mut V>
229 where
230 K: Clone + Ord,
231 V: Clone,
232 {
233 match self {
234 Self::Branch(branch) => branch.get_mut(key),
235 Self::Leaf(leaf) => leaf.get_mut(key),
236 }
237 }
238
239 fn contains_key(&self, key: &K) -> bool
240 where
241 K: Ord,
242 {
243 match self {
244 Self::Branch(branch) => branch.contains_key(key),
245 Self::Leaf(leaf) => leaf.contains_key(key),
246 }
247 }
248
249 fn keys(&self) -> &[K] {
250 match self {
251 Self::Branch(branch) => branch.keys.as_slice(),
252 Self::Leaf(leaf) => leaf.keys.as_slice(),
253 }
254 }
255
256 fn is_branch(&self) -> bool {
257 matches!(self, Self::Branch(_))
258 }
259
260 #[cfg_attr(not(test), expect(dead_code))]
261 fn is_leaf(&self) -> bool {
262 matches!(self, Self::Leaf(_))
263 }
264
265 fn assert_invariants(&self, path: &str, depth: u8)
266 where
267 K: Ord,
268 {
269 match self {
270 Self::Branch(branch) => branch.assert_invariants(path, depth),
271 Self::Leaf(leaf) => leaf.assert_invariants(path, depth),
272 }
273 }
274}
275
276#[expect(dead_code)]
277struct NodeSearchResult {
278 branches: ArrayVec<usize, H_MAX>,
279 leaf: LeafSearchResult,
280}
281
282#[cfg_attr(not(test), expect(clippy::large_enum_variant))]
283enum NodeInsertResult<K, V> {
284 Replaced(V),
285 Inserted,
286 Split(K, Node<K, V>),
287}
288
289#[derive(Clone, Debug)]
290struct NodeBranch<K, V> {
291 keys: ArrayVec<K, { (2 * D) + 1 }>,
292 children: ArrayVec<Arc<Node<K, V>>, { (2 * D) + 2 }>,
293}
294
295impl<K, V> NodeBranch<K, V> {
296 fn search(&self, key: &K) -> usize
297 where
298 K: Ord,
299 {
300 self.keys.partition_point(|k| k <= key)
301 }
302
303 fn split(&mut self) -> (K, Self)
304 where
305 K: Clone,
306 {
307 assert!(self.is_overflowing(), "Only overflowing branches are split");
308 let mut sibling = Self {
309 keys: self.keys.drain(D..).collect(),
310 children: self.children.drain(D + 1..).collect(),
311 };
312 let parent_key = sibling.keys.remove(0);
313 assert_eq!(self.keys.len(), D);
314 assert_eq!(self.children.len(), D + 1);
315 assert_eq!(sibling.keys.len(), D);
316 assert_eq!(sibling.children.len(), D + 1);
317 (parent_key, sibling)
318 }
319
320 fn insert(&mut self, key: K, value: V) -> NodeInsertResult<K, V>
321 where
322 K: Clone + Ord,
323 V: Clone,
324 {
325 let index = self.search(&key);
326 let child = Arc::make_mut(&mut self.children[index]);
327 match child.insert(key, value) {
328 NodeInsertResult::Split(key, child) => {
329 self.keys.insert(index, key);
330 self.children.insert(index + 1, Arc::new(child));
331 if self.is_overflowing() {
332 let (parent_key, sibling) = self.split();
333 NodeInsertResult::Split(parent_key, Node::Branch(sibling))
334 } else {
335 NodeInsertResult::Inserted
336 }
337 }
338 no_split => no_split,
339 }
340 }
341
342 fn remove(&mut self, key: &K) -> Option<V>
343 where
344 K: Clone + Ord,
345 V: Clone,
346 {
347 let index = self.search(key);
348 let child = Arc::make_mut(&mut self.children[index]);
349 child.remove(key)
350 }
351
352 fn get(&self, key: &K) -> Option<&V>
353 where
354 K: Ord,
355 {
356 let index = self.search(key);
357 let child = &self.children[index];
358 child.get(key)
359 }
360
361 fn get_mut(&mut self, key: &K) -> Option<&mut V>
362 where
363 K: Clone + Ord,
364 V: Clone,
365 {
366 let index = self.search(key);
367 let child = Arc::make_mut(&mut self.children[index]);
368 child.get_mut(key)
369 }
370
371 fn contains_key(&self, key: &K) -> bool
372 where
373 K: Ord,
374 {
375 let index = self.search(key);
376 let child = &self.children[index];
377 child.contains_key(key)
378 }
379
380 #[expect(dead_code)]
381 fn is_full(&self) -> bool {
382 self.keys.len() + 1 == self.keys.capacity()
383 }
384
385 fn is_overflowing(&self) -> bool {
386 self.keys.is_full()
387 }
388
389 fn assert_invariants(&self, path: &str, depth: u8)
390 where
391 K: Ord,
392 {
393 assert_eq!(
394 self.keys.len() + 1,
395 self.children.len(),
396 "{path}: keys.len() + 1 != children.len()"
397 );
398 assert!(!self.is_overflowing(), "{path}: overflowing");
399 for (i, child) in self.children.iter().enumerate() {
403 child.assert_invariants(
404 &format!(
405 "{path}->{}{i}",
406 if child.is_branch() { "branch" } else { "leaf" }
407 ),
408 depth + 1,
409 );
410 }
411 }
412}
413
414#[derive(Clone, Debug)]
415struct NodeLeaf<K, V> {
416 keys: ArrayVec<K, { (2 * D) + 1 }>,
417 values: ArrayVec<V, { (2 * D) + 1 }>,
418}
419
420impl<K, V> NodeLeaf<K, V> {
421 fn search(&self, key: &K) -> LeafSearchResult
422 where
423 K: Ord,
424 {
425 match self.keys.binary_search(key) {
426 Ok(index) => LeafSearchResult::Found(index),
427 Err(index) => LeafSearchResult::Missing(index),
428 }
429 }
430
431 fn split(&mut self) -> (K, Self)
432 where
433 K: Clone,
434 {
435 assert!(self.is_overflowing(), "Only overflowing leaves are split");
436 let self_len = D;
437 let sibling_len = D + 1;
438 let sibling = Self {
439 keys: self.keys.drain(self_len..).collect(),
440 values: self.values.drain(self_len..).collect(),
441 };
442 let parent_key = sibling.keys[0].clone();
443 assert_eq!(self.keys.len(), self_len);
444 assert_eq!(sibling.keys.len(), sibling_len);
445 (parent_key, sibling)
446 }
447
448 fn insert(&mut self, key: K, value: V) -> NodeInsertResult<K, V>
449 where
450 K: Clone + Ord,
451 {
452 match self.search(&key) {
453 LeafSearchResult::Found(index) => {
454 let previous_value = mem::replace(&mut self.values[index], value);
455 NodeInsertResult::Replaced(previous_value)
456 }
457 LeafSearchResult::Missing(index) => {
458 self.keys.insert(index, key);
459 self.values.insert(index, value);
460 if self.is_overflowing() {
461 let (parent_key, sibling) = self.split();
462 NodeInsertResult::Split(parent_key, Node::Leaf(sibling))
463 } else {
464 NodeInsertResult::Inserted
465 }
466 }
467 }
468 }
469
470 fn remove(&mut self, key: &K) -> Option<V>
471 where
472 K: Ord,
473 {
474 match self.search(key) {
475 LeafSearchResult::Found(index) => {
476 self.keys.remove(index);
477 let value = self.values.remove(index);
478 Some(value)
479 }
480 LeafSearchResult::Missing(_) => None,
481 }
482 }
483
484 fn get(&self, key: &K) -> Option<&V>
485 where
486 K: Ord,
487 {
488 match self.search(key) {
489 LeafSearchResult::Found(index) => Some(&self.values[index]),
490 LeafSearchResult::Missing(_) => None,
491 }
492 }
493
494 fn get_mut(&mut self, key: &K) -> Option<&mut V>
495 where
496 K: Ord,
497 {
498 match self.search(key) {
499 LeafSearchResult::Found(index) => Some(&mut self.values[index]),
500 LeafSearchResult::Missing(_) => None,
501 }
502 }
503
504 fn contains_key(&self, key: &K) -> bool
505 where
506 K: Ord,
507 {
508 matches!(self.search(key), LeafSearchResult::Found(_))
509 }
510
511 #[expect(dead_code)]
512 fn is_full(&self) -> bool {
513 self.keys.len() + 1 == self.keys.capacity()
514 }
515
516 fn is_overflowing(&self) -> bool {
517 self.keys.is_full()
518 }
519
520 fn assert_invariants(&self, path: &str, _depth: u8)
521 where
522 K: Ord,
523 {
524 assert!(
525 self.keys.len() == self.values.len(),
526 "{path}: keys.len() != values.len()"
527 );
528 assert!(!self.is_overflowing(), "{path}: overflowing");
529 assert!(self.keys.is_sorted(), "{path}: keys are not sorted");
530 }
531}
532
533enum LeafSearchResult {
534 Found(usize),
535 Missing(usize),
536}
537
538#[cfg(test)]
539mod tests {
540 use super::*;
541
542 fn xorshift(mut x: u32) -> u32 {
543 assert!(x != 0);
544 x ^= x << 13;
545 x ^= x >> 17;
546 x ^= x << 5;
547 x
548 }
549
550 #[test]
551 fn big_insert() {
552 let mut map = BTreeMap::new();
553 let count: u32 = 1000;
554 for x in (1..=count).map(xorshift) {
555 map.insert(x, x);
556 }
557 assert_eq!(map.len(), 1000);
558 for x in (1..=count).map(xorshift) {
559 assert_eq!(map.remove(&x), Some(x));
560 }
561 assert!(map.is_empty());
562 }
563
564 #[test]
565 fn leaf_split() {
566 let mut leaf1 = NodeLeaf {
567 keys: ArrayVec::new(),
568 values: ArrayVec::new(),
569 };
570
571 assert!(matches!(leaf1.insert(1, 11), NodeInsertResult::Inserted));
572 assert!(matches!(leaf1.insert(2, 22), NodeInsertResult::Inserted));
573 assert!(matches!(leaf1.insert(3, 33), NodeInsertResult::Inserted));
574 assert!(matches!(leaf1.insert(4, 44), NodeInsertResult::Inserted));
575 let NodeInsertResult::Split(parent_key, Node::Leaf(leaf2)) = leaf1.insert(5, 55) else {
576 panic!();
577 };
578
579 assert_eq!(leaf1.keys.as_slice(), &[1, 2]);
580 assert_eq!(leaf1.values.as_slice(), &[11, 22]);
581
582 assert_eq!(parent_key, 3);
583
584 assert_eq!(leaf2.keys.as_slice(), &[3, 4, 5]);
585 assert_eq!(leaf2.values.as_slice(), &[33, 44, 55]);
586 }
587
588 #[test]
589 fn leaf_to_branch() {
590 let mut map = BTreeMap::new();
591 assert!(map.insert(1, 11).is_none());
592 assert!(map.insert(2, 22).is_none());
593 assert!(map.insert(3, 33).is_none());
594 assert!(map.insert(4, 44).is_none());
595 assert!(map.root.is_leaf());
596 assert!(map.insert(5, 55).is_none());
597 assert!(map.root.is_branch());
598 assert_eq!(map.len(), 5);
599 }
600}