1#![doc = include_str!("../README.md")]
2
3use std::collections::HashMap;
4
5use uuid::Uuid;
6
7#[derive(Debug)]
15pub struct Graph<Node, EdgeData> {
16 pub nodes: HashMap<NodeIndex, Node>,
17 pub edges: HashMap<EdgeIndex, Edge<EdgeData>>,
18}
19
20#[derive(Debug, Clone)]
22pub struct Edge<Data> {
23 pub nodes: (NodeIndex, NodeIndex),
24 pub data: Data,
25}
26
27impl<Data> Edge<Data> {
28 pub fn new(nodes: (NodeIndex, NodeIndex), data: Data) -> Edge<Data> {
30 Edge {
31 nodes,
32 data,
33 }
34 }
35}
36
37#[derive(Debug, Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
39pub struct NodeIndex(Uuid);
40
41#[derive(Debug, Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
43pub struct EdgeIndex(Uuid);
44
45impl NodeIndex {
46 pub fn new() -> NodeIndex {
48 NodeIndex(Uuid::new_v4())
49 }
50}
51
52impl EdgeIndex {
53 pub fn new() -> EdgeIndex {
55 EdgeIndex(Uuid::new_v4())
56 }
57}
58
59impl<Node, EdgeData> Graph<Node, EdgeData> {
60 pub fn new() -> Self {
65 Self {
66 nodes: HashMap::new(),
67 edges: HashMap::new()
68 }
69 }
70
71 pub fn nodes<'a>(&'a self) -> impl Iterator + 'a {
74 self.nodes.iter()
75 }
76
77 pub fn edges<'a>(&'a self) -> impl Iterator + 'a {
80 self.edges.iter()
81 }
82
83 pub fn edge(&mut self, edge: Edge<EdgeData>) -> EdgeIndex {
85 let idx = EdgeIndex::new();
86 self.edges.insert(idx, edge);
87 idx
88 }
89
90 pub fn r_edge(&mut self, idx: EdgeIndex) -> Option<Edge<EdgeData>> {
93 self.edges.remove(&idx)
94 }
95
96 pub fn node(&mut self, node: Node) -> NodeIndex {
98 let idx = NodeIndex::new();
99 self.nodes.insert(idx, node);
100 idx
101 }
102
103 pub fn r_node(&mut self, idx: NodeIndex) -> Option<Node> {
109 self.nodes.remove(&idx)
110 }
111}
112
113pub mod prelude {
114 pub use crate::{
115 Graph,
116 NodeIndex,
117 EdgeIndex,
118 Edge,
119 };
120}