Skip to main content

qualia_core_db/sensing/container/
assemble.rs

1//! Caller-buffered authoring of a minimal sensing envelope.
2use super::super::record::MeasurementRecord;
3use super::{
4    RegistrationError, SensingContainerError, SensingIndexProfile, MAX_SENSING_PROFILE_EXTENSIONS,
5};
6use crate::container_10d::{
7    encode_container_with_manifold_identity_extensions,
8    manifold_identity_container::ManifoldContainerError,
9    manifold_identity_v2::MANIFOLD_IDENTITY_V2_MAX_FIELDS, AlignmentTier, Container10dHeader,
10    ManifoldIdentityV2, SectionInput, SectionType, TypedFieldRecord,
11};
12
13#[derive(Debug)]
14pub enum SensingAssemblyError {
15    DeclarationMismatch,
16    Capacity,
17    Index(SensingContainerError),
18    Registration(RegistrationError),
19    Envelope(ManifoldContainerError),
20}
21
22/// Assemble a new envelope containing FieldSidecar and MID2 sections. All raw
23/// fields must refer to the supplied prefix; this does not rewrite an existing
24/// container or preserve other sections. Identity, namespaces and metadata are
25/// explicit caller declarations, not verified scientific or policy claims.
26/// Legacy FIEL descriptors are not authored here; their semantic pairing stays
27/// with the caller, as in `PhysicalFieldSemantics::from_existing`.
28///
29/// Scratch is caller-owned and may change on failure. The existing checked
30/// envelope writer validates before changing final output. Slice capacities
31/// are the caller-selected byte/entry budgets; this function allocates nothing.
32#[allow(clippy::too_many_arguments)]
33pub fn encode_sensing_container<'a>(
34    profile: SensingIndexProfile,
35    header: &Container10dHeader,
36    identity: &ManifoldIdentityV2,
37    container_id: [u8; 16],
38    index_field_id: u64,
39    raw_prefix: &[u8],
40    raw_fields: &[TypedFieldRecord],
41    records: &[MeasurementRecord],
42    other_extensions: &[u16],
43    payload_scratch: &'a mut [u8],
44    manifest_scratch: &'a mut [u8],
45    field_scratch: &mut [TypedFieldRecord],
46    section_scratch: &mut [SectionInput<'a>],
47    output: &mut [u8],
48) -> Result<usize, SensingAssemblyError> {
49    let count = raw_fields
50        .len()
51        .checked_add(1)
52        .ok_or(SensingAssemblyError::Capacity)?;
53    if count > MANIFOLD_IDENTITY_V2_MAX_FIELDS
54        || field_scratch.len() < count
55        || section_scratch.len() < 2
56    {
57        return Err(SensingAssemblyError::Capacity);
58    }
59    for (i, field) in raw_fields.iter().enumerate() {
60        if field.field_id == 0
61            || field.field_id == index_field_id
62            || field.kind == profile.kind()
63            || field.flags != 0
64            || field.payload_section_id != SectionType::FieldSidecar as u32
65            || field.payload_length == 0
66            || field
67                .payload_offset
68                .checked_add(field.payload_length)
69                .filter(|end| *end <= raw_prefix.len() as u64)
70                .is_none()
71            || raw_fields[..i]
72                .iter()
73                .any(|prior| prior.field_id == field.field_id)
74        {
75            return Err(SensingAssemblyError::DeclarationMismatch);
76        }
77    }
78    for record in records {
79        let physical = record.physical();
80        let raw = record.raw_payload();
81        let Some(field) = raw_fields
82            .iter()
83            .find(|field| field.field_id == physical.field_id())
84        else {
85            return Err(SensingAssemblyError::DeclarationMismatch);
86        };
87        if field.kind != physical.typed_field_kind()
88            || field.unit_id != physical.typed_unit_id().value().unwrap_or(0)
89            || field.payload_section_id != raw.section_id()
90            || field.payload_offset != raw.offset()
91            || field.payload_length != raw.length()
92        {
93            return Err(SensingAssemblyError::DeclarationMismatch);
94        }
95    }
96    let mut extensions = [0u16; MAX_SENSING_PROFILE_EXTENSIONS];
97    let extension_count = profile
98        .write_supported_kinds(other_extensions, &mut extensions)
99        .map_err(SensingAssemblyError::Registration)?;
100    let packed = profile
101        .pack(
102            container_id,
103            index_field_id,
104            raw_prefix,
105            records,
106            payload_scratch,
107        )
108        .map_err(SensingAssemblyError::Index)?;
109    field_scratch[..raw_fields.len()].copy_from_slice(raw_fields);
110    field_scratch[raw_fields.len()] = packed.index_field;
111    let section = SectionInput {
112        section_type: SectionType::FieldSidecar,
113        alignment_tier: AlignmentTier::Word,
114        stride: 0,
115        element_count: 0,
116        payload: &payload_scratch[..packed.field_section_bytes],
117    };
118    encode_container_with_manifold_identity_extensions(
119        header,
120        &[section],
121        identity,
122        &field_scratch[..count],
123        &extensions[..extension_count],
124        manifest_scratch,
125        section_scratch,
126        output,
127    )
128    .map_err(SensingAssemblyError::Envelope)
129}