Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-index/src/nest.rs

//! Nesting: pre/post-order numbers over a forest (is A inside B: two compares) and a static
//! interval tree (which ranges cover an address).

use arrow_buffer::ScalarBuffer;

use crate::error::{Result, bad};

/// Pre- and post-order numbers of a forest given by a parent per node, one word per node
/// (`pre << 32 | post`) so a query reads one word of each node.
#[derive(Clone, Debug)]
pub struct Nesting {
    order: ScalarBuffer<u64>,
}

impl Nesting {
    /// Number the forest whose node `i` has parent `parent[i]`; a node is a root when its
    /// parent is itself or not a node (`>= parent.len()`). Children are visited in rising
    /// order. A cycle is refused.
    pub fn from_parents(parent: &[u32]) -> Result<Self> {
        let n = parent.len();
        if u32::try_from(n).is_err() {
            return Err(bad("more than 2^32 nodes"));
        }
        let is_root = |i: usize| parent[i] as usize >= n || parent[i] as usize == i;
        // children grouped by parent (counting sort keeps them rising)
        let mut off = vec![0u32; n + 1];
        for i in 0..n {
            if !is_root(i) {
                off[parent[i] as usize + 1] += 1;
            }
        }
        for i in 0..n {
            off[i + 1] += off[i];
        }
        let mut kids = vec![0u32; off[n] as usize];
        let mut fill = off.clone();
        for (i, &p) in parent.iter().enumerate() {
            if !is_root(i) {
                let p = p as usize;
                kids[fill[p] as usize] = i as u32;
                fill[p] += 1;
            }
        }
        const NONE: u32 = u32::MAX;
        let mut pre = vec![NONE; n];
        let mut post = vec![NONE; n];
        let (mut next_pre, mut next_post) = (0u32, 0u32);
        // (node, next child slot)
        let mut stack: Vec<(u32, u32)> = Vec::new();
        for r in (0..n).filter(|&i| is_root(i)) {
            pre[r] = next_pre;
            next_pre += 1;
            stack.push((r as u32, off[r]));
            while let Some(top) = stack.last_mut() {
                let v = top.0 as usize;
                if top.1 < off[v + 1] {
                    let c = kids[top.1 as usize];
                    top.1 += 1;
                    pre[c as usize] = next_pre;
                    next_pre += 1;
                    stack.push((c, off[c as usize]));
                } else {
                    post[v] = next_post;
                    next_post += 1;
                    stack.pop();
                }
            }
        }
        if next_pre as usize != n {
            return Err(bad(format!(
                "{} of {n} nodes lie on a parent cycle",
                n - next_pre as usize
            )));
        }
        let order: Vec<u64> = pre
            .iter()
            .zip(&post)
            .map(|(&a, &b)| u64::from(a) << 32 | u64::from(b))
            .collect();
        Ok(Nesting {
            order: order.into(),
        })
    }

    /// Numbers from their stored words (as [`Nesting::words`] gave them).
    pub fn from_parts(order: ScalarBuffer<u64>) -> Result<Self> {
        Ok(Nesting { order })
    }

    /// `pre << 32 | post` per node.
    pub fn words(&self) -> &ScalarBuffer<u64> {
        &self.order
    }

    /// The pre-order number of `v`.
    pub fn pre(&self, v: u32) -> u32 {
        (self.order[v as usize] >> 32) as u32
    }

    /// The post-order number of `v`.
    pub fn post(&self, v: u32) -> u32 {
        self.order[v as usize] as u32
    }

    /// Whether `a` lies inside `b` (`b` is `a` or one of its ancestors).
    #[inline]
    pub fn inside(&self, a: u32, b: u32) -> bool {
        let (a, b) = (self.order[a as usize], self.order[b as usize]);
        b >> 32 <= a >> 32 && a as u32 <= b as u32
    }
}

/// Half-open ranges `start..end`, each with an id, in a static interval tree: the ranges
/// sorted by start, and over them an implicit balanced tree whose node (the middle of its
/// span) knows the largest end in its span.
#[derive(Clone, Debug)]
pub struct Intervals {
    starts: ScalarBuffer<u64>,
    ends: ScalarBuffer<u64>,
    ids: ScalarBuffer<u32>,
    max_end: ScalarBuffer<u64>,
}

