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/tests/no_alloc.rs

//! Queries allocate nothing: every index answers with the heap untouched once built.

#![allow(unsafe_code)]

use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;

use kleene_index::{AddrColumn, Groups, Intervals, Nesting, ParentTree, Reach, ReverseReach};
use kleene_sparse::CpuDevice;

struct Counting;

thread_local! {
    static COUNT: Cell<usize> = const { Cell::new(0) };
}

// SAFETY: forwards to the system allocator; only counts.
unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, l: Layout) -> *mut u8 {
        COUNT.with(|c| c.set(c.get() + 1));
        unsafe { System.alloc(l) }
    }
    unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
        unsafe { System.dealloc(p, l) }
    }
    unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
        COUNT.with(|c| c.set(c.get() + 1));
        unsafe { System.realloc(p, l, n) }
    }
}

#[global_allocator]
static A: Counting = Counting;

fn allocations_in(f: impl FnOnce()) -> usize {
    let before = COUNT.with(Cell::get);
    f();
    COUNT.with(Cell::get) - before
}

#[test]
fn queries_allocate_nothing() {
    let n = 20_000u32;
    // a chain with shortcuts and one cycle
    let mut off = vec![0u64];
    let mut adj = Vec::new();
    for v in 0..n {
        let mut row: Vec<u32> = [v / 2, v + 1, v + 7]
            .into_iter()
            .filter(|&w| w < n && w != v)
            .collect();
        row.dedup();
        adj.extend(row);
        off.push(adj.len() as u64);
    }
    let starts: Vec<u64> = (0..u64::from(n)).map(|k| 0x40_0000 + 32 * k).collect();
    let ends: Vec<u64> = starts.iter().map(|&s| s + 20).collect();
    let addr = AddrColumn::build(starts.clone().into(), Some(ends.clone().into())).unwrap();
    let look = addr.lookup().unwrap();
    let reach = Reach::build(&off, &adj).unwrap();
    let rr = ReverseReach::build(&off, &adj, &[vec![5], vec![9, 900]]).unwrap();
    let tree = ParentTree::build(
        off.clone().into(),
        adj.clone().into(),
        0,
        &CpuDevice::new(1),
    )
    .unwrap();
    let parent: Vec<u32> = (0..n)
        .map(|i| if i == 0 { u32::MAX } else { i / 2 })
        .collect();
    let nest = Nesting::from_parents(&parent).unwrap();
    let ids: Vec<u32> = (0..n).collect();
    let ivl = Intervals::build(&starts, &ends, &ids).unwrap();
    let groups = Groups::build(&vec![1; n as usize], &starts, &ids).unwrap();

    let qs: Vec<u64> = (0..4096u64).map(|k| 0x40_0000 + 37 * k).collect();
    let mut out = vec![None; qs.len()];
    let mut path = Vec::with_capacity(n as usize);
    let mut hits = Vec::with_capacity(64);
    // the first call settles the search tree's one-time SIMD choice
    // (an address inside the span: one below it never reaches the tree)
    let _ = look.floor(starts[1]);
    let mut sink = 0u64;
    let got = allocations_in(|| {
        for &q in &qs {
            sink += u64::from(look.floor(q).unwrap_or(0));
            sink += u64::from(look.covering(q).unwrap_or(0));
            sink += u64::from(look.exact(q).unwrap_or(0));
            hits.clear();
            ivl.stab_into(q, &mut hits);
            sink += hits.len() as u64;
            sink += groups.get(1, q).len() as u64;
        }
        look.floor_batch(&qs, &mut out);
        look.covering_batch(&qs, &mut out);
        for a in (0..n).step_by(97) {
            for b in (0..n).step_by(101) {
                sink += u64::from(reach.reaches(a, b));
                sink += u64::from(nest.inside(a, b));
            }
            sink += u64::from(rr.reaches(a, 1));
            sink += tree.why(a).count() as u64;
            sink += u64::from(tree.path_into(a, &mut path));
        }
        sink += rr.who(0).map(u64::from).sum::<u64>();
    });
    assert!(sink > 0);
    assert_eq!(got, 0, "queries allocated");
}