1use DirectedWeightedGraph;
2use collections::Map;
3use std::iter;
4
5pub struct MapGraph<M>(M);
6
7impl<M> From<M> for MapGraph<M> {
8 fn from(map: M) -> Self {
9 MapGraph(map)
10 }
11}
12
13impl<M> MapGraph<M> {
14 pub fn unwrap(self) -> M {
16 let MapGraph(graph) = self;
17 graph
18 }
19}
20
21impl<'m, N, W, M> DirectedWeightedGraph<'m, N, W> for MapGraph<M>
23where
24 M: Map<'m, (N, N), W>,
25 N: 'm + Eq + Clone,
26 W: 'm,
27{
28 type AllWeightedEdges = iter::Map<M::Iter, fn((&'m (N, N), &'m W)) -> (&'m N, &'m N, &'m W)>;
29 type AllWeightedEdgesMut = iter::Map<
30 M::IterMut,
31 fn((&'m (N, N), &'m mut W)) -> (&'m N, &'m N, &'m mut W),
32 >;
33
34 fn all_edges(&'m self) -> Self::AllWeightedEdges {
35 fn map_weighted_edge<'m, N, W>(
36 (&(ref source, ref sink), weight): (&'m (N, N), &'m W),
37 ) -> (&'m N, &'m N, &'m W) {
38 (source, sink, weight)
39 }
40
41 let &MapGraph(ref map) = self;
42
43 map.iter().map(map_weighted_edge)
44
45 }
46
47 fn all_edges_mut(&'m mut self) -> Self::AllWeightedEdgesMut {
48 fn map_weighted_edge_mut<'m, N, W>(
49 (&(ref source, ref sink), &mut ref mut weight): (&'m (N, N), &'m mut W),
50 ) -> (&'m N, &'m N, &'m mut W) {
51 (source, sink, weight)
52 }
53
54 let &mut MapGraph(ref mut map) = self;
55
56 map.iter_mut().map(map_weighted_edge_mut)
57 }
58
59 fn add_edge(&'m mut self, source: N, sink: N, weight: W) -> Option<(N, N, W)> {
60 let &mut MapGraph(ref mut map) = self;
61
62 map.insert((source, sink), weight)
63 .map(|((source, sink), value)| (source, sink, value))
64 }
65
66 fn remove_edge(&'m mut self, source: &N, sink: &N) -> Option<(N, N, W)> {
68 let &mut MapGraph(ref mut map) = self;
69 let key = (source.clone(), sink.clone());
70
71 map.remove(&key)
72 .map(|((source, sink), value)| (source, sink, value))
73 }
74
75 fn edge_weight(&'m self, source: &N, sink: &N) -> Option<&W> {
77 let &MapGraph(ref map) = self;
78 map.get(&(source.clone(), sink.clone()))
79 }
80
81 fn edge_weight_mut(&'m mut self, source: &N, sink: &N) -> Option<&mut W> {
83 let &mut MapGraph(ref mut map) = self;
84 map.get_mut(&(source.clone(), sink.clone()))
85 }
86}
87
88
89