Skip to main content

uqa_execution/query/document_changes/
desired.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Budgeted private identity selection preserves the last evaluated change per row.
8
9use uqa_core::{memory::BudgetedVec, DocId};
10use uqa_storage::{read_control::StorageReadControl, StorageBackendResult};
11
12pub struct DocumentSelection {
13    rows: BudgetedVec<(DocId, bool, usize)>,
14}
15
16impl DocumentSelection {
17    pub fn new(control: &StorageReadControl) -> Self {
18        Self {
19            rows: BudgetedVec::new(control.memory()),
20        }
21    }
22
23    pub fn insert(
24        &mut self,
25        id: DocId,
26        present: bool,
27        control: &StorageReadControl,
28    ) -> StorageBackendResult<()> {
29        control.check()?;
30        self.rows.push((id, present, self.rows.len()))?;
31        Ok(())
32    }
33
34    pub fn is_empty(&self) -> bool {
35        self.rows.is_empty()
36    }
37
38    pub(super) fn finish(mut self, control: &StorageReadControl) -> StorageBackendResult<Self> {
39        control.check()?;
40        self.rows
41            .sort_unstable_by_key(|(id, _, order)| (*id, *order));
42        let mut write = 0;
43        for read in 0..self.rows.len() {
44            control.check()?;
45            let row = self.rows[read];
46            if write != 0 && self.rows[write - 1].0 == row.0 {
47                self.rows[write - 1] = row;
48            } else {
49                self.rows[write] = row;
50                write += 1;
51            }
52        }
53        self.rows.truncate(write);
54        Ok(self)
55    }
56
57    pub(super) fn entries(&self) -> impl Iterator<Item = (DocId, bool)> + '_ {
58        self.rows.iter().map(|(id, present, _)| (*id, *present))
59    }
60}