impl Intervals {
    /// The tree over `(starts[k]..ends[k], ids[k])`; empty ranges are kept but cover
    /// nothing.
    pub fn build(starts: &[u64], ends: &[u64], ids: &[u32]) -> Result<Self> {
        if starts.len() != ends.len() || starts.len() != ids.len() {
            return Err(bad("interval columns of unequal length"));
        }
        let mut order: Vec<u32> = (0..starts.len() as u32).collect();
        order.sort_unstable_by_key(|&k| (starts[k as usize], ends[k as usize], ids[k as usize]));
        let pick = |c: &[u64]| -> Vec<u64> { order.iter().map(|&k| c[k as usize]).collect() };
        let s = pick(starts);
        let e = pick(ends);
        let i: Vec<u32> = order.iter().map(|&k| ids[k as usize]).collect();
        let mut max_end = vec![0u64; s.len()];
        fill_max(&e, &mut max_end, 0, s.len());
        Ok(Intervals {
            starts: s.into(),
            ends: e.into(),
            ids: i.into(),
            max_end: max_end.into(),
        })
    }

    /// A tree from its stored parts (as [`Intervals::parts`] gave them).
    pub fn from_parts(
        starts: ScalarBuffer<u64>,
        ends: ScalarBuffer<u64>,
        ids: ScalarBuffer<u32>,
        max_end: ScalarBuffer<u64>,
    ) -> Result<Self> {
        let n = starts.len();
        if ends.len() != n || ids.len() != n || max_end.len() != n {
            return Err(bad("interval parts of unequal length"));
        }
        Ok(Intervals {
            starts,
            ends,
            ids,
            max_end,
        })
    }

    /// Starts, ends, ids (sorted by start) and the largest end below each tree node.
    pub fn parts(&self) -> IntervalParts<'_> {
        IntervalParts {
            starts: &self.starts,
            ends: &self.ends,
            ids: &self.ids,
            max_end: &self.max_end,
        }
    }

    /// The number of ranges.
    pub fn len(&self) -> usize {
        self.starts.len()
    }

    /// Whether there are no ranges.
    pub fn is_empty(&self) -> bool {
        self.starts.is_empty()
    }

    /// Call `f(id)` for every range holding `x`, in order of start.
    #[inline]
    pub fn stab(&self, x: u64, mut f: impl FnMut(u32)) {
        self.visit(x, 0, self.starts.len(), &mut f);
    }

    /// The ids of the ranges holding `x`, in order of start, appended to `out` (reused
    /// storage: no allocation once it has grown).
    pub fn stab_into(&self, x: u64, out: &mut Vec<u32>) {
        self.stab(x, |id| out.push(id));
    }

    fn visit(&self, x: u64, lo: usize, hi: usize, f: &mut impl FnMut(u32)) {
        if lo >= hi {
            return;
        }
        let mid = lo + (hi - lo) / 2;
        if self.max_end[mid] <= x {
            return;
        }
        self.visit(x, lo, mid, f);
        if self.starts[mid] <= x {
            if x < self.ends[mid] {
                f(self.ids[mid]);
            }
            self.visit(x, mid + 1, hi, f);
        }
    }
}

/// The stored columns of an [`Intervals`] tree.
#[derive(Clone, Copy, Debug)]
pub struct IntervalParts<'a> {
    /// Starts, rising.
    pub starts: &'a ScalarBuffer<u64>,
    /// The end of each range.
    pub ends: &'a ScalarBuffer<u64>,
    /// The id of each range.
    pub ids: &'a ScalarBuffer<u32>,
    /// The largest end in the span of each tree node.
    pub max_end: &'a ScalarBuffer<u64>,
}

fn fill_max(ends: &[u64], max_end: &mut [u64], lo: usize, hi: usize) -> u64 {
    if lo >= hi {
        return 0;
    }
    let mid = lo + (hi - lo) / 2;
    let m = ends[mid]
        .max(fill_max(ends, max_end, lo, mid))
        .max(fill_max(ends, max_end, mid + 1, hi));
    max_end[mid] = m;
    m
}