1use std::iter::repeat_with;
4
5pub struct Graph<V, E> {
9 pub(crate) vertices: Vec<V>,
10 pub(crate) edges: Vec<Vec<E>>,
11}
12
13#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Debug)]
15pub struct Handle(pub(crate) usize);
16
17impl<V, E> Graph<V, E> {
18 pub fn new() -> Self {
20 Graph {
21 vertices: vec![],
22 edges: vec![],
23 }
24 }
25
26 pub fn new_with_size(size: usize) -> Self {
30 Graph {
31 edges: Vec::with_capacity(size),
32 vertices: Vec::with_capacity(size),
33 }
34 }
35
36 pub fn add_vertex(&mut self, value: V) -> Handle {
38 let handle = self.vertices.len();
39 self.vertices.push(value);
40 self.edges.push(Vec::new());
41 Handle(handle)
42 }
43
44 pub fn size(&self) -> usize {
46 self.vertices.len()
47 }
48
49 pub fn num_edges(&self) -> usize {
51 self.edges.iter().map(|elem| elem.len()).sum()
52 }
53
54 pub fn vertex_value(&self, vertex: Handle) -> &V {
56 &self.vertices[vertex.0]
57 }
58}
59
60impl<V, E> FromIterator<V> for Graph<V, E> {
61 fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self {
63 let vertices: Vec<V> = iter.into_iter().collect();
64 let size = vertices.len();
65 Graph {
66 vertices,
67 edges: repeat_with(Vec::new).take(size).collect(),
68 }
69 }
70}
71
72impl<V, E> Default for Graph<V, E> {
73 fn default() -> Self {
74 Self::new()
75 }
76}
77
78impl<V, E> Graph<V, E>
79where
80 V: Eq,
81{
82 pub fn get_vertex(&self, vertex_value: V) -> Option<Handle> {
85 self.vertices
86 .iter()
87 .enumerate()
88 .find(|(_, vertex)| **vertex == vertex_value)
89 .map(|(i, _)| Handle(i))
90 }
91}