Skip to main content

qualia_core_db/container_10d/field_section/
checked.rs

1//! Checked, borrowed FIEL v0 declaration/grid inspection. No allocation or casts.
2use super::{
3    FieldRepresentationKind, FieldSupportKind, FieldTypeKind, FIELD_DESCRIPTOR_SIZE,
4    FIELD_SECTION_HEADER_SIZE, FIELD_SECTION_MAGIC, FIELD_SECTION_VERSION,
5};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct FieldInspectionLimits {
9    pub max_payload_bytes: usize,
10    pub max_fields: usize,
11    pub max_samples: usize,
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct FieldInspection {
16    pub fields: usize,
17    pub grid_fields: usize,
18    pub samples: usize,
19    /// Bit n denotes an observed FieldTypeKind discriminant n.
20    pub type_mask: u8,
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum FieldInspectionError {
25    Budget,
26    Header,
27    Descriptor { index: usize },
28    UnsupportedSamples { index: usize },
29    Grid { index: usize },
30    NonFinite { field: usize, sample: usize },
31    UnclaimedBytes,
32}
33impl std::fmt::Display for FieldInspectionError {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        write!(f, "FIEL inspection: {self:?}")
36    }
37}
38impl std::error::Error for FieldInspectionError {}
39
40fn u16_at(data: &[u8], at: usize) -> u16 {
41    u16::from_le_bytes(data[at..at + 2].try_into().expect("checked field bounds"))
42}
43fn u32_at(data: &[u8], at: usize) -> u32 {
44    u32::from_le_bytes(data[at..at + 4].try_into().expect("checked field bounds"))
45}
46fn u64_at(data: &[u8], at: usize) -> u64 {
47    u64::from_le_bytes(data[at..at + 8].try_into().expect("checked field bounds"))
48}
49
50/// Supports the existing declaration-only schema and contiguous scalar/region/
51/// grid samples emitted by `encode_field_section_with_rasters`. Declared units
52/// are retained, not authenticated. Unknown sample schemas, gaps, aliases, tails,
53/// reserved metadata, invalid enums/shape and nonfinite samples fail closed.
54/// Unaligned input follows the same LE path. No output is mutated on error.
55pub fn inspect_field_section(
56    bytes: &[u8],
57    limits: FieldInspectionLimits,
58) -> Result<FieldInspection, FieldInspectionError> {
59    if bytes.len() > limits.max_payload_bytes {
60        return Err(FieldInspectionError::Budget);
61    }
62    if bytes.len() < FIELD_SECTION_HEADER_SIZE
63        || u32_at(bytes, 0) != FIELD_SECTION_MAGIC
64        || u16_at(bytes, 4) != FIELD_SECTION_VERSION
65        || u32_at(bytes, 8) != 0
66    {
67        return Err(FieldInspectionError::Header);
68    }
69    let fields = usize::from(u16_at(bytes, 6));
70    if fields > limits.max_fields {
71        return Err(FieldInspectionError::Budget);
72    }
73    let table_end = FIELD_SECTION_HEADER_SIZE + fields * FIELD_DESCRIPTOR_SIZE;
74    if table_end > bytes.len() {
75        return Err(FieldInspectionError::Header);
76    }
77    let mut occupied_end = table_end;
78    let mut samples = 0usize;
79    let mut grid_fields = 0;
80    let mut type_mask = 0;
81    for index in 0..fields {
82        let at = FIELD_SECTION_HEADER_SIZE + index * FIELD_DESCRIPTOR_SIZE;
83        let d = &bytes[at..at + FIELD_DESCRIPTOR_SIZE];
84        if FieldTypeKind::from_u8(d[16]).is_none()
85            || FieldSupportKind::from_u8(d[17]).is_none()
86            || FieldRepresentationKind::from_u8(d[18]).is_none()
87            || d[19] != 0
88            || u32_at(d, 20) != 0
89        {
90            return Err(FieldInspectionError::Descriptor { index });
91        }
92        type_mask |= 1 << d[16];
93        let raw_offset = u64_at(d, 24);
94        if raw_offset == 0 {
95            continue;
96        }
97        if d[16] != FieldTypeKind::Scalar as u8
98            || d[17] != FieldSupportKind::Region as u8
99            || d[18] != FieldRepresentationKind::Grid as u8
100        {
101            return Err(FieldInspectionError::UnsupportedSamples { index });
102        }
103        let offset =
104            usize::try_from(raw_offset).map_err(|_| FieldInspectionError::Grid { index })?;
105        // Sequential samples exclude overlap, reinterpretation of descriptors,
106        // unclaimed bytes, and aliases between different fields.
107        if offset != occupied_end {
108            return Err(FieldInspectionError::Grid { index });
109        }
110        let meta_end = offset
111            .checked_add(16)
112            .filter(|end| *end <= bytes.len())
113            .ok_or(FieldInspectionError::Grid { index })?;
114        let width = u32_at(bytes, offset);
115        let height = u32_at(bytes, offset + 4);
116        let count = u32_at(bytes, offset + 8) as usize;
117        if width == 0
118            || height == 0
119            || width.checked_mul(height).map(|n| n as usize) != Some(count)
120            || u32_at(bytes, offset + 12) != 0
121        {
122            return Err(FieldInspectionError::Grid { index });
123        }
124        samples = samples
125            .checked_add(count)
126            .ok_or(FieldInspectionError::Budget)?;
127        if samples > limits.max_samples {
128            return Err(FieldInspectionError::Budget);
129        }
130        let end = count
131            .checked_mul(4)
132            .and_then(|n| meta_end.checked_add(n))
133            .filter(|end| *end <= bytes.len())
134            .ok_or(FieldInspectionError::Grid { index })?;
135        for (sample, raw) in bytes[meta_end..end].chunks_exact(4).enumerate() {
136            if !f32::from_le_bytes(raw.try_into().expect("four byte chunk")).is_finite() {
137                return Err(FieldInspectionError::NonFinite {
138                    field: index,
139                    sample,
140                });
141            }
142        }
143        occupied_end = end;
144        grid_fields += 1;
145    }
146    if occupied_end != bytes.len() {
147        return Err(FieldInspectionError::UnclaimedBytes);
148    }
149    Ok(FieldInspection {
150        fields,
151        grid_fields,
152        samples,
153        type_mask,
154    })
155}
156
157#[cfg(test)]
158#[path = "checked/tests.rs"]
159mod tests;