use relate_core::tokens::WorkspaceCharge;
use relate_core::{Error, NodeId, Result};
use super::Search;
pub(crate) const LANES: usize = 64;
const MAX_SPAN: usize = 1 << 23;
const BYTES_PER_ID: u64 = 41;
#[cfg(test)]
thread_local! {
static SPAN_CAP: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}
fn span_cap() -> usize {
#[cfg(test)]
if let Some(cap) = SPAN_CAP.with(std::cell::Cell::get) {
return cap;
}
MAX_SPAN
}
#[cfg(test)]
pub(crate) fn with_span_cap<T>(cap: usize, f: impl FnOnce() -> T) -> T {
struct Restore(Option<usize>);
impl Drop for Restore {
fn drop(&mut self) {
SPAN_CAP.with(|c| c.set(self.0));
}
}
let _restore = Restore(SPAN_CAP.with(|c| c.replace(Some(cap))));
f()
}
impl Search<'_, '_> {
pub(crate) fn sweep_fits(&self) -> bool {
usize::try_from(self.graph.node_id_bound()).is_ok_and(|span| span <= span_cap())
}
pub(crate) fn sweep_levels(
&self,
origins: &[NodeId],
active: u64,
targets: &[NodeId],
mut on_level: impl FnMut(u32, &[(NodeId, u64)]) -> Result<u64>,
) -> Result<()> {
debug_assert!(origins.len() <= LANES && self.sweep_fits());
let span = slot_of(self.graph.node_id_bound())?;
let _charge = WorkspaceCharge::retain_with(|| {
u64::try_from(span).map_or(u64::MAX, |n| n.saturating_mul(BYTES_PER_ID))
})?;
let mut sweep = Sweep::seed(self, span, origins, active, targets)?;
let mut depth = 0;
while sweep.active != 0 && !sweep.frontier_nodes.is_empty() && depth < self.max {
if depth + 1 == self.max {
sweep.pull_final()?;
} else {
sweep.push_level()?;
}
depth += 1;
if !sweep.reached.is_empty() {
sweep.active &= !on_level(depth, &sweep.reached)?;
}
}
Ok(())
}
}
struct Sweep<'s, 'a, 'g> {
search: &'s Search<'a, 'g>,
back: Search<'a, 'g>,
span: usize,
targets: &'s [NodeId],
target_bits: Vec<u64>,
visited: Vec<u64>,
frontier: Vec<u64>,
next: Vec<u64>,
frontier_nodes: Vec<NodeId>,
next_nodes: Vec<NodeId>,
reached: Vec<(NodeId, u64)>,
active: u64,
}
impl<'s, 'a, 'g> Sweep<'s, 'a, 'g> {
fn seed(
search: &'s Search<'a, 'g>,
span: usize,
origins: &[NodeId],
active: u64,
targets: &'s [NodeId],
) -> Result<Self> {
let mut target_bits = vec![0u64; span.div_ceil(64)];
for &target in targets {
let at = slot_in(target, span)?;
target_bits[at / 64] |= 1 << (at % 64);
}
let mut sweep = Self {
search,
back: search.reversed(),
span,
targets,
target_bits,
visited: vec![0u64; span],
frontier: vec![0u64; span],
next: vec![0u64; span],
frontier_nodes: Vec::new(),
next_nodes: Vec::new(),
reached: Vec::new(),
active,
};
for (lane, &origin) in origins.iter().enumerate() {
if active & (1 << lane) == 0 {
continue;
}
let at = slot_in(origin, span)?;
sweep.visited[at] |= 1 << lane;
if sweep.frontier[at] == 0 {
sweep.frontier_nodes.push(origin);
}
sweep.frontier[at] |= 1 << lane;
}
Ok(sweep)
}
fn pull_final(&mut self) -> Result<()> {
self.reached.clear();
for &target in self.targets {
self.search.graph.cancel_tick()?;
let at = slot_in(target, self.span)?;
let mut lanes = 0;
self.back.each_hop(target, |peer, _| {
lanes |= self.frontier[slot_in(peer, self.span)?];
Ok(())
})?;
lanes &= self.active & !self.visited[at];
if lanes != 0 {
self.reached.push((target, lanes));
}
}
Ok(())
}
fn push_level(&mut self) -> Result<()> {
for &node in &self.frontier_nodes {
self.search.graph.cancel_tick()?;
let lanes = self.frontier[slot_in(node, self.span)?] & self.active;
if lanes == 0 {
continue;
}
self.search.each_hop(node, |peer, _| {
let at = slot_in(peer, self.span)?;
let fresh = lanes & !self.visited[at];
if fresh != 0 {
if self.next[at] == 0 {
self.next_nodes.push(peer);
}
self.next[at] |= fresh;
}
Ok(())
})?;
}
for &node in &self.frontier_nodes {
self.frontier[slot_in(node, self.span)?] = 0;
}
self.frontier_nodes.clear();
self.reached.clear();
for &node in &self.next_nodes {
let at = slot_in(node, self.span)?;
let lanes = std::mem::take(&mut self.next[at]) & self.active;
if lanes == 0 {
continue;
}
self.visited[at] |= lanes;
self.frontier[at] = lanes;
self.frontier_nodes.push(node);
if self.target_bits[at / 64] & (1 << (at % 64)) != 0 {
self.reached.push((node, lanes));
}
}
self.next_nodes.clear();
Ok(())
}
}
fn slot_of(id: NodeId) -> Result<usize> {
usize::try_from(id).map_err(|_| Error::internal("multi-source sweep: negative node id"))
}
fn slot_in(id: NodeId, span: usize) -> Result<usize> {
match slot_of(id)? {
at if at < span => Ok(at),
_ => Err(Error::internal(
"multi-source sweep: node id past the view's id bound",
)),
}
}