use std::cell::RefCell;
pub(crate) struct QueryArena {
pub(crate) scores: Vec<f32>,
pub(crate) doc_generations: Vec<u32>,
pub(crate) generation: u32,
pub(crate) touched: Vec<u32>,
}
impl QueryArena {
pub(crate) const fn new() -> Self {
Self {
scores: Vec::new(),
doc_generations: Vec::new(),
generation: 0,
touched: Vec::new(),
}
}
pub(crate) fn begin_query(&mut self, n_frames: usize) {
if self.scores.len() < n_frames {
self.scores.resize(n_frames, 0.0);
self.doc_generations.resize(n_frames, 0);
}
self.touched.clear();
if self.generation == u32::MAX {
for g in &mut self.doc_generations {
*g = 0;
}
self.generation = 1;
} else {
self.generation += 1;
}
}
#[inline]
pub(crate) fn accumulate(&mut self, idx: usize, delta: f32) {
if self.doc_generations[idx] != self.generation {
self.doc_generations[idx] = self.generation;
self.scores[idx] = delta;
self.touched.push(idx as u32);
} else {
self.scores[idx] += delta;
}
}
}
thread_local! {
static QUERY_ARENA: RefCell<QueryArena> = const { RefCell::new(QueryArena::new()) };
}
pub(crate) fn with_arena<R>(f: impl FnOnce(&mut QueryArena) -> R) -> R {
QUERY_ARENA.with(|cell| f(&mut cell.borrow_mut()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generation_bumps_invalidate_prior_writes() {
let mut a = QueryArena::new();
a.begin_query(8);
a.accumulate(3, 1.5);
a.accumulate(3, 0.5);
assert_eq!(a.scores[3], 2.0);
assert_eq!(a.touched, vec![3]);
a.begin_query(8);
assert!(a.touched.is_empty());
assert_ne!(a.doc_generations[3], a.generation);
}
#[test]
fn buffers_grow_to_largest_request() {
let mut a = QueryArena::new();
a.begin_query(4);
assert!(a.scores.len() >= 4);
a.begin_query(16);
assert!(a.scores.len() >= 16);
a.begin_query(2);
assert!(a.scores.len() >= 16);
}
#[test]
fn generation_wrap_resets_stamps() {
let mut a = QueryArena::new();
a.begin_query(4);
a.generation = u32::MAX;
a.doc_generations.fill(u32::MAX);
a.scores.fill(99.0);
a.begin_query(4);
assert_eq!(a.generation, 1);
assert!(a.doc_generations.iter().all(|&g| g == 0));
}
}