use crate::Node;
use serde::{Deserialize, Serialize};
use std::iter::Extend;
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct AdjacencyMatrix<N = String, V = i64>
where
N: Node,
V: Clone + PartialEq,
{
store: Vec<(N, Vec<(N, V)>)>,
}
impl<N: Node, V: Clone + PartialEq> AdjacencyMatrix<N, V> {
pub fn new() -> Self {
Self { store: Vec::new() }
}
pub fn clear(&mut self) {
self.store.clear()
}
pub fn capacity(&self) -> usize {
self.store.capacity()
}
pub fn get(&self, key: &N) -> Option<&Vec<(N, V)>> {
self.store
.iter()
.find_map(|(k, v)| if k == key { Some(v) } else { None })
}
pub fn get_key_value(&self, key: &N) -> Option<(&N, &Vec<(N, V)>)> {
self.store
.iter()
.find_map(|(k, v)| if k == key { Some((k, v)) } else { None })
}
pub fn get_mut(&mut self, key: &N) -> Option<&mut Vec<(N, V)>> {
self.store
.iter_mut()
.find_map(|(k, v)| if k == key { Some(v) } else { None })
}
pub fn keys(&self) -> impl Iterator<Item = &N> {
self.store.iter().map(|(k, _)| k)
}
pub fn len(&self) -> usize {
self.store.len()
}
pub fn push(&mut self, elem: N, value: Vec<(N, V)>) {
self.store.push((elem, value));
}
pub fn shrink_to_fit(&mut self) {
self.store.shrink_to_fit()
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
store: Vec::with_capacity(capacity),
}
}
}
impl<N: Node, V: Clone + PartialEq> Extend<(N, Vec<(N, V)>)> for AdjacencyMatrix<N, V> {
fn extend<T: IntoIterator<Item = (N, Vec<(N, V)>)>>(&mut self, iter: T) {
self.store.extend(iter);
}
}
impl<N, V> std::ops::Index<N> for AdjacencyMatrix<N, V>
where
N: Node,
V: Clone + PartialEq,
{
type Output = Vec<(N, V)>;
fn index(&self, index: N) -> &Self::Output {
self.get(&index).unwrap()
}
}
impl<N, V> std::ops::IndexMut<N> for AdjacencyMatrix<N, V>
where
N: Node,
V: Clone + PartialEq,
{
fn index_mut(&mut self, index: N) -> &mut Self::Output {
self.get_mut(&index).unwrap()
}
}