summaryrefslogtreecommitdiffstats
path: root/lib/etc/libimagutil/src/tree.rs
blob: c528452295bf15ddb8203ce8b9e4980813ee6f3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::iter::FromIterator;

use failure::Fallible as Result;

pub struct Tree<T: Sized> {
    elements: Vec<TreeElement<T>>
}

impl<T: Sized> Tree<T> {

    pub fn new() -> Self {
        Tree { elements: Vec::new() }
    }

    pub fn with_capacity(cap: usize) -> Self {
        Tree { elements: Vec::with_capacity(cap) }
    }

    pub fn add_node(&mut self, t: T) {
        self.elements.push(TreeElement {
            parent_idx: None,
            childs_indexes: Vec::new(),
            element: t
        });
    }

    pub fn build_tree<ID, IG>(&mut self, ig: IG) -> TreeBuilder<T, ID, IG>
        where ID: PartialEq + Sized,
              IG: IdGetter<T, ID = ID>
    {
        TreeBuilder(self, ig)
    }
}

impl<A> FromIterator<A> for Tree<A>
    where A: Sized
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = A>
    {
        Tree { elements: Vec::from_iter(iter.into_iter().map(|e| TreeElement::new(e))) }
    }
}


struct TreeElement<T> {
    pub parent_idx: Option<usize>,
    pub childs_indexes: Vec<usize>,
    pub element: T
}

impl<T> PartialEq<TreeElement<T>> for TreeElement<T>
    where T: PartialEq
{
    fn eq(&self, other: &TreeElement<T>) -> bool {
        self.element == other.element
    }
}

impl<T> TreeElement<T> {
    fn new(t: T) -> Self {
        TreeElement {
            parent_idx: None,
            childs_indexes: Vec::new(),
            element: t
        }
    }
}


pub trait IdGetter<T>
    where T: Sized,
{
    type ID: PartialEq + Sized;

    fn get_id_for_node(&self, node: &T)      -> Result<Self::ID>;
    fn get_id_for_parent_of(&self, node: &T) -> Result<Option<Self::ID>>;
}

pub struct TreeBuilder<'a, T, ID, IG>(&'a mut Tree<T>, IG)
    where T: Sized,
          ID: PartialEq + Sized,
          IG: IdGetter<T, ID = ID>;

impl<'a, T, ID, IG> TreeBuilder<'a, T, ID, IG>
    where T: Sized,
          ID: PartialEq + Sized,
          IG: IdGetter<T, ID = ID>
{
    pub fn build(&mut self) -> Result<()> {
        let mut i = 0;
        while let Some(node) = self.0.elements.get(i) {
            if let Some(parent_id) = self.1.get_id_for_parent_of(&node.element)? {
                if let Some(parent_idx) = self.find_node_idx(&parent_id)? {
                    if let Some(parent) = self.0.elements.get_mut(parent_idx) {
                        parent.childs_indexes.push(i);
                    }

                    if let Some(child) = self.0.elements.get_mut(i) {
                        child.parent_idx = Some(parent_idx);
                    }
                }
            }

            i += 1
        }

        Ok(())
    }

    fn find_node_idx<'t>(&'t self, search_id: &IG::ID) -> Result<Option<usize>> {
        let mut i = 0;

        while let Some(node) = self.0.elements.get(i) {
            let id = self.1.get_id_for_node(&node.element)?;
            if id == *search_id {
                return Ok(Some(i))
            }

            i += 1
        }

        return Ok(None)
    }
}

pub struct Traverse<'a, T: Sized>(&'a Tree<T>);


#[cfg(test)]
mod tests {
    use super::*;

    struct IdGetterImpl;
    impl IdGetter<usize> for IdGetterImpl {
        type ID = usize;

        fn get_id_for_node(&self, node: &usize)      -> Result<Self::ID> {
            Ok(*node)
        }

        fn get_id_for_parent_of(&self, node: &usize) -> Result<Option<Self::ID>> {
            if *node > 1 {
                Ok(Some(*node - 1))
            } else {
                Ok(None)
            }
        }
    }


    #[test]
    fn test_insertion() {
        let mut tree = Tree::new();
        (1..100).for_each(|i| {
            tree.add_node(i);
        });

        assert!((1..100).all(|i| tree.elements.iter().any(|e| e.element == i)));
    }

    #[test]
    fn test_insertion_and_linking() {
        let mut tree = Tree::new();
        (1..100).for_each(|i| tree.add_node(i));

        let r = tree.build_tree::<usize, IdGetterImpl>(IdGetterImpl).build();
        assert!(r.is_ok());
    }


    #[test]
    fn test_linking_leaves_none_unlinked() {
        let mut tree = Tree::new();
        (1..100).for_each(|i| tree.add_node(i));

        let r = tree.build_tree::<usize, IdGetterImpl>(IdGetterImpl) .build();
        assert!(r.is_ok());

        let c = tree.elements.iter()
            .filter(|element| element.parent_idx.is_none())
            .count();
        assert_eq!(c, 1);

        let c = tree.elements.iter()
            .filter(|element| element.childs_indexes.is_empty())
            .count();
        assert_eq!(c, 1);
    }

}