use std::hash::{Hash};
use std::collections::HashMap;
use std::iter::Map;
use std::collections::hash_map::{
Keys,
};
use std::collections::hash_map::Entry::{
Occupied,
Vacant,
};
use std::slice::{
Iter,
};
use std::fmt;
use std::ops::{Index, IndexMut};
#[derive(Clone)]
pub struct GraphMap<N: Eq + Hash, E> {
nodes: HashMap<N, Vec<N>>,
edges: HashMap<(N, N), E>,
}
impl<N: Eq + Hash + fmt::Debug, E: fmt::Debug> fmt::Debug for GraphMap<N, E>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.nodes.fmt(f)
}
}
#[inline]
fn edge_key<N: Copy + Ord>(a: N, b: N) -> (N, N)
{
if a <= b { (a, b) } else { (b, a) }
}
#[inline]
fn copy<N: Copy>(n: &N) -> N { *n }
pub trait NodeTrait : Copy + Ord + Eq + Hash {}
impl<N> NodeTrait for N where N: Copy + Ord + Eq + Hash {}
impl<N, E> GraphMap<N, E> where N: NodeTrait
{
pub fn new() -> Self
{
GraphMap {
nodes: HashMap::new(),
edges: HashMap::new(),
}
}
pub fn with_capacity(nodes: usize, edges: usize) -> Self
{
GraphMap {
nodes: HashMap::with_capacity(nodes),
edges: HashMap::with_capacity(edges),
}
}
pub fn node_count(&self) -> usize
{
self.nodes.len()
}
pub fn edge_count(&self) -> usize
{
self.edges.len()
}
pub fn clear(&mut self)
{
self.nodes.clear();
self.edges.clear();
}
pub fn add_node(&mut self, n: N) -> N {
match self.nodes.entry(n) {
Occupied(_) => {}
Vacant(ent) => { ent.insert(Vec::new()); }
}
n
}
pub fn remove_node(&mut self, n: N) -> bool {
let successors = match self.nodes.remove(&n) {
None => return false,
Some(sus) => sus,
};
for succ in successors.into_iter() {
self.remove_single_edge(&succ, &n);
self.edges.remove(&edge_key(n, succ));
}
true
}
pub fn contains_node(&self, n: N) -> bool {
self.nodes.contains_key(&n)
}
pub fn add_edge(&mut self, a: N, b: N, edge: E) -> bool
{
match self.nodes.entry(a) {
Occupied(ent) => { ent.into_mut().push(b); }
Vacant(ent) => { ent.insert(vec![b]); }
}
match self.nodes.entry(b) {
Occupied(ent) => { ent.into_mut().push(a); }
Vacant(ent) => { ent.insert(vec![a]); }
}
self.edges.insert(edge_key(a, b), edge).is_none()
}
fn remove_single_edge(&mut self, a: &N, b: &N) -> bool
{
match self.nodes.get_mut(a) {
None => false,
Some(sus) => {
match sus.iter().position(|elt| elt == b) {
Some(index) => { sus.swap_remove(index); true }
None => false,
}
}
}
}
pub fn remove_edge(&mut self, a: N, b: N) -> Option<E>
{
let exist1 = self.remove_single_edge(&a, &b);
let exist2 = self.remove_single_edge(&b, &a);
let weight = self.edges.remove(&edge_key(a, b));
debug_assert!(exist1 == exist2 && exist1 == weight.is_some());
weight
}
pub fn contains_edge(&self, a: N, b: N) -> bool {
self.edges.contains_key(&edge_key(a, b))
}
pub fn nodes<'a>(&'a self) -> Nodes<'a, N>
{
Nodes{iter: self.nodes.keys().map(copy)}
}
pub fn neighbors<'a>(&'a self, from: N) -> Neighbors<'a, N>
{
Neighbors{iter:
match self.nodes.get(&from) {
Some(neigh) => neigh.iter(),
None => [].iter(),
}.map(copy)
}
}
pub fn edges<'a>(&'a self, from: N) -> Edges<'a, N, E>
{
Edges {
from: from,
iter: self.neighbors(from),
edges: &self.edges,
}
}
pub fn edge_weight<'a>(&'a self, a: N, b: N) -> Option<&'a E>
{
self.edges.get(&edge_key(a, b))
}
pub fn edge_weight_mut<'a>(&'a mut self, a: N, b: N) -> Option<&'a mut E>
{
self.edges.get_mut(&edge_key(a, b))
}
}
macro_rules! iterator_methods {
() => (
#[inline]
fn next(&mut self) -> Option<<Self as Iterator>::Item>
{
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>)
{
self.iter.size_hint()
}
)
}
pub struct Nodes<'a, N: 'a> {
iter: Map<Keys<'a, N, Vec<N>>, fn(&N) -> N>,
}
impl<'a, N> Iterator for Nodes<'a, N>
{
type Item = N;
iterator_methods!();
}
pub struct Neighbors<'a, N: 'a> {
iter: Map<Iter<'a, N>, fn(&N) -> N>,
}
impl<'a, N> Iterator for Neighbors<'a, N>
{
type Item = N;
iterator_methods!();
}
pub struct Edges<'a, N, E: 'a> where N: 'a + NodeTrait
{
pub from: N,
pub edges: &'a HashMap<(N, N), E>,
pub iter: Neighbors<'a, N>,
}
impl<'a, N, E> Iterator for Edges<'a, N, E>
where N: 'a + NodeTrait, E: 'a
{
type Item = (N, &'a E);
fn next(&mut self) -> Option<(N, &'a E)>
{
match self.iter.next() {
None => None,
Some(b) => {
let a = self.from;
match self.edges.get(&edge_key(a, b)) {
None => unreachable!(),
Some(edge) => {
Some((b, edge))
}
}
}
}
}
}
impl<N, E> Index<(N, N)> for GraphMap<N, E> where N: NodeTrait
{
type Output = E;
fn index(&self, index: (N, N)) -> &E
{
self.edge_weight(index.0, index.1).expect("GraphMap::index: no such edge")
}
}
impl<N, E> IndexMut<(N, N)> for GraphMap<N, E> where N: NodeTrait
{
fn index_mut(&mut self, index: (N, N)) -> &mut E
{
self.edge_weight_mut(index.0, index.1).expect("GraphMap::index: no such edge")
}
}