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
pub mod bitgraph;
pub mod print;
pub mod sparsegraph;
pub mod transform;

pub trait Graph {
    type Node;

    fn nb_nodes(&self) -> usize;
    fn nodes(&self) -> Box<Iterator<Item = Self::Node>>;

    fn get(&self, from: &Self::Node, to: &Self::Node) -> bool;
    fn set_edge(&mut self, from: &Self::Node, to: &Self::Node, bool);

    fn clear_all_to(&mut self, to: &Self::Node) {
        for node in self.nodes() {
            self.set_edge(&node, to, false);
        }
    }
    fn add_all_to<I>(&mut self, to: &Self::Node, from: I)
    where
        I: IntoIterator<Item = Self::Node>,
    {
        for node in from {
            self.set_edge(&node, to, true);
        }
    }
    fn set_all_to<I>(&mut self, to: &Self::Node, from: I)
    where
        I: IntoIterator<Item = Self::Node>,
    {
        self.clear_all_to(to);
        self.add_all_to(to, from);
    }
    fn clear_all_from(&mut self, from: &Self::Node) {
        for node in self.nodes() {
            self.set_edge(from, &node, false);
        }
    }
    fn add_all_from<I>(&mut self, from: &Self::Node, to: I)
    where
        I: IntoIterator<Item = Self::Node>,
    {
        for node in to {
            self.set_edge(from, &node, true);
        }
    }
    fn set_all_from<I>(&mut self, from: &Self::Node, to: I)
    where
        I: IntoIterator<Item = Self::Node>,
    {
        self.clear_all_from(from);
        self.add_all_from(from, to);
    }
    fn iter_from<'a>(&'a self, from: Self::Node) -> Box<'a + Iterator<Item = Self::Node>> {
        Box::new(self.nodes().filter(move |to| self.get(&from, to)))
    }
    fn iter_to<'a>(&'a self, to: Self::Node) -> Box<'a + Iterator<Item = Self::Node>> {
        Box::new(self.nodes().filter(move |from| self.get(from, &to)))
    }
    fn has_from<'a>(&'a self, from: &Self::Node) -> bool {
        self.nodes().any(move |to| self.get(&from, &to))
    }
    fn has_to<'a>(&'a self, to: &Self::Node) -> bool {
        self.nodes().any(move |from| self.get(&from, &to))
    }
    fn iter_from_drain<'a>(&'a mut self, from: Self::Node) -> Box<'a + Iterator<Item = Self::Node>> {
        Box::new(self.nodes().filter(move |to| {
            let x = self.get(&from, to);
            self.set_edge(&from, to, false);
            x
        }))
    }
    fn drain_from_and_clear_all_to_drained<'a>(&'a mut self, from: Self::Node) -> Box<'a + Iterator<Item = Self::Node>> {
        use util::FinishIteratorExt;
        let nodes_from = self.iter_from(from).collect::<Vec<_>>();
        Box::new(nodes_from.into_iter().inspect(move |node| self.clear_all_to(node)).finish())
    }
    fn clear(&mut self) {
        for n in self.nodes() {
            self.clear_all_to(&n);
        }
    }
}