use crate::{GraphError, NodeId};
use std::collections::{BTreeMap, BTreeSet, VecDeque, btree_map::Entry};
#[derive(Debug, Default)]
pub struct ReferenceGraph {
adjacency: BTreeMap<NodeId, BTreeSet<NodeId>>,
edges: usize,
}
impl ReferenceGraph {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn add_node(&mut self, node: NodeId) -> bool {
if let Entry::Vacant(entry) = self.adjacency.entry(node) {
entry.insert(BTreeSet::new());
true
} else {
false
}
}
pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
GraphError::check_distinct(source, target)?;
let inserted = self.adjacency.entry(source).or_default().insert(target);
self.adjacency.entry(target).or_default().insert(source);
self.edges += usize::from(inserted);
Ok(inserted)
}
pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
GraphError::check_distinct(source, target)?;
let removed = self
.adjacency
.get_mut(&source)
.is_some_and(|neighbors| neighbors.remove(&target));
if removed {
self.adjacency
.get_mut(&target)
.expect("edge endpoint exists")
.remove(&source);
self.edges -= 1;
}
Ok(removed)
}
pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
for node in [source, target] {
if !self.adjacency.contains_key(&node) {
return Err(GraphError::UnknownNode { node });
}
}
if source == target {
return Ok(true);
}
let mut visited = BTreeSet::from([source]);
let mut pending = VecDeque::from([source]);
while let Some(node) = pending.pop_front() {
for &neighbor in &self.adjacency[&node] {
if neighbor == target {
return Ok(true);
}
if visited.insert(neighbor) {
pending.push_back(neighbor);
}
}
}
Ok(false)
}
#[must_use]
pub fn node_count(&self) -> usize {
self.adjacency.len()
}
#[must_use]
pub fn edge_count(&self) -> usize {
self.edges
}
}