Skip to main content

qualia_core_db/bundle/stream/index/
owned.rs

1//! Fallible cold materialization; no serde-owned decode before admission.
2use super::{
3    AdmittedIndex, CheckedHeader, EntryScratch, IndexError, IndexReadLimits, admit_index,
4    measure_index,
5};
6use crate::bundle::BundleEntry;
7
8fn text(value: &str) -> Result<String, IndexError> {
9    let mut out = String::new();
10    out.try_reserve_exact(value.len())
11        .map_err(|_| IndexError::Allocation)?;
12    out.push_str(value);
13    Ok(out)
14}
15fn buffer(len: usize) -> Result<Vec<u8>, IndexError> {
16    let mut out = Vec::new();
17    out.try_reserve_exact(len)
18        .map_err(|_| IndexError::Allocation)?;
19    out.resize(len, 0);
20    Ok(out)
21}
22
23pub fn materialize_entries(
24    index: &AdmittedIndex<'_>,
25    l: IndexReadLimits,
26) -> Result<Vec<BundleEntry>, IndexError> {
27    // A stricter new budget must not bypass validation through an old handle.
28    let sizing = measure_index(&index.header(), index.encoded_bytes(), l)?;
29    let mut out = Vec::new();
30    out.try_reserve_exact(sizing.entry_count())
31        .map_err(|_| IndexError::Allocation)?;
32    for row in index.entries() {
33        let row = row?;
34        let mut sha256 = buffer(32)?;
35        sha256.copy_from_slice(row.sha256());
36        let meta = if let Some(len) = row.metadata_len() {
37            let mut bytes = buffer(len)?;
38            row.copy_metadata_into(&mut bytes)?;
39            Some(bytes)
40        } else {
41            None
42        };
43        out.push(BundleEntry {
44            key: text(row.key())?,
45            kind: text(row.kind())?,
46            offset: row.offset(),
47            length: row.length(),
48            sha256,
49            meta,
50        });
51    }
52    Ok(out)
53}
54
55pub fn decode_owned_index(
56    h: &CheckedHeader,
57    bytes: &[u8],
58    l: IndexReadLimits,
59) -> Result<Vec<BundleEntry>, IndexError> {
60    let sizing = measure_index(h, bytes, l)?;
61    let mut scratch = Vec::new();
62    scratch
63        .try_reserve_exact(sizing.entry_count())
64        .map_err(|_| IndexError::Allocation)?;
65    scratch.resize(sizing.entry_count(), EntryScratch::EMPTY);
66    let index = admit_index(h, bytes, l, &mut scratch)?;
67    // The handle borrows immutable index bytes, not this temporary scratch.
68    drop(scratch);
69    materialize_entries(&index, l)
70}