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
extern crate collections_rs as collections;

pub mod vec;
mod map;

pub use map::MapGraph;

/// A directed graph with edge weights. The efficiency of the different
/// operations is highly dependent on the backend used.
pub trait DirectedWeightedGraph<'g, N, W>
where
    N: 'g + Eq,
    W: 'g,
{
    /// An iterator that iterates over all edges.
    type AllWeightedEdges: Iterator<Item = (&'g N, &'g N, &'g W)>;
    /// An iterator that iterates over all edges, giving mutable access to the
    /// weight.
    type AllWeightedEdgesMut: Iterator<Item = (&'g N, &'g N, &'g mut W)>;

    /// Returns an iterator over all the edges in this graph.
    fn all_edges(&'g self) -> Self::AllWeightedEdges;

    /// Returns an iterator over all the ediges in this graph, with mutable
    /// access to the weight.
    fn all_edges_mut(&'g mut self) -> Self::AllWeightedEdgesMut;

    /// Adds an edge to this graph.
    fn add_edge(&'g mut self, N, N, W) -> Option<(N, N, W)>;

    /// Removes an edge from the graph.
    fn remove_edge(&'g mut self, &N, &N) -> Option<(N, N, W)>;

    /// Checks if a graph has an edge or not.
    ///
    /// # Complexity
    /// The default implementation runs in O(|E|) time.
    fn has_edge(&'g self, source: &N, sink: &N) -> bool {
        self.edge_weight(source, sink).is_some()
    }

    /// Gets a borrow to the weight of the requested edge, if it exist.
    ///
    /// # Complexity
    /// The default implementation runs in O(|E|).
    fn edge_weight(&'g self, source: &N, sink: &N) -> Option<&W> {
        self.all_edges()
            .find(|&(n1, n2, _)| n1 == source && n2 == sink)
            .map(|(_, _, weight)| weight)
    }

    /// Gets a mutable borrow to the weight of the requested edge, if it exist.
    ///
    /// # Complexity
    /// The default implementation runs in O(|E|) time.
    fn edge_weight_mut(&'g mut self, source: &N, sink: &N) -> Option<&mut W> {
        self.all_edges_mut()
            .find(|&(n1, n2, _)| n1 == source && n2 == sink)
            .map(|(_, _, weight)| weight)
    }
}