Skip to main content

qualia_core_db/bundle/stream/descriptor/
refs.rs

1//! Borrowed fixed-profile page references in deterministic encoded order.
2use super::cbor::{R, W};
3use super::{DescriptorError as E, PageRef, check_ref, pages_for};
4#[derive(Clone, Copy)]
5pub struct PageRefsView<'a> {
6    encoded: &'a [u8],
7    count: usize,
8}
9impl<'a> PageRefsView<'a> {
10    pub fn len(self) -> usize {
11        self.count
12    }
13    pub fn is_empty(self) -> bool {
14        self.count == 0
15    }
16    pub fn get(self, index: usize) -> Result<PageRef, E> {
17        if index >= self.count {
18            return Err(E::Page);
19        }
20        let mut r = R::new(self.encoded)?;
21        r.array()?;
22        for i in 0..self.count {
23            let row = read_ref(&mut r)?;
24            if i == index {
25                return Ok(row);
26            }
27        }
28        Err(E::Page)
29    }
30    pub fn matches(self, refs: &[PageRef]) -> Result<(), E> {
31        if refs.len() != self.count {
32            return Err(E::Coverage);
33        }
34        for (i, want) in refs.iter().enumerate() {
35            if self.get(i)? != *want {
36                return Err(E::Commitment);
37            }
38        }
39        Ok(())
40    }
41}
42fn read_ref(r: &mut R<'_>) -> Result<PageRef, E> {
43    r.fixed_array(5)?;
44    Ok(PageRef {
45        number: r.u32()?,
46        first: r.u32()?,
47        rows: r.u32()?,
48        encoded_length: r.u32()?,
49        digest: r.digest()?,
50    })
51}
52pub(super) fn read_refs<'a>(r: &mut R<'a>, entries: usize) -> Result<PageRefsView<'a>, E> {
53    let start = r.pos;
54    let count = r.array()?;
55    if count != pages_for(entries)? {
56        return Err(E::Coverage);
57    }
58    for i in 0..count {
59        check_ref(&read_ref(r)?, entries, i)?;
60    }
61    Ok(PageRefsView {
62        encoded: &r.bytes[start..r.pos],
63        count,
64    })
65}
66pub(super) fn write_refs(w: &mut W<'_>, refs: &[PageRef], entries: usize) -> Result<(), E> {
67    if refs.len() != pages_for(entries)? {
68        return Err(E::Coverage);
69    }
70    w.array(refs.len())?;
71    for (i, row) in refs.iter().enumerate() {
72        check_ref(row, entries, i)?;
73        w.array(5)?;
74        w.uint(row.number as u64)?;
75        w.uint(row.first as u64)?;
76        w.uint(row.rows as u64)?;
77        w.uint(row.encoded_length as u64)?;
78        w.bytes(row.digest.as_bytes())?;
79    }
80    Ok(())
81}
82
83impl core::fmt::Debug for PageRefsView<'_> {
84    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
85        f.debug_struct("PageRefsView")
86            .field("count", &self.count)
87            .finish_non_exhaustive()
88    }
89}