use relate_core::tokens::WorkspaceCharge;
use relate_core::{NodeId, RelId, Result};
use relate_ir::Direction;
use crate::hash_seed::IdMap;
use crate::workspace::map_entries_bytes;
use crate::UsedSet;
use super::Search;
const RECORDED_ENTRIES: usize = 2;
#[derive(Default)]
struct HopLog {
into: IdMap<NodeId, Vec<(NodeId, RelId)>>,
count: usize,
}
struct Ball<'a, 'g> {
search: &'a Search<'a, 'g>,
dir: Direction,
depth: IdMap<NodeId, u32>,
frontier: Vec<NodeId>,
radius: u32,
log: Option<HopLog>,
charge: WorkspaceCharge,
}
impl<'a, 'g> Ball<'a, 'g> {
fn new(
search: &'a Search<'a, 'g>,
dir: Direction,
origin: NodeId,
log: Option<HopLog>,
) -> Self {
let mut depth = IdMap::default();
depth.insert(origin, 0);
Self {
search,
dir,
depth,
frontier: vec![origin],
radius: 0,
log,
charge: WorkspaceCharge::empty(),
}
}
fn counting(search: &'a Search<'a, 'g>, dir: Direction, origin: NodeId) -> Self {
Self::new(search, dir, origin, None)
}
fn recording(search: &'a Search<'a, 'g>, dir: Direction, origin: NodeId) -> Self {
Self::new(search, dir, origin, Some(HopLog::default()))
}
fn exhausted(&self) -> bool {
self.frontier.is_empty()
}
fn grow_layer(&mut self) -> Result<()> {
debug_assert!(!self.exhausted(), "an exhausted ball has no layer to grow");
let next_depth = self.radius + 1;
let mut next = Vec::new();
for &cur in &self.frontier {
for (node, rid) in self.search.hops_along(self.dir, cur)? {
if let Some(log) = self.log.as_mut() {
log.into.entry(node).or_default().push((cur, rid));
log.count += 1;
}
if let std::collections::hash_map::Entry::Vacant(slot) = self.depth.entry(node) {
slot.insert(next_depth);
next.push(node);
}
}
}
self.frontier = next;
self.radius = next_depth;
self.charge.resize_with(|| {
let logged = self.log.as_ref().map_or(0, |log| log.count);
map_entries_bytes(
self.depth
.capacity()
.saturating_add(self.frontier.capacity()),
)
.saturating_add(map_entries_bytes(logged.saturating_mul(RECORDED_ENTRIES)))
})
}
fn lower_bound(&self, node: NodeId) -> u32 {
match self.depth.get(&node) {
Some(&d) => d,
None if self.exhausted() => u32::MAX,
None => self.radius + 1,
}
}
fn recorded_hops(&self, node: NodeId, left: usize) -> Option<Vec<(NodeId, RelId)>> {
let log = self.log.as_ref()?;
(self.radius as usize >= left || self.exhausted())
.then(|| log.into.get(&node).cloned().unwrap_or_default())
}
}
struct TrailState {
trail: Vec<RelId>,
nodes: Vec<NodeId>,
used: UsedSet,
length: usize,
}
impl TrailState {
fn at(start: NodeId, length: usize) -> Self {
let mut nodes = Vec::with_capacity(length + 1);
nodes.push(start);
Self {
trail: Vec::with_capacity(length),
nodes,
used: UsedSet::default(),
length,
}
}
fn closing(&self) -> bool {
self.trail.len() + 1 == self.length
}
fn enter(&mut self, rid: RelId, node: NodeId) -> bool {
let free = if self.closing() {
!self.used.contains(&rid)
} else {
self.used.insert(rid)
};
if free {
self.trail.push(rid);
self.nodes.push(node);
debug_assert_eq!(self.nodes.len(), self.trail.len() + 1);
}
free
}
fn leave(&mut self) {
let closing = self.trail.len() == self.length;
if let Some(rid) = self.trail.pop() {
if !closing {
self.used.remove(&rid);
}
self.nodes.pop();
}
}
}
struct Frame {
hops: Vec<(NodeId, RelId)>,
next: usize,
}
pub(crate) struct ClassWalk<'a, 'g> {
search: &'a Search<'a, 'g>,
start: NodeId,
end: NodeId,
ball: Ball<'a, 'g>,
cut: bool,
start_ball: Ball<'a, 'g>,
}
impl<'a, 'g> ClassWalk<'a, 'g> {
pub(crate) fn new(search: &'a Search<'a, 'g>, start: NodeId, end: NodeId) -> Self {
Self {
search,
start,
end,
ball: Ball::recording(search, search.dir.flip(), end),
start_ball: Ball::counting(search, search.dir, start),
cut: true,
}
}
fn balance(&mut self, length: u32) -> Result<()> {
while self.ball.radius + self.start_ball.radius < length && !self.ball.exhausted() {
if self.start_ball.exhausted()
|| self.ball.frontier.len() <= self.start_ball.frontier.len()
{
self.ball.grow_layer()?;
} else {
self.start_ball.grow_layer()?;
}
}
Ok(())
}
#[cfg(test)]
pub(super) fn radii(&self) -> (u32, u32) {
(self.ball.radius, self.start_ball.radius)
}
pub(crate) fn unreachable(&self) -> bool {
(self.ball.exhausted() && !self.ball.depth.contains_key(&self.start))
|| (self.start_ball.exhausted() && !self.start_ball.depth.contains_key(&self.end))
}
fn walk_hops(&mut self, node: NodeId, left: usize) -> Result<Vec<(NodeId, RelId)>> {
match self.ball.recorded_hops(node, left) {
Some(hops) => {
self.search.graph.cancel_tick()?;
self.cut |= !self.ball.exhausted();
Ok(hops)
}
None => self.search.hops(node),
}
}
pub(crate) fn complete(&self) -> bool {
!self.cut
}
fn admit_hop(&mut self, next: NodeId, remaining: u64) -> bool {
let bound = self.ball.lower_bound(next);
let fits = u64::from(bound) <= remaining;
if !fits {
self.cut |= bound != u32::MAX;
}
fits
}
pub(crate) fn each_trail(
&mut self,
length: u32,
mut visit: impl FnMut(&[RelId], &[NodeId]) -> Result<bool>,
) -> Result<bool> {
self.balance(length)?;
self.cut = true;
if self.unreachable() {
return Ok(false);
}
let length = length as usize;
let mut walk = TrailState::at(self.start, length);
if length == 0 {
return if self.start == self.end {
visit(&walk.trail, &walk.nodes)
} else {
Ok(false)
};
}
self.cut = false;
let mut frames = vec![Frame {
hops: self.walk_hops(self.start, length)?,
next: 0,
}];
while let Some(frame) = frames.last_mut() {
let Some(&(next, rid)) = frame.hops.get(frame.next) else {
frames.pop();
walk.leave();
continue;
};
frame.next += 1;
let at = walk.trail.len() + 1;
let remaining = (length - at) as u64;
let closing = walk.closing();
if !walk.enter(rid, next) {
continue;
}
if !self.admit_hop(next, remaining) {
walk.leave();
continue;
}
if closing {
self.cut = true;
let stop = visit(&walk.trail, &walk.nodes);
walk.leave();
if stop? {
return Ok(true);
}
continue;
}
frames.push(Frame {
hops: self.walk_hops(next, length - at)?,
next: 0,
});
}
Ok(false)
}
}