use std::collections::hash_map::Entry;
use relate_core::{NodeId, RelId, Result};
use crate::hash_seed::FxMap;
use crate::overlay::ExecGraph;
use super::Search;
pub(crate) struct Dag {
origin: NodeId,
first: FxMap<NodeId, (u32, (NodeId, RelId))>,
more: FxMap<NodeId, Vec<(NodeId, RelId)>>,
}
pub(crate) struct Layer<'a> {
dag: &'a Dag,
nodes: &'a [NodeId],
}
impl Layer<'_> {
pub(crate) fn nodes(&self) -> &[NodeId] {
self.nodes
}
pub(crate) fn trails(&self, graph: &ExecGraph<'_>, target: NodeId) -> Result<Vec<Vec<RelId>>> {
debug_assert!(
self.nodes.contains(&target),
"Layer::trails: {target} is not a node of this layer"
);
self.dag.trails(graph, target)
}
}
impl Dag {
pub(crate) fn trails(&self, graph: &ExecGraph<'_>, target: NodeId) -> Result<Vec<Vec<RelId>>> {
let mut out = Vec::new();
if target != self.origin && !self.first.contains_key(&target) {
return Ok(out);
}
let mut stack = vec![(target, Vec::new())];
while let Some((at, mut rev)) = stack.pop() {
graph.cancel_tick()?;
let Some(&(_, (prev, rid))) = self.first.get(&at) else {
rev.reverse();
out.push(rev);
continue;
};
for &(p, r) in self.more.get(&at).into_iter().flatten() {
let mut longer = rev.clone();
longer.push(r);
stack.push((p, longer));
}
rev.push(rid);
stack.push((prev, rev));
}
Ok(out)
}
}
impl Search<'_, '_> {
pub(crate) fn dag(
&self,
origin: NodeId,
all: bool,
skip: Option<RelId>,
stop: impl FnMut(NodeId, u32) -> Result<bool>,
) -> Result<Dag> {
self.walk(origin, all, skip, stop, |_| Ok(false))
}
pub(crate) fn dag_layers(
&self,
origin: NodeId,
all: bool,
skip: Option<RelId>,
on_layer: impl FnMut(Layer<'_>) -> Result<bool>,
) -> Result<Dag> {
self.walk(origin, all, skip, |_, _| Ok(false), on_layer)
}
fn walk(
&self,
origin: NodeId,
all: bool,
skip: Option<RelId>,
mut stop: impl FnMut(NodeId, u32) -> Result<bool>,
mut on_layer: impl FnMut(Layer<'_>) -> Result<bool>,
) -> Result<Dag> {
let mut dag = Dag {
origin,
first: FxMap::default(),
more: FxMap::default(),
};
let mut stopped = stop(origin, 0)?;
let mut halted = on_layer(Layer {
dag: &dag,
nodes: &[origin],
})?;
let mut frontier = vec![origin];
let mut depth = 0;
while !stopped && !halted && !frontier.is_empty() && depth < self.max {
let next_depth = depth + 1;
let mut next = Vec::new();
for &cur in &frontier {
self.graph.cancel_tick()?;
self.each_hop(cur, |n, rid| {
if Some(rid) == skip || n == origin {
return Ok(());
}
match dag.first.entry(n) {
Entry::Vacant(v) => {
v.insert((next_depth, (cur, rid)));
next.push(n);
stopped |= stop(n, next_depth)?;
}
Entry::Occupied(o) if all && o.get().0 == next_depth => {
dag.more.entry(n).or_default().push((cur, rid));
}
Entry::Occupied(_) => {}
}
Ok(())
})?;
if stopped && !all {
break;
}
}
if !next.is_empty() {
halted = on_layer(Layer {
dag: &dag,
nodes: &next,
})?;
}
frontier = next;
depth = next_depth;
}
Ok(dag)
}
pub(crate) fn closed(&self, s: NodeId, all: bool) -> Result<Vec<Vec<RelId>>> {
let mut firsts = self.hops(s)?;
firsts.sort_by_key(|&(x, _)| x != s);
let mut cap = self.max;
let mut out: Vec<Vec<RelId>> = Vec::new();
for (x, first) in firsts {
if cap == 0 {
break;
}
let back = Search {
max: cap - 1,
..self.clone()
};
let rests = back
.dag(x, all, Some(first), |n, _| Ok(n == s))?
.trails(self.graph, s)?;
let Some(len) = rests.first().map(|rest| rest.len() + 1) else {
continue;
};
if out.first().is_some_and(|t| t.len() > len) {
out.clear();
}
out.extend(
rests
.into_iter()
.map(|rest| std::iter::once(first).chain(rest).collect::<Vec<_>>()),
);
cap = if all { len as u32 } else { len as u32 - 1 };
}
Ok(out)
}
}