use relate_core::tokens::WorkspaceCharge;
use relate_core::{NodeId, RelId, Result};
use relate_ir::Direction;
use crate::hash_seed::IdMap;
use crate::UsedSet;
use super::Search;
const ENTRY_BYTES: u64 = 24;
const RECORDED_BYTES: u64 = 2 * ENTRY_BYTES;
#[derive(Default)]
struct HopLog {
into: IdMap<NodeId, Vec<(NodeId, RelId)>>,
count: u64,
}
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);
(self.depth.capacity() as u64 + self.frontier.capacity() as u64)
.saturating_mul(ENTRY_BYTES)
.saturating_add(logged.saturating_mul(RECORDED_BYTES))
})
}
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 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
}
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 used = UsedSet::default();
let mut trail: Vec<RelId> = Vec::with_capacity(length);
let mut nodes: Vec<NodeId> = Vec::with_capacity(length + 1);
nodes.push(self.start);
if length == 0 {
return if self.start == self.end {
visit(&trail, &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();
if let Some(rid) = trail.pop() {
used.remove(&rid);
nodes.pop();
}
continue;
};
frame.next += 1;
let at = trail.len() + 1;
let remaining = (length - at) as u64;
if used.contains(&rid) {
continue;
}
let bound = self.ball.lower_bound(next);
if u64::from(bound) > remaining {
self.cut |= bound != u32::MAX;
continue;
}
if at == length {
self.cut = true;
trail.push(rid);
nodes.push(next);
let stop = visit(&trail, &nodes)?;
trail.pop();
nodes.pop();
if stop {
return Ok(true);
}
continue;
}
used.insert(rid);
trail.push(rid);
nodes.push(next);
frames.push(Frame {
hops: self.walk_hops(next, length - at)?,
next: 0,
});
}
Ok(false)
}
}