algae_graph/store/
matrix.rs1use crate::Node;
7use serde::{Deserialize, Serialize};
8use std::iter::Extend;
9
10#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
11pub struct AdjacencyMatrix<N = String, V = i64>
12where
13 N: Node,
14 V: Clone + PartialEq,
15{
16 store: Vec<(N, Vec<(N, V)>)>,
17}
18
19impl<N: Node, V: Clone + PartialEq> AdjacencyMatrix<N, V> {
20 pub fn new() -> Self {
21 Self { store: Vec::new() }
22 }
23 pub fn clear(&mut self) {
25 self.store.clear()
26 }
27 pub fn capacity(&self) -> usize {
29 self.store.capacity()
30 }
31 pub fn get(&self, key: &N) -> Option<&Vec<(N, V)>> {
33 self.store
34 .iter()
35 .find_map(|(k, v)| if k == key { Some(v) } else { None })
36 }
37 pub fn get_key_value(&self, key: &N) -> Option<(&N, &Vec<(N, V)>)> {
39 self.store
40 .iter()
41 .find_map(|(k, v)| if k == key { Some((k, v)) } else { None })
42 }
43 pub fn get_mut(&mut self, key: &N) -> Option<&mut Vec<(N, V)>> {
45 self.store
46 .iter_mut()
47 .find_map(|(k, v)| if k == key { Some(v) } else { None })
48 }
49 pub fn keys(&self) -> impl Iterator<Item = &N> {
51 self.store.iter().map(|(k, _)| k)
52 }
53 pub fn len(&self) -> usize {
55 self.store.len()
56 }
57 pub fn push(&mut self, elem: N, value: Vec<(N, V)>) {
59 self.store.push((elem, value));
60 }
61 pub fn shrink_to_fit(&mut self) {
63 self.store.shrink_to_fit()
64 }
65 pub fn with_capacity(capacity: usize) -> Self {
67 Self {
68 store: Vec::with_capacity(capacity),
69 }
70 }
71}
72
73impl<N: Node, V: Clone + PartialEq> Extend<(N, Vec<(N, V)>)> for AdjacencyMatrix<N, V> {
74 fn extend<T: IntoIterator<Item = (N, Vec<(N, V)>)>>(&mut self, iter: T) {
75 self.store.extend(iter);
76 }
77}
78
79impl<N, V> std::ops::Index<N> for AdjacencyMatrix<N, V>
80where
81 N: Node,
82 V: Clone + PartialEq,
83{
84 type Output = Vec<(N, V)>;
85
86 fn index(&self, index: N) -> &Self::Output {
87 self.get(&index).unwrap()
88 }
89}
90
91impl<N, V> std::ops::IndexMut<N> for AdjacencyMatrix<N, V>
92where
93 N: Node,
94 V: Clone + PartialEq,
95{
96 fn index_mut(&mut self, index: N) -> &mut Self::Output {
97 self.get_mut(&index).unwrap()
98 }
99}