1use std::cmp::Ordering;
2use std::collections::{HashMap, HashSet, VecDeque};
3use std::iter::FromIterator;
4use std::mem;
5use std::{marker::PhantomData, ptr::NonNull};
6
7pub struct AVL<K: Ord, V> {
9 root_node: OpNode<K, V>,
10 len: usize,
11 _marker: PhantomData<Box<Node<K, V>>>,
12}
13
14type OpNode<K: Ord, V> = Option<NonNull<Node<K, V>>>;
15
16struct Node<K: Ord, V> {
18 key: K,
19 value: V,
20 parent_node: OpNode<K, V>,
21 left_node: OpNode<K, V>,
22 right_node: OpNode<K, V>,
23 height: isize,
24}
25
26impl<K: Ord, V> Node<K, V> {
27 fn new(k: K, v: V) -> Self {
28 Node {
29 key: k,
30 value: v,
31 parent_node: None,
32 left_node: None,
33 right_node: None,
34 height: 1,
35 }
36 }
37
38 #[inline]
40 fn into_element(n: Box<Node<K, V>>) -> (K, V) {
41 (n.key, n.value)
42 }
43
44 #[inline]
46 fn get_parent(node: OpNode<K, V>) -> OpNode<K, V> {
47 node.as_ref()
48 .and_then(|n| unsafe { (*n.as_ptr()).parent_node })
49 }
50
51 #[inline]
53 fn set_parent(child_node: OpNode<K, V>, parent_node: OpNode<K, V>) {
54 if parent_node.is_none() {
55 child_node.as_ref().map(|n| unsafe {
56 (*n.as_ptr()).parent_node = None;
57 });
58 return;
59 }
60 let parent_k = parent_node.as_ref().map(|p| unsafe { &(*p.as_ptr()).key });
61 let child_k = child_node.as_ref().map(|c| unsafe { &(*c.as_ptr()).key });
62 let ordering = parent_k.and_then(|pk| child_k.map(|ck| pk.cmp(ck)));
63
64 if let Some(o) = ordering {
65 match o {
66 Ordering::Equal => {}
67 Ordering::Less => {
68 parent_node.as_ref().map(|p| unsafe {
69 (*p.as_ptr()).right_node = child_node;
70 });
71 child_node.as_ref().map(|c| unsafe {
72 (*c.as_ptr()).parent_node = parent_node;
73 });
74 }
75 Ordering::Greater => {
76 parent_node.as_ref().map(|p| unsafe {
77 (*p.as_ptr()).left_node = child_node;
78 });
79 child_node.as_ref().map(|c| unsafe {
80 (*c.as_ptr()).parent_node = parent_node;
81 });
82 }
83 }
84 }
85 }
86
87 #[inline]
90 fn unlink(child_node: OpNode<K, V>, parent_node: OpNode<K, V>) {
91 let parent_k = parent_node.as_ref().map(|p| unsafe { &(*p.as_ptr()).key });
92 let child_k = child_node.as_ref().map(|c| unsafe { &(*c.as_ptr()).key });
93 let ordering = parent_k.and_then(|pk| child_k.map(|ck| pk.cmp(ck)));
94
95 if let Some(o) = ordering {
96 match o {
97 Ordering::Equal => {}
98 Ordering::Less => {
99 parent_node.as_ref().map(|p| unsafe {
100 (*p.as_ptr()).right_node = None;
101 });
102 child_node.as_ref().map(|c| unsafe {
103 (*c.as_ptr()).parent_node = None;
104 });
105 }
106 Ordering::Greater => {
107 parent_node.as_ref().map(|n| unsafe {
108 (*n.as_ptr()).left_node = None;
109 });
110 child_node.as_ref().map(|n| unsafe {
111 (*n.as_ptr()).parent_node = None;
112 });
113 }
114 }
115 }
116 }
117
118 #[inline]
120 fn set_left(cur_node: OpNode<K, V>, left_node: OpNode<K, V>) {
121 cur_node.as_ref().map(|cur| unsafe {
122 (*cur.as_ptr()).left_node = left_node;
123 });
124 left_node.as_ref().map(|l| unsafe {
125 (*l.as_ptr()).parent_node = cur_node;
126 });
127 }
128
129 #[inline]
131 fn set_right(cur_node: OpNode<K, V>, right_node: OpNode<K, V>) {
132 cur_node.as_ref().map(|cur| unsafe {
133 (*cur.as_ptr()).right_node = right_node;
134 });
135 right_node.as_ref().map(|l| unsafe {
136 (*l.as_ptr()).parent_node = cur_node;
137 });
138 }
139
140 #[inline]
142 fn get_left(node: OpNode<K, V>) -> OpNode<K, V> {
143 node.as_ref()
144 .and_then(|n| unsafe { (*n.as_ptr()).left_node })
145 }
146
147 #[inline]
149 fn get_right(node: OpNode<K, V>) -> OpNode<K, V> {
150 node.as_ref()
151 .and_then(|n| unsafe { (*n.as_ptr()).right_node })
152 }
153
154 #[inline]
156 fn get_height(node: OpNode<K, V>) -> isize {
157 if node.is_none() {
158 0
159 } else {
160 node.as_ref()
161 .map(|n| unsafe { (*n.as_ptr()).height })
162 .unwrap()
163 }
164 }
165
166 #[inline]
168 fn set_height(node: OpNode<K, V>, h: isize) {
169 node.as_ref().map(|n| unsafe {
170 (*n.as_ptr()).height = h;
171 });
172 }
173
174 #[inline]
177 fn update_height(node: OpNode<K, V>) {
178 let l_height = Node::get_height(Node::get_left(node));
179 let r_height = Node::get_height(Node::get_right(node));
180 let new_height = if l_height < r_height {
181 r_height + 1
182 } else {
183 l_height + 1
184 };
185 node.as_ref().map(|n| unsafe {
186 (*n.as_ptr()).height = new_height;
187 });
188 }
189
190 #[inline]
192 fn compare_key(node: OpNode<K, V>, k: &K) -> Option<Ordering> {
193 node.as_ref().map(|n| unsafe { (*n.as_ptr()).key.cmp(k) })
194 }
195
196 #[inline]
198 fn boxed_node(node: OpNode<K, V>) -> Option<Box<Node<K, V>>> {
199 node.map(|n| unsafe { Box::from_raw(n.as_ptr()) })
200 }
201}
202
203impl<K: Ord, V> AVL<K, V> {
204 fn _update_nodes_height_down_up(&mut self, node: OpNode<K, V>) {
207 let mut todo = vec![node];
208 let mut updated = HashMap::<OpNode<K, V>, isize>::new();
209 'outer: loop {
211 let c = todo.pop();
212 match c {
213 None => {
214 if todo.is_empty() {
215 break 'outer;
216 } else {
217 continue 'outer;
218 }
219 }
220 Some(cur_node) => {
221 let cur_left = Node::get_left(cur_node);
222 let cur_right = Node::get_right(cur_node);
223 let adjs: Vec<OpNode<K, V>> = vec![cur_left, cur_right]
224 .into_iter()
225 .filter(|n| n.is_some())
226 .collect();
227
228 if cur_node.is_none() && adjs.is_empty() && todo.is_empty() {
229 break 'outer;
230 } else if cur_node.is_none() && !adjs.is_empty() && todo.is_empty() {
231 break 'outer;
232 } else if cur_node.is_none() && adjs.is_empty() && !todo.is_empty() {
233 continue 'outer;
234 } else if cur_node.is_none() && !adjs.is_empty() && !todo.is_empty() {
235 adjs.into_iter().for_each(|n| {
236 todo.push(n);
237 });
238 continue 'outer;
239 } else if cur_node.is_some() && adjs.is_empty() && todo.is_empty() {
240 Node::set_height(cur_node, 1);
241 break 'outer;
242 } else if cur_node.is_some() && adjs.is_empty() && !todo.is_empty() {
243 Node::set_height(cur_node, 1);
244 updated.insert(cur_node, 1);
245 continue 'outer;
246 } else {
247 let adjs_not_seen: Vec<OpNode<K, V>> = adjs
249 .iter()
250 .map(|n| *n)
251 .filter(|n| !updated.contains_key(n))
252 .collect();
253 if adjs_not_seen.is_empty() {
254 let new_height =
256 (*adjs.iter().flat_map(|n| updated.get(n)).max().unwrap()) + 1;
257
258 cur_node.as_ref().map(|cur| unsafe {
259 (*cur.as_ptr()).height = new_height;
260 });
261 updated.insert(cur_node, new_height);
262 continue 'outer;
263 } else {
264 todo.push(cur_node);
265 adjs_not_seen.into_iter().for_each(|n| {
266 todo.push(n);
267 });
268 continue 'outer;
269 }
270 }
271 }
272 }
273 }
274 self._update_all_upper_nodes(node);
277 }
278
279 fn _update_all_upper_nodes(&mut self, mut cur_node: OpNode<K, V>) {
283 loop {
284 let cur_parent = Node::get_parent(cur_node);
285 if cur_parent.is_none() {
286 break;
287 }
288 let parnet_l_height = Node::get_height(Node::get_left(cur_parent));
289 let parnet_r_height = Node::get_height(Node::get_right(cur_parent));
290 let new_p_height = if parnet_l_height < parnet_r_height {
291 parnet_r_height + 1
292 } else {
293 parnet_l_height + 1
294 };
295 let old_p_height = Node::get_height(cur_parent);
296 if new_p_height == old_p_height {
297 break;
298 }
299 Node::set_height(cur_parent, new_p_height);
300 cur_node = Node::get_parent(cur_parent);
301 continue;
302 }
303 }
304
305 fn _get_balance_factor(&self, node: OpNode<K, V>) -> isize {
307 if node.is_none() {
308 0
309 } else {
310 let left_height = Node::get_height(Node::get_left(node));
311 let right_height = Node::get_height(Node::get_right(node));
312
313 match (left_height, right_height) {
314 (0, 0) => 0,
315 (l, 0) => l,
316 (0, r) => -r,
317 (l, r) => l - r,
318 }
319 }
320 }
321
322 fn _is_balanced_tree(&self) -> bool {
324 let mut queue = VecDeque::new();
325 queue.push_back(self.root_node);
326 loop {
327 let c = queue.pop_front();
328 match c {
329 None => {
330 break true;
331 }
332 Some(cur_node) => {
333 if self._get_balance_factor(cur_node).abs() > 1 {
334 break false;
335 }
336 let adjs = vec![Node::get_left(cur_node), Node::get_right(cur_node)];
337 adjs.into_iter().for_each(|n| {
338 if n.is_some() {
339 queue.push_back(n);
340 }
341 });
342 continue;
343 }
344 }
345 }
346 }
347
348 fn _right_rotate(&mut self, y: OpNode<K, V>) {
357 let y_parent = Node::get_parent(y);
358 let x = Node::get_left(y);
359 let t3 = Node::get_right(x);
360
361 Node::set_parent(t3, y);
362 Node::set_parent(y, x);
363 Node::set_parent(x, y_parent);
364
365 if y_parent.is_none() {
366 self.root_node = x;
367 }
368 Node::update_height(y);
370 Node::update_height(x);
371 self._update_all_upper_nodes(x);
372 }
373
374 fn _left_rotate(&mut self, y: OpNode<K, V>) {
383 let y_parent = Node::get_parent(y);
384 let x = Node::get_right(y);
385 let t2 = Node::get_left(x);
386
387 Node::set_right(y, t2);
388 Node::set_left(x, y);
389 Node::set_parent(x, y_parent);
390
391 if y_parent.is_none() {
392 self.root_node = x;
393 }
394 Node::update_height(y);
396 Node::update_height(x);
397 self._update_all_upper_nodes(x);
398 }
399
400 fn _add_loop(&mut self, k: K, v: V) {
402 if self.root_node.is_none() {
403 let new_node = Box::new(Node::new(k, v));
404 let new_raw = NonNull::new(Box::into_raw(new_node));
405 self.len += 1;
406 self.root_node = new_raw;
407 return;
408 }
409 let mut todo = vec![self.root_node];
410 'outer: loop {
411 let c = todo.pop();
412 match c {
413 None => {
414 break 'outer;
415 }
416 Some(cur_node) => {
417 let cur_left = Node::get_left(cur_node);
418 let cur_right = Node::get_right(cur_node);
419 let cmp = Node::compare_key(cur_node, &k);
420
421 match cmp {
422 None => {
423 break 'outer;
424 }
425 Some(Ordering::Equal) => {
426 cur_node.as_ref().map(|cur| unsafe {
427 (*cur.as_ptr()).value = v;
428 });
429 break 'outer;
430 }
431 Some(Ordering::Greater) => {
432 if cur_left.is_some() {
433 todo.push(cur_left);
434 continue 'outer;
435 } else {
436 self.len += 1;
437 let new_node = Box::new(Node::new(k, v));
438 let new_raw = NonNull::new(Box::into_raw(new_node));
439 Node::set_left(cur_node, new_raw);
440 self._update_nodes_height_down_up(self.root_node);
442 self._try_to_rebalancing(new_raw);
443 break 'outer;
444 }
445 }
446 Some(Ordering::Less) => {
447 if cur_right.is_some() {
448 todo.push(cur_right);
449 continue 'outer;
450 } else {
451 self.len += 1;
452 let new_node = Box::new(Node::new(k, v));
453 let new_raw = NonNull::new(Box::into_raw(new_node));
454 Node::set_right(cur_node, new_raw);
455 self._update_nodes_height_down_up(self.root_node);
456 self._try_to_rebalancing(new_raw);
457 break 'outer;
458 }
459 }
460 }
461 }
462 }
463 }
464 }
465
466 fn _pop_min_loop(&mut self) -> OpNode<K, V> {
468 let cur_min = self._find_min_child(self.root_node);
469 cur_min
470 .as_ref()
471 .and_then(|n| unsafe { self._remove_node(&(*n.as_ptr()).key) })
472 }
473
474 fn _pop_min(&mut self) -> Option<Box<Node<K, V>>> {
476 Node::boxed_node(self._pop_min_loop())
477 }
478
479 fn _pop_max_loop(&mut self) -> OpNode<K, V> {
481 let cur_max = self._find_max_child(self.root_node);
482 cur_max
483 .as_ref()
484 .and_then(|n| unsafe { self._remove_node(&(*n.as_ptr()).key) })
485 }
486
487 fn _pop_max(&mut self) -> Option<Box<Node<K, V>>> {
489 Node::boxed_node(self._pop_max_loop())
490 }
491
492 fn _get_node(&self, k: &K) -> OpNode<K, V> {
494 let mut cur_node = self.root_node;
495 loop {
496 let cmp = Node::compare_key(cur_node, k);
497 match cmp {
498 None => {
499 break None;
500 }
501 Some(Ordering::Equal) => {
502 break cur_node;
503 }
504 Some(Ordering::Greater) => {
505 cur_node = Node::get_left(cur_node);
506 continue;
507 }
508 Some(Ordering::Less) => {
509 cur_node = Node::get_right(cur_node);
510 continue;
511 }
512 }
513 }
514 }
515
516 fn _get_mut(&mut self, k: &K) -> Option<&mut V> {
518 self._get_node(k)
519 .map(|n| unsafe { &mut (*n.as_ptr()).value })
520 }
521
522 fn _get_unbalanced_node(&mut self, mut cur_node: OpNode<K, V>) -> OpNode<K, V> {
525 loop {
526 let cur_parent = Node::get_parent(cur_node);
527 let cur_b_factor = self._get_balance_factor(cur_node);
528 if cur_b_factor.abs() > 1 {
529 break cur_node;
530 } else {
531 if cur_parent.is_some() {
532 cur_node = cur_parent;
533 continue;
534 } else {
535 break None;
536 }
537 }
538 }
539 }
540
541 fn _try_to_rebalancing(&mut self, cur_node: OpNode<K, V>) {
543 let unbalanced = self._get_unbalanced_node(cur_node);
544 if unbalanced.is_some() {
545 self._rebalancing(unbalanced);
546 }
547 }
548
549 fn _find_max_child(&self, mut cur_node: OpNode<K, V>) -> OpNode<K, V> {
551 loop {
552 let cur_right = Node::get_right(cur_node);
553 if cur_right.is_some() {
554 cur_node = cur_right;
555 continue;
556 } else {
557 break cur_node;
558 }
559 }
560 }
561
562 fn _find_min_child(&self, mut cur_node: OpNode<K, V>) -> OpNode<K, V> {
564 loop {
565 let cur_left = Node::get_left(cur_node);
566 if cur_left.is_some() {
567 cur_node = cur_left;
568 continue;
569 } else {
570 break cur_node;
571 }
572 }
573 }
574
575 fn _remove_node(&mut self, k: &K) -> OpNode<K, V> {
577 let target_node = self._get_node(k);
578 match target_node {
579 None => None,
580 cur_node @ Some(_) => {
581 self.len -= 1;
582 let cur_parent = Node::get_parent(cur_node);
583 let cur_left = Node::get_left(cur_node);
584 let cur_right = Node::get_right(cur_node);
585
586 if cur_left.is_some() && cur_right.is_some() && cur_parent.is_some() {
587 let cur_left_max = self._find_max_child(cur_left);
588 Node::unlink(cur_left_max, Node::get_parent(cur_left_max));
589 Node::set_parent(cur_left_max, cur_parent);
590 Node::set_right(cur_left_max, cur_right);
591 if !cur_left_max.eq(&cur_left) {
592 Node::set_left(cur_left_max, cur_left);
593 }
594 self._update_nodes_height_down_up(cur_left_max);
595 self._try_to_rebalancing(cur_left_max);
596 return cur_node;
597 } else if cur_left.is_some() && cur_right.is_some() && cur_parent.is_none() {
598 let cur_left_max = self._find_max_child(cur_left);
599 Node::unlink(cur_left_max, Node::get_parent(cur_left_max));
600 self.root_node = cur_left_max;
601 Node::set_parent(cur_left_max, None);
602 Node::set_right(cur_left_max, cur_right);
603 if !cur_left_max.eq(&cur_left) {
604 Node::set_left(cur_left_max, cur_left);
605 }
606 self._update_nodes_height_down_up(cur_left_max);
607 self._try_to_rebalancing(cur_left_max);
608 return cur_node;
609 } else if cur_left.is_some() && cur_right.is_none() && cur_parent.is_some() {
610 let cur_left_max = self._find_max_child(cur_left);
611 Node::unlink(cur_left_max, Node::get_parent(cur_left_max));
612 Node::set_parent(cur_left_max, cur_parent);
613 if !cur_left_max.eq(&cur_left) {
614 Node::set_left(cur_left_max, cur_left);
615 }
616 self._update_nodes_height_down_up(cur_left_max);
617 self._try_to_rebalancing(cur_left_max);
618 return cur_node;
619 } else if cur_left.is_some() && cur_right.is_none() && cur_parent.is_none() {
620 let cur_left_max = self._find_max_child(cur_left);
621 Node::unlink(cur_left_max, Node::get_parent(cur_left_max));
622 self.root_node = cur_left_max;
623 Node::set_parent(cur_left_max, None);
624 if !cur_left_max.eq(&cur_left) {
625 Node::set_left(cur_left_max, cur_left);
626 }
627 self._update_nodes_height_down_up(cur_left_max);
628 self._try_to_rebalancing(cur_left_max);
629 return cur_node;
630 } else if cur_left.is_none() && cur_right.is_some() && cur_parent.is_some() {
631 Node::set_parent(cur_right, cur_parent);
632 self._update_nodes_height_down_up(cur_right);
633 self._try_to_rebalancing(cur_right);
634 return cur_node;
635 } else if cur_left.is_none() && cur_right.is_some() && cur_parent.is_none() {
636 Node::set_parent(cur_right, None);
637 self.root_node = cur_right;
638 self._update_nodes_height_down_up(cur_right);
639 self._try_to_rebalancing(cur_right);
640 return cur_node;
641 } else if cur_left.is_none() && cur_right.is_none() && cur_parent.is_some() {
642 Node::unlink(cur_node, cur_parent);
643 self._update_nodes_height_down_up(cur_parent);
644 self._try_to_rebalancing(cur_parent);
645 return cur_node;
646 } else {
647 self.root_node = None;
649 return cur_node;
650 }
651 }
652 }
653 }
654
655 fn _rebalancing(&mut self, cur_node: OpNode<K, V>) {
658 let cur_left = Node::get_left(cur_node);
659 let cur_right = Node::get_right(cur_node);
660 let cur_b_factor = self._get_balance_factor(cur_node);
661 let cur_left_b_factor = self._get_balance_factor(cur_left);
662 let cur_right_b_factor = self._get_balance_factor(cur_right);
663 if cur_b_factor > 1 && cur_left_b_factor >= 0 {
664 self._right_rotate(cur_node);
665 }
666
667 if cur_b_factor < -1 && cur_right_b_factor <= 0 {
668 self._left_rotate(cur_node);
669 }
670
671 if cur_b_factor > 1 && cur_left_b_factor < 0 {
672 self._left_rotate(cur_left);
673 self._right_rotate(cur_node);
674 }
675
676 if cur_b_factor < -1 && cur_right_b_factor > 0 {
677 self._right_rotate(cur_right);
678 self._left_rotate(cur_node);
679 }
680 }
681}
682
683impl<K: Ord, V> Drop for AVL<K, V> {
685 fn drop(&mut self) {
686 struct DropGuard<'a, K: Ord, V>(&'a mut AVL<K, V>);
687 impl<'a, K: Ord, V> Drop for DropGuard<'a, K, V> {
688 fn drop(&mut self) {
689 while self.0._pop_min().is_some() {}
690 }
691 }
692
693 while let Some(b) = self._pop_min() {
694 let guard = DropGuard(self);
695 drop(b);
696 mem::forget(guard);
697 }
698 }
699}
700
701pub struct IntoIter<K: Ord, V>(AVL<K, V>);
702
703impl<K: Ord, V> Iterator for IntoIter<K, V> {
704 type Item = (K, V);
705
706 fn next(&mut self) -> Option<Self::Item> {
707 self.0._pop_min().map(|n| Node::into_element(n))
708 }
709}
710
711impl<K: Ord, V> DoubleEndedIterator for IntoIter<K, V> {
712 fn next_back(&mut self) -> Option<Self::Item> {
713 self.0._pop_max().map(|n| Node::into_element(n))
714 }
715}
716
717impl<K: Ord, V> Drop for IntoIter<K, V> {
718 fn drop(&mut self) {
719 struct DropGuard<'a, K: Ord, V>(&'a mut IntoIter<K, V>);
720
721 impl<'a, K: Ord, V> Drop for DropGuard<'a, K, V> {
722 fn drop(&mut self) {
723 while self.0.next().is_some() {}
724 }
725 }
726
727 while let Some(d) = self.next() {
728 let guard = DropGuard(self);
729 drop(d);
730 mem::forget(guard);
731 }
732 }
733}
734
735pub struct Iter<'a, K: Ord, V> {
736 next_nodes: Vec<OpNode<K, V>>,
737 seen: HashSet<NonNull<Node<K, V>>>,
738 next_back_nodes: Vec<OpNode<K, V>>,
739 seen_back: HashSet<NonNull<Node<K, V>>>,
740 _marker: PhantomData<&'a Node<K, V>>,
741}
742
743impl<'a, K: Ord, V> Iter<'a, K, V> {
744 fn next_ascending(&mut self) -> OpNode<K, V> {
745 loop {
746 let n = self.next_nodes.pop();
747 match n {
748 None => {
749 if self.next_nodes.len() == 0 {
750 break None;
751 } else {
752 continue;
753 }
754 }
755 Some(node) => unsafe {
756 let left = node
757 .as_ref()
758 .and_then(|n| (*n.as_ptr()).left_node)
759 .filter(|n| !self.seen.contains(n));
760 let right = node
761 .as_ref()
762 .and_then(|n| (*n.as_ptr()).right_node)
763 .filter(|n| !self.seen.contains(n));
764
765 if left.is_some() && right.is_some() {
766 self.next_nodes.push(node);
767 self.next_nodes.push(left);
768 continue;
769 } else if left.is_some() && right.is_none() {
770 self.next_nodes.push(node);
771 self.next_nodes.push(left);
772 continue;
773 } else if left.is_none() && right.is_some() {
774 self.next_nodes.push(right);
775 node.map(|n| {
776 self.seen.insert(n);
777 });
778 break node;
779 } else {
780 node.map(|n| {
781 self.seen.insert(n);
782 });
783 break node;
784 }
785 },
786 }
787 }
788 }
789
790 fn next_descending(&mut self) -> OpNode<K, V> {
791 loop {
792 let n = self.next_back_nodes.pop();
793 match n {
794 None => {
795 if self.next_back_nodes.len() == 0 {
796 break None;
797 } else {
798 continue;
799 }
800 }
801 Some(node) => unsafe {
802 let left = node
803 .as_ref()
804 .and_then(|n| (*n.as_ptr()).left_node)
805 .filter(|n| !self.seen_back.contains(n));
806 let right = node
807 .as_ref()
808 .and_then(|n| (*n.as_ptr()).right_node)
809 .filter(|n| !self.seen_back.contains(n));
810
811 if left.is_some() && right.is_some() {
812 self.next_back_nodes.push(node);
813 self.next_back_nodes.push(right);
814 continue;
815 } else if left.is_some() && right.is_none() {
816 self.next_back_nodes.push(left);
817 node.map(|n| {
818 self.seen_back.insert(n);
819 });
820 break node;
821 } else if left.is_none() && right.is_some() {
822 self.next_back_nodes.push(node);
823 self.next_back_nodes.push(right);
824 continue;
825 } else {
826 node.map(|n| {
828 self.seen.insert(n);
829 });
830 break node;
831 }
832 },
833 }
834 }
835 }
836}
837
838impl<'a, K: Ord, V> Iterator for Iter<'a, K, V> {
839 type Item = (&'a K, &'a V);
840 fn next(&mut self) -> Option<Self::Item> {
841 self.next_ascending()
842 .as_ref()
843 .map(|n| unsafe { (&(*n.as_ptr()).key, &(*n.as_ptr()).value) })
844 }
845}
846
847impl<'a, K: Ord, V> DoubleEndedIterator for Iter<'a, K, V> {
848 fn next_back(&mut self) -> Option<Self::Item> {
849 self.next_descending()
850 .as_ref()
851 .map(|n| unsafe { (&(*n.as_ptr()).key, &(*n.as_ptr()).value) })
852 }
853}
854
855impl<K: Ord, V> FromIterator<(K, V)> for AVL<K, V> {
856 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
857 let inputs: Vec<_> = iter.into_iter().collect();
858 if inputs.is_empty() {
859 return AVL::<K, V>::new();
860 }
861 let mut out = AVL::<K, V>::new();
862 for (k, v) in inputs {
863 out.add(k, v);
864 }
865 out
866 }
867}
868
869impl<K: Ord, V> IntoIterator for AVL<K, V> {
870 type Item = (K, V);
871 type IntoIter = IntoIter<K, V>;
872
873 fn into_iter(self) -> Self::IntoIter {
874 IntoIter(self)
875 }
876}
877
878impl<K: Ord + Copy, V: Copy> Clone for AVL<K, V> {
879 fn clone(&self) -> Self {
880 let mut out = AVL::<K, V>::new();
881 for (k, v) in self.iter() {
882 out.add(*k, *v);
883 }
884 out
885 }
886}
887
888unsafe impl<K: Ord + Send, V: Send> Send for AVL<K, V> {}
889
890unsafe impl<K: Ord + Sync, V: Sync> Sync for AVL<K, V> {}
891
892unsafe impl<K: Ord + Send, V: Send> Send for Iter<'_, K, V> {}
893
894unsafe impl<K: Ord + Sync, V: Sync> Sync for Iter<'_, K, V> {}
895
896impl<K: Ord, V> AVL<K, V> {
897 pub fn new() -> Self {
907 AVL {
908 root_node: None,
909 len: 0,
910 _marker: PhantomData,
911 }
912 }
913
914 pub fn add(&mut self, k: K, v: V) {
925 self._add_loop(k, v);
926 }
927 pub fn insert(&mut self, k: K, v: V) {
939 self._add_loop(k, v);
940 }
941
942 pub fn set(&mut self, k: K, v: V) {
956 self.add(k, v)
957 }
958
959 pub fn len(&self) -> usize {
971 self.len
972 }
973
974 pub fn iter<'a>(&'a self) -> Iter<'a, K, V> {
993 let nodes = vec![self.root_node];
994 let seen = HashSet::<NonNull<Node<K, V>>>::new();
995 let nodes_back = vec![self.root_node];
996 let seen_back = HashSet::<NonNull<Node<K, V>>>::new();
997 Iter {
998 next_nodes: nodes,
999 seen: seen,
1000 next_back_nodes: nodes_back,
1001 seen_back: seen_back,
1002 _marker: PhantomData,
1003 }
1004 }
1005
1006 pub fn contains(&self, k: &K) -> bool {
1021 if self.is_empty() {
1022 false
1023 } else {
1024 self.iter().any(|n| n.0.eq(k))
1025 }
1026 }
1027
1028 pub fn remove(&mut self, k: &K) -> Option<V> {
1044 let out = self._remove_node(k);
1045 Node::boxed_node(out).map(|n| n.value)
1046 }
1047
1048 pub fn peek_root<'a>(&'a self) -> Option<(&'a K, &'a V)> {
1063 self.root_node
1064 .as_ref()
1065 .map(|n| unsafe { (&(*n.as_ptr()).key, &(*n.as_ptr()).value) })
1066 }
1067
1068 pub fn is_balanced_tree(&self) -> bool {
1083 self._is_balanced_tree()
1084 }
1085
1086 pub fn is_empty(&self) -> bool {
1101 self.len == 0
1102 }
1103
1104 pub fn clear(&mut self) {
1120 *self = Self::new();
1121 }
1122
1123 pub fn get(&self, k: &K) -> Option<&V> {
1138 let mut outs: Vec<_> = self.iter().filter(|n| n.0.eq(k)).collect();
1139 if outs.len() == 0 {
1140 None
1141 } else {
1142 outs.pop().map(|o| o.1)
1143 }
1144 }
1145
1146 pub fn get_mut(&mut self, k: &K) -> Option<&mut V> {
1162 self._get_mut(k)
1163 }
1164}