use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use crate::geom::{Direction, Point};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct VertexId(pub(crate) u32);
impl VertexId {
#[must_use]
pub const fn index(self) -> usize {
self.0 as usize
}
}
const NONE: u32 = u32::MAX;
#[derive(Debug, Clone)]
struct Slot {
point: Point,
neighbors: [u32; 4],
alive: bool,
}
#[derive(Debug, Clone, Default)]
pub struct RoutingGraph {
slots: Vec<Slot>,
free: Vec<u32>,
by_point: BTreeMap<Point, VertexId>,
}
impl RoutingGraph {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn len(&self) -> usize {
self.by_point.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.by_point.is_empty()
}
#[must_use]
pub fn capacity(&self) -> usize {
self.slots.len()
}
#[must_use]
pub fn vertex_at(&self, point: Point) -> Option<VertexId> {
self.by_point.get(&point).copied()
}
#[must_use]
pub fn point(&self, v: VertexId) -> Point {
let slot = &self.slots[v.index()];
assert!(slot.alive, "vertex {v:?} is not in the graph");
slot.point
}
#[must_use]
pub fn contains(&self, v: VertexId) -> bool {
self.slots.get(v.index()).is_some_and(|slot| slot.alive)
}
#[must_use]
pub fn neighbor(&self, v: VertexId, dir: Direction) -> Option<VertexId> {
let id = self.slots[v.index()].neighbors[dir.index()];
(id != NONE).then_some(VertexId(id))
}
pub fn vertices(&self) -> impl Iterator<Item = VertexId> + '_ {
self.by_point.values().copied()
}
pub fn edges(&self) -> impl Iterator<Item = (VertexId, VertexId)> + '_ {
self.vertices().flat_map(move |v| {
[Direction::Right, Direction::Up]
.into_iter()
.filter_map(move |dir| self.neighbor(v, dir).map(|w| (v, w)))
})
}
#[must_use]
pub fn canonical(&self) -> (Vec<Point>, Vec<(Point, Point)>) {
let points = self.by_point.keys().copied().collect();
let edges = self
.edges()
.map(|(a, b)| (self.point(a), self.point(b)))
.collect();
(points, edges)
}
pub(crate) fn insert(&mut self, point: Point) -> VertexId {
debug_assert!(!self.by_point.contains_key(&point), "duplicate vertex");
let slot = Slot {
point,
neighbors: [NONE; 4],
alive: true,
};
let id = if let Some(index) = self.free.pop() {
self.slots[index as usize] = slot;
index
} else {
let index = u32::try_from(self.slots.len()).expect("fewer than 2^32 vertices");
self.slots.push(slot);
index
};
let v = VertexId(id);
self.by_point.insert(point, v);
v
}
pub(crate) fn link(&mut self, a: VertexId, dir: Direction, b: VertexId) {
self.slots[a.index()].neighbors[dir.index()] = b.0;
self.slots[b.index()].neighbors[dir.reverse().index()] = a.0;
}
pub(crate) fn unlink(&mut self, a: VertexId, dir: Direction) {
if let Some(b) = self.neighbor(a, dir) {
self.slots[b.index()].neighbors[dir.reverse().index()] = NONE;
}
self.slots[a.index()].neighbors[dir.index()] = NONE;
}
pub(crate) fn remove(&mut self, v: VertexId) {
for (back, forward) in [
(Direction::Left, Direction::Right),
(Direction::Down, Direction::Up),
] {
match (self.neighbor(v, back), self.neighbor(v, forward)) {
(Some(a), Some(b)) => self.link(a, forward, b),
(Some(_), None) => self.unlink(v, back),
(None, Some(_)) => self.unlink(v, forward),
(None, None) => {}
}
}
let slot = &mut self.slots[v.index()];
slot.alive = false;
slot.neighbors = [NONE; 4];
self.by_point.remove(&slot.point);
self.free.push(v.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn remove_joins_neighbours() {
let mut graph = RoutingGraph::new();
let a = graph.insert(Point::new(0, 0));
let b = graph.insert(Point::new(5, 0));
let c = graph.insert(Point::new(9, 0));
graph.link(a, Direction::Right, b);
graph.link(b, Direction::Right, c);
graph.remove(b);
assert_eq!(graph.neighbor(a, Direction::Right), Some(c));
assert_eq!(graph.neighbor(c, Direction::Left), Some(a));
assert_eq!(graph.len(), 2);
let d = graph.insert(Point::new(1, 1));
assert_eq!(d, b);
assert_eq!(graph.canonical().1, [(Point::new(0, 0), Point::new(9, 0))]);
}
}