Skip to main content

qualia_core_db/q42/field_envelope/
metadata_writer.rs

1//! Caller-buffered canonical TLV grammar, without schema/reference interpretation.
2use super::{align, metadata, Error, Limits};
3
4/// Numeric slices are encoded explicitly little endian, preserving finite bits.
5#[derive(Clone, Copy, Debug)]
6pub enum FieldValue<'a> {
7    U32(&'a [u32]),
8    U64(&'a [u64]),
9    I64(&'a [i64]),
10    F32(&'a [f32]),
11    F64(&'a [f64]),
12    Utf8(&'a str),
13    Bytes(&'a [u8]),
14    MetadataRefs(&'a [u32]),
15    EntryRefs(&'a [u32]),
16    U16(&'a [u16]),
17    I32(&'a [i32]),
18    /// Exact primitive/unknown wire value. Known tags obey the same primitive rules
19    /// as typed variants; unknown tags stay bounded uninterpreted bytes. Critical
20    /// unknown semantics still require rejection by the family semantic adapter.
21    Raw {
22        type_tag: u8,
23        element_count: u32,
24        bytes: &'a [u8],
25    },
26}
27impl FieldValue<'_> {
28    fn layout(self) -> Result<(u8, u32, usize), Error> {
29        let (tag, count, width) = match self {
30            Self::U32(v) => (1, v.len(), 4),
31            Self::U64(v) => (2, v.len(), 8),
32            Self::I64(v) => (3, v.len(), 8),
33            Self::F32(v) => (4, v.len(), 4),
34            Self::F64(v) => (5, v.len(), 8),
35            Self::Utf8(v) => (6, v.len(), 1),
36            Self::Bytes(v) => (7, v.len(), 1),
37            Self::MetadataRefs(v) => (8, v.len(), 4),
38            Self::EntryRefs(v) => (9, v.len(), 4),
39            Self::U16(v) => (10, v.len(), 2),
40            Self::I32(v) => (11, v.len(), 4),
41            Self::Raw {
42                type_tag,
43                element_count,
44                bytes,
45            } => {
46                u32::try_from(bytes.len()).map_err(|_| Error::Overflow)?;
47                return Ok((type_tag, element_count, bytes.len()));
48            }
49        };
50        let n = u32::try_from(count).map_err(|_| Error::Overflow)?;
51        let bytes = count.checked_mul(width).ok_or(Error::Overflow)?;
52        u32::try_from(bytes).map_err(|_| Error::Overflow)?;
53        Ok((tag, n, bytes))
54    }
55    fn validate(self, limits: Limits) -> Result<(), Error> {
56        match self {
57            Self::F32(v) => {
58                if v.iter().any(|x| !x.is_finite()) {
59                    return Err(Error::Numeric);
60                }
61            }
62            Self::F64(v) => {
63                if v.iter().any(|x| !x.is_finite()) {
64                    return Err(Error::Numeric);
65                }
66            }
67            Self::Utf8(v) => metadata::validate_primitive(
68                6,
69                u32::try_from(v.len()).map_err(|_| Error::Overflow)?,
70                v.as_bytes(),
71                limits,
72            )?,
73            Self::Raw {
74                type_tag,
75                element_count,
76                bytes,
77            } => metadata::validate_primitive(type_tag, element_count, bytes, limits)?,
78            _ => {}
79        }
80        Ok(())
81    }
82    fn write(self, out: &mut [u8]) {
83        macro_rules! le {
84            ($values:expr,$width:expr) => {
85                for (dst, value) in out.chunks_exact_mut($width).zip($values) {
86                    dst.copy_from_slice(&value.to_le_bytes());
87                }
88            };
89        }
90        match self {
91            Self::U32(v) | Self::MetadataRefs(v) | Self::EntryRefs(v) => le!(v, 4),
92            Self::U64(v) => le!(v, 8),
93            Self::I64(v) => le!(v, 8),
94            Self::F32(v) => le!(v, 4),
95            Self::F64(v) => le!(v, 8),
96            Self::U16(v) => le!(v, 2),
97            Self::I32(v) => le!(v, 4),
98            Self::Utf8(v) => out.copy_from_slice(v.as_bytes()),
99            Self::Bytes(v) => out.copy_from_slice(v),
100            Self::Raw { bytes, .. } => out.copy_from_slice(bytes),
101        }
102    }
103}
104#[derive(Clone, Copy, Debug)]
105pub struct FieldInput<'a> {
106    pub key: u16,
107    pub flags: u8,
108    pub value: FieldValue<'a>,
109}
110#[derive(Clone, Copy, Debug)]
111pub struct BlockInput<'a> {
112    pub id: u32,
113    pub schema_type: u16,
114    pub revision: u16,
115    pub flags: u32,
116    pub fields: &'a [FieldInput<'a>],
117}
118#[derive(Clone, Copy, Debug)]
119pub struct MetadataInput<'a> {
120    pub blocks: &'a [BlockInput<'a>],
121}
122fn field_len(field: FieldInput<'_>) -> Result<usize, Error> {
123    let n = align(field.value.layout()?.2 as u64, 8)?
124        .checked_add(16)
125        .ok_or(Error::Overflow)?;
126    usize::try_from(n).map_err(|_| Error::Extent)
127}
128fn body_len(block: BlockInput<'_>) -> Result<usize, Error> {
129    let mut n = 0usize;
130    for field in block.fields {
131        n = n.checked_add(field_len(*field)?).ok_or(Error::Overflow)?;
132    }
133    u32::try_from(n).map_err(|_| Error::Overflow)?;
134    Ok(n)
135}
136impl MetadataInput<'_> {
137    /// Validate complete input, canonical nonzero ID/key ordering, bounds, primitive
138    /// sizes/finiteness and UTF-8 before output is touched. This enforces metadata,
139    /// block, field and string limits; unrelated file/payload limits belong to the
140    /// enclosing EnvelopeInput. No allocations or semantic schema admission.
141    pub fn encoded_len(&self, limits: Limits) -> Result<usize, Error> {
142        if self.blocks.len() as u64 > u64::from(limits.blocks) {
143            return Err(Error::Limit);
144        }
145        let mut previous = 0u32;
146        let mut len = 0usize;
147        for b in self.blocks {
148            if b.id <= previous || b.flags & !1 != 0 {
149                return Err(Error::Metadata);
150            }
151            previous = b.id;
152            if b.fields.len() as u64 > u64::from(limits.fields_per_block) {
153                return Err(Error::Limit);
154            }
155            let mut key = 0u16;
156            for f in b.fields {
157                if f.key <= key || f.flags & !1 != 0 {
158                    return Err(Error::Metadata);
159                }
160                key = f.key;
161            }
162            let body = body_len(*b)?;
163            len = len
164                .checked_add(16)
165                .and_then(|v| v.checked_add(body))
166                .ok_or(Error::Overflow)?;
167            if len as u64 > limits.metadata_bytes {
168                return Err(Error::Limit);
169            }
170        }
171        // Size admission precedes potentially large float/string scans.
172        for b in self.blocks {
173            for f in b.fields {
174                f.value.validate(limits)?;
175            }
176        }
177        Ok(len)
178    }
179    /// Every error leaves the entire output unchanged. Successful output has zero
180    /// reserved/padding bytes; the unused caller tail is unchanged. Borrowing keeps
181    /// input slices disjoint from mutable output. No hidden staging allocation.
182    pub fn encode_into<'out>(
183        &self,
184        output: &'out mut [u8],
185        limits: Limits,
186    ) -> Result<&'out mut [u8], Error> {
187        let len = self.encoded_len(limits)?;
188        if output.len() < len {
189            return Err(Error::Extent);
190        }
191        let out = &mut output[..len];
192        out.fill(0);
193        let mut cursor = 0usize;
194        for b in self.blocks {
195            let body = body_len(*b).expect("prevalidated metadata layout");
196            out[cursor..cursor + 4].copy_from_slice(&b.id.to_le_bytes());
197            out[cursor + 4..cursor + 6].copy_from_slice(&b.schema_type.to_le_bytes());
198            out[cursor + 6..cursor + 8].copy_from_slice(&b.revision.to_le_bytes());
199            out[cursor + 8..cursor + 12].copy_from_slice(&(body as u32).to_le_bytes());
200            out[cursor + 12..cursor + 16].copy_from_slice(&b.flags.to_le_bytes());
201            cursor += 16;
202            for f in b.fields {
203                let (tag, count, bytes) = f.value.layout().expect("prevalidated field layout");
204                out[cursor..cursor + 2].copy_from_slice(&f.key.to_le_bytes());
205                out[cursor + 2] = tag;
206                out[cursor + 3] = f.flags;
207                out[cursor + 4..cursor + 8].copy_from_slice(&count.to_le_bytes());
208                out[cursor + 8..cursor + 12].copy_from_slice(&(bytes as u32).to_le_bytes());
209                f.value.write(&mut out[cursor + 16..cursor + 16 + bytes]);
210                cursor += field_len(*f).expect("prevalidated field length");
211            }
212        }
213        Ok(out)
214    }
215}