use std::cell::Cell;
use relate_core::NodeId;
const MAX_SPAN: usize = 1 << 26;
fn index(id: NodeId) -> usize {
usize::try_from(id).expect("node ids are non-negative")
}
pub(super) struct FarSet {
words: Vec<u64>,
len: usize,
}
impl FarSet {
pub(super) fn of(ids: &[NodeId]) -> Option<Self> {
let words = ids.iter().map(|&id| index(id) / 64 + 1).max().unwrap_or(0);
if words * 64 > MAX_SPAN {
return None;
}
let mut set = Self {
words: vec![0; words],
len: 0,
};
for &id in ids {
let (word, bit) = (index(id) / 64, index(id) % 64);
set.len += usize::from(set.words[word] & (1 << bit) == 0);
set.words[word] |= 1 << bit;
}
Some(set)
}
pub(super) fn len(&self) -> usize {
self.len
}
pub(super) fn ids(&self) -> Vec<NodeId> {
let mut ids = Vec::with_capacity(self.len);
for (word_at, &word) in self.words.iter().enumerate() {
let mut rest = word;
while rest != 0 {
let bit = rest.trailing_zeros() as usize;
rest &= rest - 1;
ids.push(NodeId::try_from(word_at * 64 + bit).expect("a node id fits NodeId"));
}
}
ids
}
pub(super) fn contains(&self, id: NodeId) -> bool {
let index = index(id);
self.words
.get(index / 64)
.is_some_and(|word| word & (1 << (index % 64)) != 0)
}
}
pub(super) struct Settled<'f> {
counts: Vec<Cell<usize>>,
far: &'f FarSet,
}
impl<'f> Settled<'f> {
pub(super) fn new(lanes: usize, far: &'f FarSet) -> Self {
Self {
counts: vec![Cell::new(0); lanes],
far,
}
}
pub(super) fn settle(&self, lane: usize) {
self.counts[lane].set(self.counts[lane].get() + 1);
}
pub(super) fn done(&self, lane: usize) -> bool {
self.counts[lane].get() == self.far.len()
}
pub(super) fn settle_if_hit(&self, lane: usize, node: NodeId) -> bool {
if !self.far.contains(node) {
return false;
}
self.settle(lane);
true
}
}
pub(super) struct OneLane<'f>(Settled<'f>);
impl<'f> OneLane<'f> {
pub(super) fn new(far: &'f FarSet) -> Self {
Self(Settled::new(1, far))
}
pub(super) fn settle_if_hit(&self, node: NodeId) -> bool {
self.0.settle_if_hit(0, node)
}
pub(super) fn done(&self) -> bool {
self.0.done(0)
}
}
pub(super) fn retires(done: bool, first_layer_only: bool, productive: bool) -> bool {
done || (first_layer_only && productive)
}
#[cfg(test)]
mod tests {
use super::FarSet;
#[test]
fn membership_len_and_out_of_range() {
let set = FarSet::of(&[3, 64, 3, 130]).unwrap();
assert_eq!(set.len(), 3);
assert_eq!(set.ids(), vec![3, 64, 130]);
assert!([3, 64, 130].iter().all(|&id| set.contains(id)));
assert!(![0, 4, 63, 65, 131, 100_000]
.iter()
.any(|&id| set.contains(id)));
let empty = FarSet::of(&[]).unwrap();
assert_eq!(empty.len(), 0);
assert!(!empty.contains(0));
assert!(FarSet::of(&[1 << 40]).is_none());
}
}