augmented_rbtree/augmented_rbtree.rs
1use core::{fmt::Debug, ops::Bound};
2
3use crate::{
4 Augment,
5 alloc_proxy::proxy::{AllocError, Allocator, Global},
6 augmentations,
7 policy::internal_details::{
8 DefaultTraitPolicy, FullAugmentationStrategy, NullAugmentationStrategy,
9 },
10};
11
12/// An error type representing an out-of-memory condition when a tree tries to allocate a node.
13pub struct OutOfMemoryError {
14 pub(crate) error: AllocError,
15 pub(crate) size: usize,
16}
17
18impl Debug for OutOfMemoryError {
19 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
20 f.debug_struct("OutOfMemoryError")
21 .field("error", &self.error)
22 .field("size", &self.size)
23 .finish()
24 }
25}
26
27impl OutOfMemoryError {
28 pub(crate) fn new(size: usize, error: AllocError) -> Self {
29 Self { error, size }
30 }
31}
32
33impl core::fmt::Display for OutOfMemoryError {
34 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
35 write!(
36 f,
37 "Out of memory when trying to allocate {} bytes: {:?}",
38 self.size, self.error
39 )
40 }
41}
42
43impl core::error::Error for OutOfMemoryError {}
44
45/// It is used to specify the location of the node in the tree where the cursor should be initially positioned.
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub enum TreeLocation<Q> {
48 /// Root of the tree
49 Root,
50
51 /// Position at a specific key
52 At(Q),
53
54 /// The cursor will be positioned at the leftmost (minimum) node in the tree.
55 Leftmost,
56
57 /// Rightmost (maximum) node in the tree.
58 Rightmost,
59
60 /// The cursor will be positioned at the first node whose key is greater than (or equal) to the given key depending on the bound type.
61 LowerBound(Bound<Q>),
62
63 /// The cursor will be positioned at the first node whose key is less than (or equal) to the given key depending on the bound type.
64 UpperBound(Bound<Q>),
65}
66
67/// A Red-Black Tree that supports augmentation through the `Augment` trait.
68/// This is the main type that users will interact with.
69/// The `AugmentedRBTree` type is a wrapper around the internal [`AugmentedRBTreeInt`](internal_details::AugmentedRBTreeInt) type, which handles the actual tree operations and augmentation logic.
70pub type AugmentedRBTree<K, V, G, A = Global> = internal_details::AugmentedRBTreeInt<
71 K,
72 V,
73 <G as Augment<K, V>>::Stats,
74 A,
75 DefaultTraitPolicy<K, V, G, <G as Augment<K, V>>::Stats, A, FullAugmentationStrategy>,
76>;
77
78/// A standard Red-Black Tree without augmentation.
79/// This is equivalent to `AugmentedRBTree<K, V, Unit>`.
80pub type RBTree<K, V, A = Global> = internal_details::AugmentedRBTreeInt<
81 K,
82 V,
83 (),
84 A,
85 DefaultTraitPolicy<K, V, augmentations::Unit, (), A, NullAugmentationStrategy>,
86>;
87
88/// A factory for creating `AugmentedRBTree` instances with default parameters.
89#[derive(Debug)]
90pub struct AugmentedRBTreeFactory<G> {
91 _marker: core::marker::PhantomData<fn() -> G>,
92}
93
94impl<G> AugmentedRBTreeFactory<G> {
95 /// Creates a tree using the `Global` allocator.
96 ///
97 /// # Examples
98 ///
99 /// ```
100 /// # use augmented_rbtree::{AugmentedRBTreeFactory, augmentations::SubtreeSize};
101 /// let mut tree = AugmentedRBTreeFactory::<SubtreeSize>::new_tree();
102 /// tree.insert(1, 100);
103 /// assert!(tree.contains_key(&1));
104 /// ```
105 /// Type inference for K and V works automatically here!
106 #[must_use]
107 pub fn new_tree<K, V>() -> crate::AugmentedRBTree<K, V, G, Global>
108 where
109 K: Ord,
110 G: Augment<K, V>,
111 {
112 AugmentedRBTree::new_in(Global)
113 }
114
115 /// Creates a tree using a custom allocator.
116 ///
117 /// # Examples
118 /// ```
119 /// #![cfg_attr(feature = "nightly", feature(allocator_api))]
120 /// use augmented_rbtree::{AugmentedRBTreeFactory, augmentations::SubtreeSize, Global};
121 /// let mut tree = AugmentedRBTreeFactory::<SubtreeSize>::new_tree_in(Global);
122 /// tree.insert(1, 100);
123 /// assert!(tree.contains_key(&1));
124 /// ```
125 #[must_use]
126 pub fn new_tree_in<K, V, A: Allocator>(alloc: A) -> crate::AugmentedRBTree<K, V, G, A>
127 where
128 K: Ord,
129 G: Augment<K, V>,
130 {
131 AugmentedRBTree::new_in(alloc)
132 }
133}
134
135#[doc(hidden)]
136pub mod internal_details {
137 use core::{
138 borrow::Borrow,
139 fmt::{self},
140 marker::PhantomData,
141 mem,
142 ops::{Bound, RangeBounds},
143 };
144
145 use crate::{
146 Entry, TreeLocation,
147 alloc_proxy::proxy::{Allocator, Global, Layout, handle_alloc_error},
148 augmented_rbtree::OutOfMemoryError,
149 cursor::{NavCursor, NavCursorMut},
150 iterators::{
151 IntoIter, Iter, IterMut, Keys, NodeGuard, Range, RangeBoundsLimits, RangeMut, Stats,
152 Values,
153 },
154 layout::AugmentedRBTreeLayout,
155 node::{Color, Node, internal_details::NodeRef},
156 node_allocator::NodeAllocator,
157 policy::internal_details::TreePolicy,
158 };
159
160 /// A Red-Black Tree that supports augmentation through the `Augment` trait.
161 pub struct AugmentedRBTreeInt<K, V, S, A, P>
162 where
163 P: TreePolicy<K = K, V = V, S = S>,
164 A: Allocator,
165 {
166 pub(crate) layout: AugmentedRBTreeLayout<K, V, S, A, P>,
167 }
168
169 impl<K, V, S, P> AugmentedRBTreeInt<K, V, S, Global, P>
170 where
171 P: TreePolicy<K = K, V = V, S = S>,
172 {
173 /// Creates a new, empty `AugmentedRBTree` using the global allocator.
174 #[inline]
175 #[must_use]
176 pub fn new() -> Self {
177 Self {
178 layout: AugmentedRBTreeLayout::<K, V, S, Global, P> {
179 root: None,
180 node_allocator: NodeAllocator::new(Global),
181 len: 0,
182 _marker: PhantomData,
183 },
184 }
185 }
186 }
187
188 impl<K, V, S, A, P> AugmentedRBTreeInt<K, V, S, A, P>
189 where
190 P: TreePolicy<K = K, V = V, S = S>,
191 A: Allocator,
192 {
193 /// Inserts a key-value pair into the tree. If the key already exists, its value is updated.
194 ///
195 /// # Returns
196 /// Returns `Some(old_value)` if the key was already present, or `None` if the key was newly inserted.
197 ///
198 /// # Examples
199 ///
200 /// ```
201 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
202 /// let mut tree = AugmentedRBTree::<String, i32, SubtreeSize>::new();
203 /// tree.insert("hello".to_string(), 1);
204 /// assert_eq!(tree.insert("hello".to_string(), 2), Some(1));
205 /// assert_eq!(tree.insert("world".to_string(), 3), None);
206 /// ```
207 pub fn insert(&mut self, key: K, value: V) -> Option<V>
208 where
209 K: Ord,
210 {
211 self.try_insert(key, value)
212 .unwrap_or_else(|_| handle_alloc_error(Layout::new::<Node<K, V, S>>()))
213 }
214
215 /// Try to insert a key with a value
216 pub fn try_insert(&mut self, key: K, value: V) -> Result<Option<V>, OutOfMemoryError>
217 where
218 K: Ord,
219 {
220 self.layout.try_insert_node(key, value)
221 }
222
223 /// Returns the number of elements in the tree.
224 pub fn len(&self) -> usize {
225 self.layout.len
226 }
227
228 /// Returns a reference to the value associated with the given key, if it exists in the tree.
229 ///
230 /// The key may be any borrowed form of the tree's key type, but the ordering on the borrowed
231 /// form *must* match the ordering on the key type.
232 ///
233 /// # Examples
234 ///
235 /// ```
236 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
237 /// let mut tree = AugmentedRBTree::<String, i32, SubtreeSize>::new();
238 /// tree.insert("hello".to_string(), 1);
239 /// assert_eq!(tree.get("hello"), Some(&1));
240 /// assert_eq!(tree.get("world"), None);
241 /// ```
242 pub fn get<Q>(&self, key: &Q) -> Option<&V>
243 where
244 K: Borrow<Q> + Ord,
245 Q: Ord + ?Sized,
246 {
247 self.layout
248 .find_node(key)
249 .map(|node| unsafe { node.value() })
250 }
251
252 /// Returns a mutable reference to the value associated with the given key, if it exists.
253 ///
254 /// The key may be any borrowed form of the tree's key type, but the ordering on the borrowed
255 /// form *must* match the ordering on the key type.
256 ///
257 /// # Examples
258 ///
259 /// ```
260 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
261 /// let mut tree = AugmentedRBTree::<String, i32, SubtreeSize>::new();
262 /// tree.insert("hello".to_string(), 1);
263 /// if let Some(v) = tree.get_mut("hello") {
264 /// *v = 42;
265 /// }
266 /// assert_eq!(tree.get("hello"), Some(&42));
267 /// ```
268 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
269 where
270 K: Borrow<Q> + Ord,
271 Q: Ord + ?Sized,
272 {
273 self.layout
274 .find_node(key)
275 .map(|node| unsafe { node.value_mut() })
276 }
277
278 /// Returns `true` if the tree contains a value for the given key.
279 ///
280 /// The key may be any borrowed form of the tree's key type, but the ordering on the borrowed
281 /// form *must* match the ordering on the key type.
282 ///
283 /// # Examples
284 ///
285 /// ```
286 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
287 /// let mut tree = AugmentedRBTree::<String, i32, SubtreeSize>::new();
288 /// tree.insert("hello".to_string(), 1);
289 /// assert!(tree.contains_key("hello"));
290 /// assert!(!tree.contains_key("world"));
291 /// ```
292 pub fn contains_key<Q>(&self, key: &Q) -> bool
293 where
294 K: Borrow<Q> + Ord,
295 Q: Ord + ?Sized,
296 {
297 self.layout.find_node(key).is_some()
298 }
299
300 /// Returns a reference to the key-value-stats tuple for the given key, if it exists.
301 ///
302 /// # Examples
303 ///
304 /// ```
305 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
306 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
307 /// tree.insert(1, "a");
308 /// assert_eq!(tree.get_key_value_stats(&1), Some((&1, &"a", &1)));
309 /// ```
310 pub fn get_key_value_stats<Q>(&self, key: &Q) -> Option<(&K, &V, &S)>
311 where
312 K: Borrow<Q> + Ord,
313 Q: Ord + ?Sized,
314 {
315 self.layout
316 .find_node(key)
317 .map(|node| unsafe { (node.key(), node.value(), node.stats()) })
318 }
319
320 /// Returns a reference to the key-value-stats tuple for the given key, if it exists.
321 ///
322 /// # Examples
323 ///
324 /// ```
325 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
326 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
327 /// tree.insert(1, "a");
328 /// assert_eq!(tree.get_value_stats(&1), Some((&"a", &1)));
329 /// ```
330 pub fn get_value_stats<Q>(&self, key: &Q) -> Option<(&V, &S)>
331 where
332 K: Borrow<Q> + Ord,
333 Q: Ord + ?Sized,
334 {
335 self.layout
336 .find_node(key)
337 .map(|node| unsafe { (node.value(), node.stats()) })
338 }
339
340 /// Returns a reference to the key-value tuple for the given key, if it exists.
341 ///
342 /// # Examples
343 ///
344 /// ```
345 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
346 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
347 /// tree.insert(1, "a");
348 /// assert_eq!(tree.get_key_value(&1), Some((&1, &"a")));
349 /// ```
350 pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
351 where
352 K: Borrow<Q> + Ord,
353 Q: Ord + ?Sized,
354 {
355 self.layout
356 .find_node(key)
357 .map(|node| unsafe { (node.key(), node.value()) })
358 }
359
360 /// Removes the node with the given key from the tree, if it exists, and returns its value.
361 /// If the key does not exist in the tree, returns `None`.
362 ///
363 /// The key may be any borrowed form of the tree's key type, but the ordering on the borrowed
364 /// form *must* match the ordering on the key type.
365 ///
366 /// # Examples
367 ///
368 /// ```
369 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
370 /// let mut tree = AugmentedRBTree::<String, i32, SubtreeSize>::new();
371 /// tree.insert("hello".to_string(), 1);
372 /// assert_eq!(tree.remove("hello"), Some(1));
373 /// assert_eq!(tree.remove("hello"), None);
374 /// ```
375 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
376 where
377 K: Borrow<Q> + Ord,
378 Q: Ord + ?Sized,
379 {
380 self.layout.find_node(key).map(|node| {
381 let (_key, value) = self.layout.delete_node(node);
382 value
383 })
384 }
385
386 /// Removes and returns the key-value pair for the given key if it exists.
387 ///
388 /// # Examples
389 ///
390 /// ```
391 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
392 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
393 /// tree.insert(1, "a");
394 /// assert_eq!(tree.remove_entry(&1), Some((1, "a")));
395 /// assert_eq!(tree.remove_entry(&1), None);
396 /// ```
397 pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
398 where
399 K: Borrow<Q> + Ord,
400 Q: Ord + ?Sized,
401 {
402 self.layout.find_node(key).map(|node| {
403 let (k, v) = self.layout.delete_node(node);
404 (k, v)
405 })
406 }
407
408 /// Returns a reference to the first (minimum) key-value-stats entry in the tree.
409 ///
410 /// # Examples
411 ///
412 /// ```
413 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
414 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
415 /// tree.insert(3, "c");
416 /// tree.insert(1, "a");
417 /// tree.insert(2, "b");
418 /// assert_eq!(tree.first_key_value_stats(), Some((&1, &"a", &1)));
419 /// ```
420 pub fn first_key_value_stats(&self) -> Option<(&K, &V, &S)>
421 where
422 K: Ord,
423 {
424 self.layout.root.map(|r| {
425 let node = r.leftmost();
426 unsafe { (node.key(), node.value(), node.stats()) }
427 })
428 }
429
430 /// Returns a reference to the last (maximum) key-value-stats entry in the tree.
431 ///
432 /// # Examples
433 ///
434 /// ```
435 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
436 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
437 /// tree.insert(3, "c");
438 /// tree.insert(1, "a");
439 /// tree.insert(2, "b");
440 /// assert_eq!(tree.last_key_value_stats(), Some((&3, &"c", &1)));
441 /// ```
442 pub fn last_key_value_stats(&self) -> Option<(&K, &V, &S)>
443 where
444 K: Ord,
445 {
446 self.layout.root.map(|r| {
447 let node = r.rightmost();
448 unsafe { (node.key(), node.value(), node.stats()) }
449 })
450 }
451
452 /// Removes and returns the first (minimum) key-value pair from the tree.
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
458 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
459 /// tree.insert(3, "c");
460 /// tree.insert(1, "a");
461 /// tree.insert(2, "b");
462 /// assert_eq!(tree.pop_first(), Some((1, "a")));
463 /// assert_eq!(tree.len(), 2);
464 /// ```
465 pub fn pop_first(&mut self) -> Option<(K, V)>
466 where
467 K: Ord,
468 {
469 #[allow(clippy::redundant_closure_for_method_calls)]
470 let node = self.layout.root.map(|r| r.leftmost())?;
471 let (k, v) = self.layout.delete_node(node);
472 Some((k, v))
473 }
474
475 /// Removes and returns the last (maximum) key-value pair from the tree.
476 ///
477 /// # Examples
478 ///
479 /// ```
480 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
481 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
482 /// tree.insert(3, "c");
483 /// tree.insert(1, "a");
484 /// tree.insert(2, "b");
485 /// assert_eq!(tree.pop_last(), Some((3, "c")));
486 /// assert_eq!(tree.len(), 2);
487 /// ```
488 pub fn pop_last(&mut self) -> Option<(K, V)>
489 where
490 K: Ord,
491 {
492 #[allow(clippy::redundant_closure_for_method_calls)]
493 let node = self.layout.root.map(|r| r.rightmost())?;
494 let (k, v) = self.layout.delete_node(node);
495 Some((k, v))
496 }
497
498 /// Returns the augmentation data (stats) stored at the root, covering the entire tree.
499 ///
500 /// For augmentations like sum or count, this gives the aggregate result over all elements.
501 /// Returns `None` if the tree is empty.
502 ///
503 /// # Examples
504 ///
505 /// ```
506 /// # use augmented_rbtree::{AugmentedRBTree, Augment};
507 /// # struct Sum;
508 /// # impl Augment<i32, i32> for Sum {
509 /// # type Stats = i32;
510 /// #
511 /// # fn compute(k: &i32, v: &i32, l: Option<(&i32, &i32, &i32)>, r: Option<(&i32, &i32, &i32)>) -> i32 {
512 /// # v + l.map(|x| *x.2).unwrap_or(0) + r.map(|x| *x.2).unwrap_or(0)
513 /// # }
514 /// # }
515 /// let mut tree = AugmentedRBTree::<i32, i32, Sum>::new();
516 /// tree.insert(1, 10);
517 /// tree.insert(2, 20);
518 /// tree.insert(3, 30);
519 /// assert_eq!(tree.root_stats(), Some(&60));
520 /// ```
521 pub fn root_stats(&self) -> Option<&S> {
522 self.layout.root.map(|r| unsafe { r.stats() })
523 }
524
525 /// Verify red-black tree structural invariants. Exposed for testing and debugging.
526 #[doc(hidden)]
527 pub fn verify_properties(&self) -> bool
528 where
529 K: Ord,
530 {
531 self.layout.verify_properties()
532 }
533
534 /// Verify augmentation correctness. Exposed for testing and debugging.
535 #[doc(hidden)]
536 pub fn verify_augmentation(&self) -> bool
537 where
538 K: Ord,
539 S: PartialEq,
540 {
541 self.layout.verify_augmentation()
542 }
543
544 /// Returns `true` if the tree contains no elements.
545 ///
546 /// # Examples
547 ///
548 /// ```
549 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
550 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
551 /// assert!(tree.is_empty());
552 /// tree.insert(1, "a");
553 /// assert!(!tree.is_empty());
554 /// ```
555 pub fn is_empty(&self) -> bool {
556 self.layout.len == 0
557 }
558
559 /// Clears the tree, removing all elements.
560 ///
561 /// # Examples
562 ///
563 /// ```
564 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
565 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
566 /// tree.insert(1, "a");
567 /// tree.clear();
568 /// assert!(tree.is_empty());
569 /// ```
570 pub fn clear(&mut self) {
571 self.layout.clear();
572 }
573 }
574
575 impl<K, V, S, P> Default for AugmentedRBTreeInt<K, V, S, Global, P>
576 where
577 P: TreePolicy<K = K, V = V, S = S>,
578 {
579 fn default() -> Self {
580 Self::new()
581 }
582 }
583
584 impl<K, V, S, A: Allocator, P> fmt::Debug for AugmentedRBTreeInt<K, V, S, A, P>
585 where
586 P: TreePolicy<K = K, V = V, S = S>,
587 K: fmt::Debug,
588 V: fmt::Debug,
589 {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591 f.debug_map()
592 .entries(self.iter().map(|(k, v, _)| (k, v)))
593 .finish()
594 }
595 }
596
597 impl<K, V, S, A, P> PartialEq for AugmentedRBTreeInt<K, V, S, A, P>
598 where
599 P: TreePolicy<K = K, V = V, S = S>,
600 K: PartialEq,
601 V: PartialEq,
602 A: Allocator,
603 {
604 fn eq(&self, other: &Self) -> bool {
605 if self.len() != other.len() {
606 return false;
607 }
608 self.iter()
609 .zip(other.iter())
610 .all(|((k1, v1, _), (k2, v2, _))| k1 == k2 && v1 == v2)
611 }
612 }
613
614 impl<K, V, S, A, P> Eq for AugmentedRBTreeInt<K, V, S, A, P>
615 where
616 P: TreePolicy<K = K, V = V, S = S>,
617 K: Eq,
618 V: Eq,
619 A: Allocator,
620 {
621 }
622
623 impl<K, V, S, A: Allocator, P> AugmentedRBTreeInt<K, V, S, A, P>
624 where
625 P: TreePolicy<K = K, V = V, S = S>,
626 {
627 /// Creates a new, empty `AugmentedRBTree` with the specified allocator.
628 #[inline]
629 pub fn new_in(alloc: A) -> Self {
630 Self {
631 layout: AugmentedRBTreeLayout::new_in(alloc),
632 }
633 }
634
635 /// Returns an iterator over the entries of the tree in sorted order by key.
636 ///
637 /// # Examples
638 ///
639 /// ```
640 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::Unit};
641 /// let mut tree = AugmentedRBTree::<i32, &str, Unit>::new();
642 /// tree.insert(2, "b");
643 /// tree.insert(1, "a");
644 /// tree.insert(3, "c");
645 ///
646 /// let entries: Vec<_> = tree.iter().collect();
647 /// assert_eq!(entries, vec![(&1, &"a", &()), (&2, &"b", &()), (&3, &"c", &())]);
648 /// ```
649 pub fn iter(&self) -> Iter<'_, K, V, S> {
650 Iter::new(self.layout.root, self.len())
651 }
652
653 /// Returns a mutable iterator over the entries of the tree in sorted order by key.
654 ///
655 /// # Examples
656 ///
657 /// ```
658 /// # use augmented_rbtree::{AugmentedRBTree, Unit};
659 /// let mut tree = AugmentedRBTree::<i32, i32, Unit>::new();
660 /// tree.insert(1, 10);
661 /// tree.insert(2, 20);
662 ///
663 /// for mut node_guard in tree.iter_mut() {
664 /// *node_guard.value_mut() *= 2;
665 /// }
666 ///
667 /// assert_eq!(tree.get(&1), Some(&20));
668 /// assert_eq!(tree.get(&2), Some(&40));
669 /// ```
670 pub fn iter_mut(&mut self) -> crate::iterators::IterMut<'_, K, V, S, P>
671 where
672 P: TreePolicy<K = K, V = V, S = S>,
673 {
674 IterMut::new(self.layout.root, self.len())
675 }
676
677 /// Returns an iterator over the keys of the tree in sorted order.
678 ///
679 /// # Examples
680 ///
681 /// ```
682 /// # use augmented_rbtree::{AugmentedRBTree, Unit};
683 /// let mut tree = AugmentedRBTree::<i32, &str, Unit>::new();
684 /// tree.insert(2, "b");
685 /// tree.insert(1, "a");
686 /// tree.insert(3, "c");
687 ///
688 /// let keys: Vec<_> = tree.keys().collect();
689 /// assert_eq!(keys, vec![&1, &2, &3]);
690 /// ```
691 pub fn keys(&self) -> Keys<'_, K, V, S> {
692 Keys::new(self.iter())
693 }
694
695 /// Returns an iterator over the values of the tree in order by key.
696 ///
697 /// # Examples
698 ///
699 /// ```
700 /// # use augmented_rbtree::{AugmentedRBTree, Unit};
701 /// let mut tree = AugmentedRBTree::<i32, &str, Unit>::new();
702 /// tree.insert(2, "b");
703 /// tree.insert(1, "a");
704 /// tree.insert(3, "c");
705 ///
706 /// let values: Vec<_> = tree.values().collect();
707 /// assert_eq!(values, vec![&"a", &"b", &"c"]);
708 /// ```
709 pub fn values(&self) -> Values<'_, K, V, S> {
710 Values::new(self.iter())
711 }
712
713 /// Returns a mutable iterator over the values of the tree in order by key.
714 ///
715 /// # Note
716 ///
717 /// Because this is an augmented tree, this iterator yields a smart guard [`NodeGuard`](crate::NodeGuard) rather than a raw reference. You must declare the loop variable as `mut`.
718 ///
719 /// # Examples
720 ///
721 /// ```
722 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
723 /// let mut tree = AugmentedRBTree::<i32, i32, SubtreeSize>::new();
724 /// tree.insert(1, 10);
725 /// tree.insert(2, 20);
726 ///
727 /// for mut v in tree.values_mut() {
728 /// *v *= 2;
729 /// }
730 ///
731 /// assert_eq!(tree.get(&1), Some(&20));
732 /// assert_eq!(tree.get(&2), Some(&40));
733 /// ```
734 pub fn values_mut(&mut self) -> crate::iterators::ValuesMut<'_, K, V, S, P>
735 where
736 P: TreePolicy<K = K, V = V, S = S>,
737 {
738 crate::iterators::ValuesMut::new(self.layout.root, self.len())
739 }
740
741 /// Returns an iterator over the stats of the tree in order by key.
742 ///
743 /// # Examples
744 ///
745 /// ```
746 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SumAugmentation};
747 /// let mut tree = AugmentedRBTree::<i32, i32, SumAugmentation>::new();
748 /// tree.insert(1, 1);
749 /// tree.insert(2, 2);
750 /// tree.insert(3, 3);
751 ///
752 /// let stats: Vec<_> = tree.stats().map(|x| *x).collect();
753 /// assert_eq!(stats, vec![1, 6, 3]);
754 /// ```
755 pub fn stats(&self) -> Stats<'_, K, V, S>
756 where
757 P: TreePolicy<K = K, V = V, S = S>,
758 {
759 Stats::new(self.iter())
760 }
761
762 /// Returns an iterator over a sub-range of entries in the tree.
763 ///
764 /// Constructs a double-ended iterator over a sub-range of entries in the tree.
765 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
766 /// yield elements from `min` (inclusive) to `max` (exclusive).
767 /// The range may also be entered as `(Bound<T>, Bound<T>)`.
768 ///
769 /// # Panics
770 ///
771 /// Panics if the range start is greater than the range end, or if the range start equals the
772 /// range end and both bounds are `Excluded`.
773 ///
774 /// # Examples
775 ///
776 /// ```
777 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
778 /// let mut tree = AugmentedRBTree::<i32, &str, SubtreeSize>::new();
779 /// for (k, v) in [(1, "a"), (2, "b"), (3, "c"), (4, "d"), (5, "e")] {
780 /// tree.insert(k, v);
781 /// }
782 ///
783 /// let range: Vec<_> = tree.range(2..=4).map(|(k, v, _)| (*k, *v)).collect();
784 /// assert_eq!(range, vec![(2, "b"), (3, "c"), (4, "d")]);
785 /// ```
786 pub fn range<'a, Q, R>(&'a self, range: R) -> Range<'a, K, V, S>
787 where
788 K: Borrow<Q> + Ord,
789 Q: Ord + ?Sized + 'a,
790 R: RangeBounds<Q>,
791 {
792 Range::new(&self.layout, range)
793 }
794
795 /// Returns a mutable iterator over a sub-range of entries in the tree.
796 ///
797 /// # Examples
798 ///
799 /// ```
800 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::SubtreeSize};
801 /// let mut tree = AugmentedRBTree::<i32, i32, SubtreeSize>::new();
802 /// for i in 1..=5 { tree.insert(i, i * 10); }
803 ///
804 /// for mut node_guard in tree.range_mut(2..=4) {
805 /// *node_guard.value_mut() += 1;
806 /// }
807 ///
808 /// assert_eq!(tree.get(&2), Some(&21));
809 /// assert_eq!(tree.get(&3), Some(&31));
810 /// assert_eq!(tree.get(&4), Some(&41));
811 /// assert_eq!(tree.get(&1), Some(&10)); // untouched
812 /// ```
813 pub fn range_mut<'a, Q, R>(&'a mut self, range: R) -> RangeMut<'a, K, V, S, P>
814 where
815 K: Borrow<Q> + Ord,
816 Q: Ord + ?Sized + 'a,
817 R: RangeBounds<Q>,
818 {
819 RangeMut::new(&self.layout, range)
820 }
821
822 /// Gets the given key's corresponding entry in the tree for in-place manipulation.
823 ///
824 /// # Examples
825 ///
826 /// ```
827 /// # use augmented_rbtree::{AugmentedRBTree, Entry, augmentations::SubtreeSize};
828 /// let mut tree = AugmentedRBTree::<&str, u32, SubtreeSize>::new();
829 ///
830 /// for word in ["hello", "world", "hello", "rust"] {
831 /// let count = tree.entry(word).or_insert(0);
832 /// *count += 1;
833 /// }
834 ///
835 /// assert_eq!(tree.get(&"hello"), Some(&2));
836 /// assert_eq!(tree.get(&"world"), Some(&1));
837 /// assert_eq!(tree.get(&"rust"), Some(&1));
838 /// ```
839 pub fn entry(&mut self, key: K) -> crate::entry::Entry<'_, K, V, S, A, P>
840 where
841 K: Ord,
842 {
843 Entry::new(self, key)
844 }
845
846 /// Resolves an abstract [`TreeLocation`] request into a physical node reference within the tree.
847 ///
848 /// This function serves as the central router for cursor initialization, mapping logical
849 /// positioning variants cleanly onto the underlying traversal and boundary methods:
850 ///
851 /// | `TreeLocation` Request | Underlying Method | Target Condition |
852 /// | :--- | :--- | :--- |
853 /// | `Root` | `self.layout.root` | Returns raw root node if present |
854 /// | `At(key)` | `find_node(key)` | Find node x for which x == key |
855 /// | `LowerBound(Included(key))` | `lower_bound(key)` | Find the smallest node x for which x >= key |
856 /// | `LowerBound(Excluded(key))` | `lower_bound_excluded(key)` | Find the smallest node x for which x > key |
857 /// | `LowerBound(Unbounded)` | `leftmost()` | Find the smallest node x in the tree |
858 /// | `UpperBound(Included(key))` | `floor(key)` | Find the largest node x for which x <= key |
859 /// | `UpperBound(Excluded(key))` | `floor_excluded(key)` | Find the largest node x for which x < key |
860 /// | `UpperBound(Unbounded)` | `rightmost()` | Find the largest node x in the tree |
861 /// | `Leftmost` | `leftmost()` | Find the smallest node x in the tree |
862 /// | `Rightmost` | `rightmost()` | Find the largest node x in the tree |
863 pub(crate) fn get_tree_location<Q>(
864 &self,
865 location: TreeLocation<&Q>,
866 ) -> Option<NodeRef<K, V, S>>
867 where
868 K: Borrow<Q> + Ord,
869 Q: Ord,
870 {
871 match location {
872 TreeLocation::Root => self.layout.root,
873 TreeLocation::At(key) => self.layout.find_node(key),
874
875 TreeLocation::LowerBound(bound) => match bound {
876 Bound::Included(key) => self.layout.lower_bound(key),
877 Bound::Excluded(key) => self.layout.lower_bound_excluded(key),
878 Bound::Unbounded => self.layout.leftmost(),
879 },
880 TreeLocation::UpperBound(bound) => match bound {
881 Bound::Included(key) => self.layout.floor(key),
882 Bound::Excluded(key) => self.layout.floor_excluded(key),
883 Bound::Unbounded => self.layout.rightmost(),
884 },
885 TreeLocation::Leftmost => self.layout.leftmost(),
886 TreeLocation::Rightmost => self.layout.rightmost(),
887 }
888 }
889
890 /// Visits each node in the tree and invokes the provided callback function with the current node's key, color, and its children's keys (if they exist).
891 pub fn visit_topology<F>(&self, mut visitor: F)
892 where
893 F: FnMut(&K, Color, Option<&K>, Option<&K>),
894 {
895 self.visit_nodes(|node, left, right| {
896 let key = unsafe { node.key() };
897 let color = node.color();
898
899 let left_key = if let Some(l) = left {
900 let l_ptr = l.ptr.as_ptr();
901 unsafe { Some(&(*l_ptr).key) }
902 } else {
903 None
904 };
905
906 let right_key = if let Some(r) = right {
907 let r_ptr = r.ptr.as_ptr();
908 unsafe { Some(&(*r_ptr).key) }
909 } else {
910 None
911 };
912 visitor(key, color, left_key, right_key);
913 });
914 }
915
916 fn visit_nodes<F>(&self, mut visitor: F)
917 where
918 F: FnMut(NodeRef<K, V, S>, Option<NodeRef<K, V, S>>, Option<NodeRef<K, V, S>>),
919 {
920 let mut current = self.layout.root;
921 let mut prev = None;
922
923 while let Some(current_ref) = current {
924 if prev == current_ref.parent() {
925 // Coming down from parent
926 let left = current_ref.left();
927 if let Some(left_ref) = left {
928 // try to visit left child
929 prev = Some(current_ref);
930 current = Some(left_ref);
931 continue;
932 }
933 // Visit current node
934 visitor(current_ref, current_ref.left(), current_ref.right());
935 if let Some(right_ref) = current_ref.right() {
936 // try to visit right child
937 prev = Some(current_ref);
938 current = Some(right_ref);
939 } else {
940 // nothing to be doen we need to go up
941 prev = Some(current_ref);
942 current = current_ref.parent();
943 }
944 } else if prev == current_ref.left() {
945 // Coming up from left child
946 // Visit current node
947 visitor(current_ref, current_ref.left(), current_ref.right());
948 if let Some(right_ref) = current_ref.right() {
949 // try to visit right child
950 prev = Some(current_ref);
951 current = Some(right_ref);
952 } else {
953 // nothing to be doen we need to go up
954 prev = Some(current_ref);
955 current = current_ref.parent();
956 }
957 } else if prev == current_ref.right() {
958 // Coming up from right child
959 prev = Some(current_ref);
960 current = current_ref.parent();
961 }
962 }
963 }
964
965 /// Attempts to clone the entire tree, returning a new tree with the same structure and values.
966 pub fn try_clone(&self) -> Result<Self, OutOfMemoryError>
967 where
968 K: Clone,
969 V: Clone,
970 A: Allocator + Clone,
971 {
972 let clone_root = self.layout.try_clone()?;
973 let node_allocator = self.layout.node_allocator.clone();
974 Ok(Self {
975 layout: AugmentedRBTreeLayout {
976 root: clone_root,
977 node_allocator,
978 len: self.len(),
979 _marker: PhantomData,
980 },
981 })
982 }
983
984 /// Initializes an immutable navigation cursor positioned at the specified location within the tree.
985 ///
986 /// The cursor's starting node is determined dynamically based on the requested variant:
987 ///
988 /// | `TreeLocation` Request | Target Condition |
989 /// | :--- | :--- |
990 /// | `Root` | Position at the root node of the tree |
991 /// | `At(key)` | Find node x for which x == key |
992 /// | `LowerBound(Included(key))` | Find the smallest node x for which x >= key |
993 /// | `LowerBound(Excluded(key))` | Find the smallest node x for which x > key |
994 /// | `LowerBound(Unbounded)` | Find the smallest node x in the tree |
995 /// | `UpperBound(Included(key))` | Find the largest node x for which x <= key |
996 /// | `UpperBound(Excluded(key))` | Find the largest node x for which x < key |
997 /// | `UpperBound(Unbounded)` | Find the largest node x in the tree |
998 /// | `Leftmost` | Find the smallest node x in the tree |
999 /// | `Rightmost` | Find the largest node x in the tree |
1000 pub fn nav_cursor<Q>(&self, location: TreeLocation<&Q>) -> NavCursor<'_, K, V, S>
1001 where
1002 K: Borrow<Q> + Ord,
1003 Q: Ord,
1004 {
1005 let node = self.get_tree_location(location);
1006 NavCursor::new(node)
1007 }
1008
1009 /// Initializes a mutable navigation cursor positioned at the specified location within the tree.
1010 ///
1011 /// This cursor allows safely mutating node values or removing the current node from the tree.
1012 /// The initial position rules are identical to the immutable variant:
1013 ///
1014 /// | `TreeLocation` Request | Target Condition |
1015 /// | :--- | :--- |
1016 /// | `Root` | Position at the root node of the tree |
1017 /// | `At(key)` | Find node x for which x == key |
1018 /// | `LowerBound(Included(key))` | Find the smallest node x for which x >= key |
1019 /// | `LowerBound(Excluded(key))` | Find the smallest node x for which x > key |
1020 /// | `LowerBound(Unbounded)` | Find the smallest node x in the tree |
1021 /// | `UpperBound(Included(key))` | Find the largest node x for which x <= key |
1022 /// | `UpperBound(Excluded(key))` | Find the largest node x for which x < key |
1023 /// | `UpperBound(Unbounded)` | Find the largest node x in the tree |
1024 /// | `Leftmost` | Find the smallest node x in the tree |
1025 /// | `Rightmost` | Find the largest node x in the tree |
1026 pub fn nav_cursor_mut<Q>(
1027 &mut self,
1028 location: TreeLocation<&Q>,
1029 ) -> NavCursorMut<'_, K, V, S, A, P>
1030 where
1031 K: Borrow<Q> + Ord,
1032 Q: Ord,
1033 {
1034 let node = self.get_tree_location(location);
1035 NavCursorMut::new(&mut self.layout, node)
1036 }
1037 }
1038
1039 impl<K, V, S, A: Allocator, P: TreePolicy<K = K, V = V, S = S>> IntoIterator
1040 for AugmentedRBTreeInt<K, V, S, A, P>
1041 {
1042 type Item = (K, V);
1043 type IntoIter = IntoIter<K, V, S, A, P>;
1044
1045 /// Consumes the tree and returns an iterator over its entries in sorted order by key.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```
1050 /// # use augmented_rbtree::{AugmentedRBTree, augmentations::Unit};
1051 /// let mut tree = AugmentedRBTree::<i32, &str, Unit>::new();
1052 /// tree.insert(2, "b");
1053 /// tree.insert(1, "a");
1054 /// tree.insert(3, "c");
1055 ///
1056 /// let entries: Vec<_> = tree.into_iter().collect();
1057 /// assert_eq!(entries, vec![(1, "a"), (2, "b"), (3, "c")]);
1058 /// ```
1059 fn into_iter(self) -> Self::IntoIter {
1060 let layout = unsafe { core::ptr::read(&raw const self.layout) };
1061 // do not run the destructor for self, since we are taking ownership of the allocator and root
1062 mem::forget(self);
1063 IntoIter::new(layout)
1064 }
1065 }
1066
1067 impl<'a, K, V, S, A: Allocator, P: TreePolicy<K = K, V = V, S = S>> IntoIterator
1068 for &'a AugmentedRBTreeInt<K, V, S, A, P>
1069 where
1070 P: TreePolicy<K = K, V = V, S = S>,
1071 {
1072 type Item = (&'a K, &'a V, &'a S);
1073 type IntoIter = Iter<'a, K, V, S>;
1074
1075 fn into_iter(self) -> Self::IntoIter {
1076 self.iter()
1077 }
1078 }
1079
1080 impl<'a, K, V, S, A: Allocator, P: TreePolicy<K = K, V = V, S = S>> IntoIterator
1081 for &'a mut AugmentedRBTreeInt<K, V, S, A, P>
1082 {
1083 type Item = NodeGuard<'a, K, V, S, P>;
1084 type IntoIter = IterMut<'a, K, V, S, P>;
1085
1086 fn into_iter(self) -> Self::IntoIter {
1087 self.iter_mut()
1088 }
1089 }
1090
1091 impl<K, V, S, A, P> FromIterator<(K, V)> for AugmentedRBTreeInt<K, V, S, A, P>
1092 where
1093 K: Ord,
1094 A: Allocator + Default,
1095 P: TreePolicy<K = K, V = V, S = S>,
1096 {
1097 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
1098 let mut tree = Self::new_in(A::default());
1099 for (k, v) in iter {
1100 tree.insert(k, v);
1101 }
1102 tree
1103 }
1104 }
1105
1106 impl<K, V, S, A: Allocator, P: TreePolicy<K = K, V = V, S = S>> Extend<(K, V)>
1107 for AugmentedRBTreeInt<K, V, S, A, P>
1108 where
1109 K: Ord,
1110 {
1111 fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
1112 for (k, v) in iter {
1113 self.insert(k, v);
1114 }
1115 }
1116 }
1117
1118 impl<K, V, S, A, P> Clone for AugmentedRBTreeInt<K, V, S, A, P>
1119 where
1120 K: Clone,
1121 V: Clone,
1122 A: Allocator + Clone,
1123 P: TreePolicy<K = K, V = V, S = S>,
1124 {
1125 fn clone(&self) -> Self {
1126 self.try_clone()
1127 .expect("Failed to clone AugmentedRBTree due to memory allocation failure")
1128 }
1129 }
1130}
1131
1132#[cfg(test)]
1133mod test {
1134
1135 use alloc::string::String;
1136
1137 use super::*;
1138 use crate::augmentations::Unit;
1139 #[test]
1140 fn covariance() {
1141 fn assert_covariance<'a, 'b: 'a>(
1142 x: AugmentedRBTree<&'b str, i32, Unit>,
1143 ) -> AugmentedRBTree<&'a str, i32, Unit> {
1144 x
1145 }
1146 let p = AugmentedRBTree::<&'static str, i32, Unit>::new();
1147 let _q = assert_covariance(p);
1148 }
1149
1150 #[test]
1151 fn test_strict_trait_exclusions() {
1152 type YesX = AugmentedRBTree<String, i32, Unit>;
1153
1154 static_assertions::assert_impl_all!(YesX: Send, Sync);
1155
1156 type NoX = AugmentedRBTree<*const u8, i32, Unit>;
1157 type NoY = AugmentedRBTree<i32, *const u8, Unit>;
1158
1159 #[cfg(not(under_rust_analyzer))]
1160 {
1161 static_assertions::assert_not_impl_all!(NoX: Send, Sync);
1162 static_assertions::assert_not_impl_all!(NoY: Send, Sync);
1163 }
1164 }
1165}