k/
iterator.rs

1/*
2  Copyright 2017 Takashi Ogura
3
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8      http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15*/
16//! Iterators to iterate descendants and ancestors
17use super::node::*;
18use nalgebra::RealField;
19use simba::scalar::SubsetOf;
20use std::collections::VecDeque;
21
22#[derive(Debug)]
23/// Iterator for parents
24pub struct Ancestors<T>
25where
26    T: RealField,
27{
28    parent: Option<Node<T>>,
29}
30
31impl<T> Ancestors<T>
32where
33    T: RealField,
34{
35    pub fn new(parent: Option<Node<T>>) -> Self {
36        Self { parent }
37    }
38}
39
40impl<T> Iterator for Ancestors<T>
41where
42    T: RealField + SubsetOf<f64>,
43{
44    type Item = Node<T>;
45    #[allow(clippy::question_mark)]
46    fn next(&mut self) -> Option<Node<T>> {
47        if self.parent.is_none() {
48            return None;
49        }
50        let next = self.parent.clone().unwrap();
51        self.parent = next.parent();
52        Some(next)
53    }
54}
55
56#[derive(Debug)]
57/// Iterator for children
58pub struct Descendants<T>
59where
60    T: RealField,
61{
62    queue: VecDeque<Node<T>>,
63}
64
65impl<T> Descendants<T>
66where
67    T: RealField,
68{
69    pub fn new(queue: Vec<Node<T>>) -> Self {
70        Self {
71            queue: queue.into(),
72        }
73    }
74}
75
76impl<T> Iterator for Descendants<T>
77where
78    T: RealField + SubsetOf<f64>,
79{
80    type Item = Node<T>;
81
82    fn next(&mut self) -> Option<Self::Item> {
83        let node = match self.queue.pop_front() {
84            Some(node) => node,
85            None => {
86                return None;
87            }
88        };
89
90        // procedure for prepending (no prepending function exists)
91        let mut new_queue: VecDeque<Node<T>> = node.children().clone().into();
92        new_queue.append(&mut (self.queue.clone()));
93        self.queue = new_queue;
94
95        Some(node)
96    }
97}