generic_graph/lib.rs
1//! # generic_graph
2//!
3//!`generic_graph` defines a series of traits for the implementation of either directed and
4//! non directed graphs. This library also provides a few default implementation if the programmer
5//! doesn't have special requirements for his graphs.
6//!
7//!All traits make large use of generic types, allowing for deep customization of the graph structure
8//!
9use std::hash::Hash;
10use std::ops::{Add, Sub};
11pub mod adjacency_list;
12
13///Generic behaviour of a vertex
14///
15/// Key type (K) must implement Hash, Eq and Clone
16///
17/// Value type is free
18pub trait Vertex<K, V>
19 where K: Hash + Eq + Clone
20{
21 fn get_value(&self) -> &V;
22
23 fn get_mut_value(&mut self) -> &mut V;
24
25 fn key(&self) -> K;
26}
27
28///Generic behaviour of an edge
29///
30///Generic type C is the key type of the edge
31///
32///Generic type K is the key type of the vertexes connected by the edge
33///
34///Generic type W is
35pub trait Edge<K, W, C>
36 where K: Hash + Eq + Clone,
37 C: Hash + Eq + Clone,
38 W: Add + Sub + Eq + Ord + Copy
39{
40 fn get_weight(&self) -> W;
41
42 fn set_weight(&mut self, weight: W);
43
44 fn left(&self) -> &K;
45
46 fn right(&self) -> &K;
47
48 ///This pair must not be used as a key for the edge, this must instead be used to generate the key
49 /// or to construct a new edge
50 fn get_pair(&self) -> (&K, &K);
51
52 ///An associated function constructing the edge key from a pair of
53 /// vertex keys must be implemented for the edge tipe
54 ///
55 ///the key returned by the key(&self) method must correspond to the key generated by said function
56 /// with the pair of keys returned by the method get_pair(&self)
57 fn generate_key(pair: (&K, &K)) -> C;
58
59 ///The key returned by this method must correspond to the key generated by passing the pair of keys
60 /// returned by get_pair(&self) to rhe associated function generate_key(pair: (&T, &T))
61 fn key(&self) -> C;
62}
63
64
65///This trait define the behaviour of a directed graph
66/// it requires the for vertexes (T), edges (E), vertex's keys (K), vertex's values (v), edge's weights (W) and edge's keys (C)
67pub trait DirectedGraph<T, E, K, V, W, C>
68 where K: Hash + Eq + Clone,
69 C: Hash + Eq + Clone,
70 W: Add + Sub + Eq + Ord + Copy,
71 T: Vertex<K, V>,
72 E: Edge<K, W, C>
73{
74 ///This method returns a boolean stating if exist an edge from the first vertex to the other
75 fn adjacent(&self, from: &K, to: &K) -> bool;
76
77 ///This method returns a vector containing the keys of all the vertexes reached by edges starting from the argument
78 fn neighbors(&self, from: &K) -> Vec<&K>;
79
80 ///This method returns a vector containing the keys of all the vertexes with by edges leading to the argument
81 fn leading_to(&self, to: &K) -> Vec<&K>;
82
83 ///This method returns a vector containing references to the keys of all vertexes in the graph
84 fn get_all_keys(&self) -> Vec<&K>;
85
86 ///This method returns a vector containing the pairs of all edges in the graph
87 fn get_all_pairs(&self) -> Vec<(&K, &K)>;
88
89 fn get_vertex(&self, key: &K) -> Option<&T>;
90
91 fn get_mut_vertex(&mut self, key: &K) -> Option<&mut T>;
92
93 fn get_edge(&self, pair: (&K, &K)) -> Option<&E>;
94
95 fn get_mut_edge(&mut self, pair: (&K, &K)) -> Option<&mut E>;
96}
97
98///This trait adds to a Directed graph the methods to add and remove edges
99pub trait VariableEdges<T, E, K, V, W, C>: DirectedGraph<T, E, K, V, W, C>
100 where K: Hash + Eq + Clone,
101 C: Hash + Eq + Clone,
102 W: Add + Sub + Eq + Ord + Copy,
103 T: Vertex<K, V>,
104 E: Edge<K, W, C>
105{
106 ///If an edge with an equal key is already present, the edge is updated (not the key)
107 /// and the old edge is returned ad Ok(Some(old_edge)). If not present OK(None) is returned.
108 ///
109 ///If one or both of the concerned vertexes are missing an error will be returned containing
110 /// an enum specifying which side is missing
111 fn add_edge(&mut self, edge: E) -> Result<Option<E>, EdgeSide>;
112
113 ///If the removed edge was present it's removed and returned as Some(edge). Otherwise None is returned
114 fn remove_edge(&mut self, pair: (&K, &K)) -> Option<E>;
115}
116
117///This trait adds to a Directed graph the methods to add and remove edges
118pub trait VariableVertexes<T, E, K, V, W, C>: DirectedGraph<T, E, K, V, W, C>
119 where K: Hash + Eq + Clone,
120 C: Hash + Eq + Clone,
121 W: Add + Sub + Eq + Ord + Copy,
122 T: Vertex<K, V>,
123 E: Edge<K, W, C>
124{
125 ///If a vertex with an equal key is already present, the vertex is updated (not the key)
126 /// and the old vertex is returned ad Some(old_vertex). If not present None is returned.
127 fn add_vertex(&mut self, vertex: T) -> Option<T>;
128
129 ///If the removed vertex was present it's removed and returned as Some(vertex). Otherwise None is returned
130 fn remove_vertex(&mut self, key: K) -> Option<T>;
131}
132
133///This trait does not add methods. It just indicates that the graph is not directed.
134///
135///As such, the vectors returned by the method neighbors(&self, from: &K) and leading_to(&self, to: &K)
136/// contains the same keys, eventually in different order (Unless the graph muted between calls).
137///
138///Also the outcome the methods accepting a pair of keys (adjacent(...), get_edge(...), get_mutable_edge(...))
139/// must not be influenced by the order of the keys.
140pub trait Graph<T, E, K, V, W, C>: DirectedGraph<T, E, K, V, W, C>
141 where K: Hash + Eq + Clone,
142 C: Hash + Eq + Clone,
143 W: Add + Sub + Eq + Ord + Copy,
144 T: Vertex<K, V>,
145 E: Edge<K, W, C>
146{}
147
148///A default implementation for vertexes. This implementation should be suitable for most of the
149/// problem one can encounter requiring graph.
150///
151///Contrary to other graph implementation this library does not expect the vertexes to store if they
152/// have been visited, or if they were marked. The reason for this is that the author believes such an
153/// information should be stored in a structure extern and independent to the graph, this to ensure
154/// consistency between threads and to allow different algorithms to use different structures according
155/// to their needs
156///
157///methods are self explanatory
158#[derive(Debug, Eq, PartialEq)]
159pub struct SimpleVertex<K: Hash + Eq + Clone, V> {
160 key: K,
161 value: V,
162}
163
164impl<K: Hash + Eq + Clone, V> SimpleVertex<K, V> {
165
166 ///Creates a new instance of SimpleVertex
167 pub fn new(key: K, value: V) -> SimpleVertex<K, V> {
168 SimpleVertex {
169 key,
170 value,
171 }
172 }
173}
174
175///`EdgeSide` is used to indicate which side of the edge caused an error.
176/// Usually returned as Result::Err(EdgeSide) by the VariableEdges::add_edge() method when
177/// it was impossible to add the edge due to the absence of one of the concerned vertexes.
178///
179///Can be used by user defined functions or types for error handling.
180#[derive(Debug, Eq, PartialEq)]
181pub enum EdgeSide {
182 Left,
183 Right,
184 Both
185}
186
187///`SimpleVertex` implement the Vertex trait maintaining the key type and the value type generics
188impl<K: Hash + Eq + Clone, V> Vertex<K, V> for SimpleVertex<K, V> {
189
190 ///Get the value stored in a vertex
191 fn get_value(&self) -> &V {
192 &(self.value)
193 }
194
195 ///Get the value as mutable reference
196 fn get_mut_value(&mut self) -> &mut V {
197 &mut (self.value)
198 }
199
200 ///Returns the key of the vertex
201 fn key(&self) -> K {
202 self.key.clone()
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 #[test]
211 fn simple_vertex_construction() {
212 let vertex = SimpleVertex::new(1,0);
213
214 assert_eq!(vertex, SimpleVertex {key: 1, value: 0});
215 }
216
217 #[test]
218 fn simple_vertex_getters() {
219 let mut vertex = SimpleVertex::new(1,0);
220
221 assert_eq!(vertex.get_value(), &0);
222 assert_eq!(vertex.key(), 1);
223
224 *vertex.get_mut_value() += 3;
225 assert_eq!(vertex.get_value(), &3);
226 }
227}