Skip to main content

qualia_core_db/q42/volume/
cursor.rs

1//! Caller-buffered sequential SuperBlock cursor.
2
3use std::io;
4
5use super::super::{Q42Volume, QUINS_PER_BLOCK, SUPERBLOCK_HEADER, SUPERBLOCK_SIZE};
6
7/// Metadata for one decoded SuperBlock returned by [`Q42BlockCursor`].
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub struct Q42BlockMeta {
10    pub block_index: usize,
11    pub live_quins: usize,
12}
13
14/// Sequential, caller-buffered view of a Q42 volume's SuperBlocks.
15pub struct Q42BlockCursor<'a> {
16    volume: &'a Q42Volume,
17    next_index: usize,
18}
19
20impl<'a> Q42BlockCursor<'a> {
21    /// Creates with the given state.
22    pub(super) fn new(volume: &'a Q42Volume) -> Self {
23        Self {
24            volume,
25            next_index: 0,
26        }
27    }
28
29    /// Decode the next block into `out`.  No block-sized allocation occurs in
30    /// this cursor or the underlying decompressor.
31    pub fn next_into(&mut self, out: &mut [u8]) -> io::Result<Option<Q42BlockMeta>> {
32        if self.next_index >= self.volume.block_count() as usize {
33            return Ok(None);
34        }
35        let block_index = self.next_index;
36        self.next_index += 1;
37        let decoded = self.volume.read_superblock_into(block_index, out)?;
38        if decoded != SUPERBLOCK_SIZE {
39            return Err(io::Error::new(
40                io::ErrorKind::InvalidData,
41                "Q42 block did not decode to a complete SuperBlock",
42            ));
43        }
44        let live_quins = u64::from_le_bytes(out[16..24].try_into().unwrap()) as usize;
45        if live_quins > QUINS_PER_BLOCK {
46            return Err(io::Error::new(
47                io::ErrorKind::InvalidData,
48                "Q42 SuperBlock declares more live Quins than its ledger holds",
49            ));
50        }
51        if SUPERBLOCK_HEADER + live_quins * crate::q42_volume::QUIN_SIZE > SUPERBLOCK_SIZE {
52            return Err(io::Error::new(
53                io::ErrorKind::InvalidData,
54                "Q42 SuperBlock live Quin count exceeds its decoded bounds",
55            ));
56        }
57        Ok(Some(Q42BlockMeta {
58            block_index,
59            live_quins,
60        }))
61    }
62
63    #[inline]
64    /// `Q42BlockCursor::next_index`.
65    pub fn next_index(&self) -> usize {
66        self.next_index
67    }
68}
69
70impl Q42Volume {
71    /// Return a sequential cursor which decodes into a caller-owned buffer.
72    pub fn block_cursor(&self) -> Q42BlockCursor<'_> {
73        Q42BlockCursor::new(self)
74    }
75}