Skip to main content

qualia_core_db/bundle/stream/formats/
emf.rs

1use super::{
2    range::{extent, nonoverlap, overlap},
3    AuthenticatedRange, FormatError as E, FormatLimits, PayloadInterval,
4};
5use crate::q42::{
6    chunk_integrity::{verify_blake3_trailer, BLAKE3_TRAILER_BYTES},
7    emf_container::{
8        chunk_directory::{EmfChunkDirectoryEntry, CHUNK_DIRECTORY_ENTRY_BYTES},
9        header::{
10            EmfCellRecord64, EmfContainerHeader, EMF_CHUNK_FLAG_BLAKE3_FULL, EMF_CONTAINER_VERSION,
11        },
12    },
13};
14/// Authenticated complete v2 directory with global payload extent consistency.
15/// V3 interpretation/PCM closure is exposed separately by EmfV3DirectoryView.
16pub struct EmfDirectoryView<'a> {
17    header: EmfContainerHeader,
18    directory: AuthenticatedRange<'a>,
19    limits: FormatLimits,
20}
21pub struct EmfChunkView<'a> {
22    entry: EmfChunkDirectoryEntry,
23    records: &'a [u8],
24}
25impl<'a> EmfChunkView<'a> {
26    pub const fn entry(&self) -> &EmfChunkDirectoryEntry {
27        &self.entry
28    }
29    pub fn records(&self) -> &'a [u8] {
30        self.records
31    }
32    pub fn cell(&self, index: usize) -> Option<EmfCellRecord64> {
33        let start = index.checked_mul(64)?;
34        let end = start.checked_add(64)?;
35        self.records
36            .get(start..end)
37            .map(bytemuck::pod_read_unaligned)
38    }
39}
40impl<'a> EmfDirectoryView<'a> {
41    pub fn admit(
42        header: AuthenticatedRange<'a>,
43        directory: AuthenticatedRange<'a>,
44        limits: FormatLimits,
45        scratch: &mut [PayloadInterval],
46    ) -> Result<Self, E> {
47        Self::admit_version(header, directory, limits, scratch, EMF_CONTAINER_VERSION)
48    }
49    pub(super) fn admit_version(
50        header: AuthenticatedRange<'a>,
51        directory: AuthenticatedRange<'a>,
52        limits: FormatLimits,
53        scratch: &mut [PayloadInterval],
54        expected_version: u16,
55    ) -> Result<Self, E> {
56        if !cfg!(target_endian = "little") {
57            return Err(E::Unsupported);
58        }
59        if !header.same_entry(&directory) {
60            return Err(E::Identity);
61        }
62        if header.offset() != 0 || header.bytes().len() != 64 {
63            return Err(E::Bounds);
64        }
65        if header.selected().logical_length() > limits.max_entry_bytes {
66            return Err(E::Limit);
67        }
68        let h: EmfContainerHeader = bytemuck::pod_read_unaligned(header.bytes());
69        h.validate().map_err(|_| E::Integrity)?;
70        if h.version != expected_version || h.flags & !7 != 0 {
71            return Err(E::Unsupported);
72        }
73        let count = usize::try_from(h.chunk_count).map_err(|_| E::Limit)?;
74        if count > limits.max_rows || count > 4096 {
75            return Err(E::Limit);
76        }
77        let bytes = count
78            .checked_mul(CHUNK_DIRECTORY_ENTRY_BYTES)
79            .ok_or(E::Bounds)?;
80        if bytes.checked_add(64).ok_or(E::Bounds)? > limits.max_metadata_bytes {
81            return Err(E::Limit);
82        }
83        if scratch.len() < count {
84            return Err(E::Capacity);
85        }
86        let dstart = h.directory_offset;
87        let dend = extent(dstart, bytes as u64, header.selected().logical_length())?;
88        if dstart < 64
89            || dstart % 64 != 0
90            || directory.offset() != dstart
91            || directory.bytes().len() != bytes
92        {
93            return Err(E::Geometry);
94        }
95        for (i, raw) in directory.bytes().chunks_exact(64).enumerate() {
96            let row: EmfChunkDirectoryEntry = bytemuck::pod_read_unaligned(raw);
97            row.validate().map_err(|_| E::Integrity)?;
98            let records = u64::from(row.cell_count).checked_mul(64).ok_or(E::Bounds)?;
99            let length = records
100                .checked_add(BLAKE3_TRAILER_BYTES as u64)
101                .ok_or(E::Bounds)?;
102            if length != u64::from(row.byte_length)
103                || row.flags & EMF_CHUNK_FLAG_BLAKE3_FULL == 0
104                || row.flags & 2 != 0
105                || row.bao_hash_prefix != [0; 16]
106                || row.reserved != [0; 12]
107            {
108                return Err(E::Integrity);
109            }
110            let end = extent(row.byte_offset, length, header.selected().logical_length())?;
111            if row.byte_offset < 64
112                || row.byte_offset % 64 != 0
113                || overlap(row.byte_offset, end, dstart, dend)
114            {
115                return Err(E::Geometry);
116            }
117            scratch[i] = PayloadInterval {
118                start: row.byte_offset,
119                end,
120            };
121        }
122        nonoverlap(&mut scratch[..count])?;
123        Ok(Self {
124            header: h,
125            directory,
126            limits,
127        })
128    }
129    pub const fn header(&self) -> &EmfContainerHeader {
130        &self.header
131    }
132    pub fn selected_chunk(
133        &self,
134        index: usize,
135        payload: AuthenticatedRange<'a>,
136    ) -> Result<EmfChunkView<'a>, E> {
137        if !self.directory.same_entry(&payload) {
138            return Err(E::Identity);
139        }
140        let start = index.checked_mul(64).ok_or(E::Bounds)?;
141        let raw = self
142            .directory
143            .bytes()
144            .get(start..start.checked_add(64).ok_or(E::Bounds)?)
145            .ok_or(E::Bounds)?;
146        let row: EmfChunkDirectoryEntry = bytemuck::pod_read_unaligned(raw);
147        let length = usize::try_from(row.byte_length).map_err(|_| E::Limit)?;
148        if length > self.limits.max_chunk_bytes {
149            return Err(E::Limit);
150        }
151        if payload.offset() != row.byte_offset || payload.bytes().len() != length {
152            return Err(E::Bounds);
153        }
154        let split = length.checked_sub(BLAKE3_TRAILER_BYTES).ok_or(E::Bounds)?;
155        let (records, trailer) = payload.bytes().split_at(split);
156        if !verify_blake3_trailer(records, trailer) {
157            return Err(E::Integrity);
158        }
159        Ok(EmfChunkView {
160            entry: row,
161            records,
162        })
163    }
164}