Skip to main content

qualia_core_db/sensing/container/
pack.rs

1use super::super::record::{
2    encode_measurement_index_records, MeasurementRecord, MAX_MEASUREMENT_INDEX_RECORDS,
3    MEASUREMENT_INDEX_RECORD_SIZE,
4};
5use super::{validate_container, validate_kind, SensingContainerError};
6use crate::container_10d::{SectionType, TypedFieldRecord};
7
8/// The declaration to add to MID2 and total FieldSidecar length. Pass the
9/// resulting payload and extension kind to the existing extension-aware
10/// container writer; retain the original raw-field declarations unchanged.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct PackedSensingIndex {
13    pub index_field: TypedFieldRecord,
14    pub field_section_bytes: usize,
15}
16
17/// Append canonical index rows to an unchanged raw FieldSidecar prefix.
18/// `output` is caller-owned. All refusals precede output modification. Raw
19/// FieldSidecar references must remain entirely inside the prefix; references
20/// to other sections require validation by the enclosing container writer.
21/// This function does not assign or authenticate the container identifier.
22pub fn pack_sensing_index_field(
23    container_id: [u8; 16],
24    index_field_id: u64,
25    extension_kind: u16,
26    raw_field_prefix: &[u8],
27    records: &[MeasurementRecord],
28    output: &mut [u8],
29) -> Result<PackedSensingIndex, SensingContainerError> {
30    validate_container(&container_id)?;
31    validate_kind(extension_kind)?;
32    if index_field_id == 0 {
33        return Err(SensingContainerError::InvalidFieldId);
34    }
35    if records.is_empty() || records.len() > MAX_MEASUREMENT_INDEX_RECORDS {
36        return Err(SensingContainerError::InvalidIndex);
37    }
38    let index_len = records
39        .len()
40        .checked_mul(MEASUREMENT_INDEX_RECORD_SIZE)
41        .ok_or(SensingContainerError::Range)?;
42    let total = raw_field_prefix
43        .len()
44        .checked_add(index_len)
45        .ok_or(SensingContainerError::Range)?;
46    if output.len() < total {
47        return Err(SensingContainerError::Capacity);
48    }
49    for (i, record) in records.iter().enumerate() {
50        if records[..i]
51            .iter()
52            .any(|other| other.record_id() == record.record_id())
53        {
54            return Err(SensingContainerError::DuplicateRecordId);
55        }
56        if record.physical().field_id() == index_field_id {
57            return Err(SensingContainerError::IndexPayloadOverlap);
58        }
59        let raw = record.raw_payload();
60        if raw.container_id() != container_id {
61            return Err(SensingContainerError::ContainerMismatch);
62        }
63        if raw.section_id() == SectionType::FieldSidecar as u32
64            && raw
65                .offset()
66                .checked_add(raw.length())
67                .filter(|end| *end <= raw_field_prefix.len() as u64)
68                .is_none()
69        {
70            return Err(SensingContainerError::IndexPayloadOverlap);
71        }
72    }
73    let field = TypedFieldRecord {
74        field_id: index_field_id,
75        kind: extension_kind,
76        flags: 0,
77        unit_id: 0,
78        payload_section_id: SectionType::FieldSidecar as u32,
79        payload_offset: raw_field_prefix.len() as u64,
80        payload_length: index_len as u64,
81    };
82    // Encoder preflight above exhausts its capacity/duplicate/count refusals.
83    encode_measurement_index_records(records, &mut output[raw_field_prefix.len()..total])
84        .map_err(SensingContainerError::Record)?;
85    output[..raw_field_prefix.len()].copy_from_slice(raw_field_prefix);
86    Ok(PackedSensingIndex {
87        index_field: field,
88        field_section_bytes: total,
89    })
90}