ABtree/A/
AVL.rs

1use std::cmp::Ordering;
2use std::collections::{HashMap, HashSet, VecDeque};
3use std::iter::FromIterator;
4use std::mem;
5use std::{marker::PhantomData, ptr::NonNull};
6
7/// An AVL balanced tree with owned nodes.
8pub 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
16/// Inner Node to store data
17struct 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    /// Take a boxed Node and return the key and value
39    #[inline]
40    fn into_element(n: Box<Node<K, V>>) -> (K, V) {
41        (n.key, n.value)
42    }
43
44    /// get parent node
45    #[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    /// set the parent node for a child node
52    #[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    /// unlink a child node and parent node
88    /// and set their linkage to None
89    #[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    /// Set the left node of a given node
119    #[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    /// set the right node of a given node
130    #[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    /// get the left node
141    #[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    /// get the right node
148    #[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    /// get the height of a node
155    #[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    /// set the height of a node
167    #[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    /// update the height of a node
175    /// and the heights of children must be updated
176    #[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    /// give a node compare with some K
191    #[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    /// Wrap a NonNull Node into a Box
197    #[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    /// For a given node this method will update all the heights of it's children using dynamic programming
205    /// and then update all the height of it's upper nodes
206    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        // updates all heights of lower nodes
210        '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                        //cur_node.is_some() && !adjs.is_empty() && (todo.is_empty() || !todo.is_empty()) {
248                        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                            // all child nodes have been updated
255                            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        // the input node and it's children have been updated
275        // now update it's upper nodes if possible
276        self._update_all_upper_nodes(node);
277    }
278
279    /// Because every time we call add or remove only one node will changed
280    /// so this method will assume the cur_node is the changed node
281    /// and it's height has been updated but not it's parent's height
282    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    /// Get balance factor
306    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    /// To tell if this tree is balanced
323    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    /// Right rotate for node `y`
349    ///        y                              x
350    ///       / \                           /   \
351    ///      x   T4                         z     y
352    ///     / \       - - - - - - - ->    / \   / \
353    ///    z   T3                       T1  T2 T3 T4
354    ///   / \
355    /// T1   T2
356    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 x and node y needs to update the height
369        Node::update_height(y);
370        Node::update_height(x);
371        self._update_all_upper_nodes(x);
372    }
373
374    /// Left ratate for node `y`
375    ///    y                             x
376    ///  /  \                          /   \
377    /// T1   x                        y     z
378    ///     / \   - - - - - - - ->   / \   / \
379    ///   T2  z                     T1 T2 T3 T4
380    ///      / \
381    ///     T3 T4
382    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 x and node y needs to update the height
395        Node::update_height(y);
396        Node::update_height(x);
397        self._update_all_upper_nodes(x);
398    }
399
400    /// Private method for adding a key-value pair
401    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                                // try to rebalance
441                                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    /// Pop out the minimun node
467    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    /// Return a boxed node after pop out the minimum node
475    fn _pop_min(&mut self) -> Option<Box<Node<K, V>>> {
476        Node::boxed_node(self._pop_min_loop())
477    }
478
479    /// Pop out the maximum node
480    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    /// Returnn a boxed node after pop out the maximum node
488    fn _pop_max(&mut self) -> Option<Box<Node<K, V>>> {
489        Node::boxed_node(self._pop_max_loop())
490    }
491
492    /// Given a ref key return the node
493    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    /// Given a ref key and return the mut ref of value
517    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    // When all heights have been updated call this methods to
523    // find the first unbalanced node from bottom to top
524    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    /// Rebalancing
542    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    /// Find maximun child node
550    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    /// Find minimum child node
563    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    /// remove node
576    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                    // cur_left is none and cur_right is none and cur_parent is none
648                    self.root_node = None;
649                    return cur_node;
650                }
651            }
652        }
653    }
654
655    // For the heights of nodes will be updated after rotate
656    // the rebalanceing methods is also heights updated after calling
657    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
683/// Drop
684impl<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                        // left is none and right is node
827                        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    /// Create an empty AVL tree
898    ///
899    /// # Examples
900    ///
901    /// ```
902    /// use ABtree::AVL;
903    ///
904    /// let t = AVL::<i32, i32>::new();
905    /// ```
906    pub fn new() -> Self {
907        AVL {
908            root_node: None,
909            len: 0,
910            _marker: PhantomData,
911        }
912    }
913
914    /// Adding key-value pair into the tree
915    ///
916    /// # Example
917    ///
918    /// ```
919    /// use ABtree::AVL;
920    /// let mut t = AVL::<i32, i32>::new();
921    /// t.add(2, 3);
922    /// assert_eq!(t.len(), 1);
923    /// ```
924    pub fn add(&mut self, k: K, v: V) {
925        self._add_loop(k, v);
926    }
927    /// Adding key-value pair into the tree
928    /// this method is an alias of method add
929    ///
930    /// # Example
931    ///
932    /// ```
933    /// use ABtree::AVL;
934    /// let mut t = AVL::<i32, i32>::new();
935    /// t.insert(2, 3);
936    /// assert_eq!(t.len(), 1);
937    /// ```
938    pub fn insert(&mut self, k: K, v: V) {
939        self._add_loop(k, v);
940    }
941
942    /// Setting a key-value pair
943    /// if the key exists it will update the value
944    /// otherwise it will insert the key-value into the tree
945    ///
946    /// # Example
947    ///
948    /// ```
949    /// use ABtree::AVL;
950    /// let mut t = AVL::<i32, i32>::new();
951    /// t.set(2, 2);
952    /// t.set(2, 31);
953    /// assert_eq!(t.get(&2), Some(&31));
954    /// ```
955    pub fn set(&mut self, k: K, v: V) {
956        self.add(k, v)
957    }
958
959    /// Get the length of this tree
960    ///
961    /// # Example
962    ///
963    /// ```
964    /// use ABtree::AVL;
965    /// let mut t = AVL::<i32, i32>::new();
966    /// t.insert(2, 2);
967    /// t.insert(3, 3);
968    /// assert_eq!(t.len(), 2);
969    /// ```
970    pub fn len(&self) -> usize {
971        self.len
972    }
973
974    /// Provides a forward iterator.
975    ///
976    /// # Examples
977    ///
978    /// ```
979    /// use ABtree::AVL;
980    ///
981    /// let mut t: AVL<u32, u32> = AVL::new();
982    ///
983    /// t.insert(0, 0);
984    /// t.insert(1, 1);
985    /// t.insert(2, 2);
986    ///
987    /// let mut iter = t.iter();
988    /// assert_eq!(iter.next(), Some((&0, &0)));
989    /// assert_eq!(iter.next(), Some((&1, &1)));
990    /// assert_eq!(iter.next_back(), Some((&2, &2)));
991    /// ```
992    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    /// Containment check
1007    ///
1008    /// # Example
1009    ///
1010    /// ```
1011    /// use ABtree::AVL;
1012    ///
1013    /// let mut t: AVL<u32, u32> = AVL::new();
1014    ///
1015    /// t.insert(0, 0);
1016    /// t.insert(1, 1);
1017    /// t.insert(2, 2);
1018    /// assert!(t.contains(&1));
1019    /// ```
1020    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    /// Removing key-value pair
1029    ///
1030    /// # Example
1031    ///
1032    /// ```
1033    /// use ABtree::AVL;
1034    ///
1035    /// let mut t: AVL<u32, u32> = AVL::new();
1036    ///
1037    /// t.insert(0, 0);
1038    /// t.insert(1, 1);
1039    /// t.insert(2, 2);
1040    /// assert_eq!(t.remove(&1), Some(1));
1041    /// assert_eq!(t.len(), 2);
1042    /// ```
1043    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    /// Peeking the root node
1049    ///
1050    /// # Example
1051    ///
1052    /// ```
1053    /// use ABtree::AVL;
1054    ///
1055    /// let mut t: AVL<u32, u32> = AVL::new();
1056    ///
1057    /// t.insert(0, 0);
1058    /// t.insert(1, 1);
1059    /// t.insert(2, 2);
1060    /// assert_eq!(t.peek_root(), Some((&1, &1)));
1061    /// ```
1062    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    /// To check if shis tree is balanced
1069    ///
1070    /// # Example
1071    ///
1072    /// ```
1073    /// use ABtree::AVL;
1074    ///
1075    /// let mut t: AVL<u32, u32> = AVL::new();
1076    ///
1077    /// t.insert(0, 0);
1078    /// t.insert(1, 1);
1079    /// t.insert(2, 2);
1080    /// assert_eq!(t.is_balanced_tree(), true);
1081    /// ```
1082    pub fn is_balanced_tree(&self) -> bool {
1083        self._is_balanced_tree()
1084    }
1085
1086    /// To check if shis tree is empty
1087    ///
1088    /// # Example
1089    ///
1090    /// ```
1091    /// use ABtree::AVL;
1092    ///
1093    /// let mut t: AVL<u32, u32> = AVL::new();
1094    ///
1095    /// t.insert(0, 0);
1096    /// t.insert(1, 1);
1097    /// t.insert(2, 2);
1098    /// assert_eq!(t.is_empty(), false);
1099    /// ```
1100    pub fn is_empty(&self) -> bool {
1101        self.len == 0
1102    }
1103
1104    /// Removes all elements from the AVL tree
1105    ///
1106    /// # Example
1107    ///
1108    /// ```
1109    /// use ABtree::AVL;
1110    ///
1111    /// let mut t: AVL<u32, u32> = AVL::new();
1112    ///
1113    /// t.insert(0, 0);
1114    /// t.insert(1, 1);
1115    /// t.insert(2, 2);
1116    /// t.clear();
1117    /// assert_eq!(t.len(), 0);
1118    /// ```
1119    pub fn clear(&mut self) {
1120        *self = Self::new();
1121    }
1122
1123    /// Get the value by key
1124    ///
1125    /// # Example
1126    ///
1127    /// ```
1128    /// use ABtree::AVL;
1129    ///
1130    /// let mut t: AVL<u32, u32> = AVL::new();
1131    ///
1132    /// t.insert(0, 0);
1133    /// t.insert(1, 1);
1134    /// t.insert(2, 2);
1135    /// assert_eq!(t.get(&1), Some(&1));
1136    /// ```
1137    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    /// Get a mutable reference of value by key
1147    ///
1148    /// # Example
1149    ///
1150    /// ```
1151    /// use ABtree::AVL;
1152    ///
1153    /// let mut t: AVL<u32, u32> = AVL::new();
1154    /// t.insert(0, 0);
1155    /// t.insert(1, 1);
1156    /// t.insert(2, 2);
1157    /// let v = t.get_mut(&2);
1158    /// v.map(|i| *i += 10);
1159    /// assert_eq!(t.get(&2), Some(&12))
1160    /// ```    
1161    pub fn get_mut(&mut self, k: &K) -> Option<&mut V> {
1162        self._get_mut(k)
1163    }
1164}