Skip to main content

qualia_core_db/container_10d/
section.rs

1//! `.10d` self-describing section table + tiered alignment + caller-buffered
2//! writer (P0.2).
3//!
4//! A `.10d` file is: the 64-byte [`super::header::Container10dHeader`], then
5//! (optionally) a section table — an array of [`SectionDescriptor`] rows —
6//! then the section payloads, each aligned to its declared tier. The header's
7//! `section_table_offset` + `section_count` point at the table.
8//!
9//! **Canonical encoding (determinism).** Sections are written in ascending
10//! `section_type` order. Duplicate `section_type` values are rejected, so two
11//! encodes of the same section set — even if the caller passes them in
12//! permuted order — produce byte-identical output. This is the P0.2
13//! "two encodes (incl. permuted section order) are byte-identical" gate.
14//!
15//! **Tiered alignment.** Each section declares an [`AlignmentTier`]; the
16//! writer inserts zero padding so every section start meets its tier. The
17//! reader rejects any section whose start is misaligned, whose descriptor
18//! overlaps another, whose `byte_offset`/`byte_length` is out of bounds, or
19//! whose `stride * element_count != byte_length` (stride-inconsistent).
20//!
21//! **Per-section CRC-32C.** Each descriptor carries a CRC-32C over its
22//! payload bytes; the reader rejects a flipped bit. The CRC-32C routine here
23//! is a local copy of the Castagnoli-reflected algorithm used in
24//! `q42/p64_weight.rs`; **P0.3 consolidates the two into a shared module and
25//! delegates both call sites** (the P0.3 acceptance gate verifies p64's
26//! checksums stay byte-identical after delegation).
27//!
28//! **Caller-buffered / zero-heap.** [`encode_container`] takes a caller-
29//! supplied `&mut [u8]` output buffer and returns the bytes written; it
30//! allocates no `Vec`/`String`/`Box` on the hot path (the only allocation is
31//! the canonical-order index sort, which uses a stack array — see
32//! `sort_indices_stack`). [`parse_section_table`] returns a zero-copy
33//! `&[SectionDescriptor]` view into the input bytes.
34
35#[path = "section/table_validation.rs"]
36mod table_validation;
37/// Shared allocation-free descriptor geometry for full and partial readers.
38pub mod metadata;
39
40// FND-04: new preservation behavior lives in a focused child; the oversized
41// strict parser/writer remains unchanged pending its separate decomposition.
42#[path = "section/opaque_preservation.rs"]
43mod opaque_preservation;
44pub use opaque_preservation::{
45    copy_opaque_container_into, inspect_opaque_container,
46    replace_known_section_bytes_preserving_layout, OpaqueContainerView,
47    OpaquePreservationBudget, OpaquePreservationError,
48};
49
50use bytemuck::{Pod, Zeroable};
51
52use crate::container_10d::crc32c::crc32c;
53use crate::container_10d::header::{Container10dHeader, HEADER_BYTE_SIZE, MAX_SECTION_COUNT};
54
55/// Size of one [`SectionDescriptor`] in bytes.
56pub const SECTION_DESCRIPTOR_SIZE: usize = 24;
57
58/// Maximum number of sections the writer will accept (mirrors the header's
59/// `MAX_SECTION_COUNT` so the writer cannot produce an unreadable file).
60const MAX_SECTIONS_ENCODE: usize = MAX_SECTION_COUNT as usize;
61
62/// A section type tag. v1 defines the types the runtime actually fills;
63/// future types are listed as `SpecReserved*` and the writer rejects them
64/// (a `SpecReserved*` type in a v1 file is a forward-incompatibility signal,
65/// not a payload to read blindly).
66#[repr(u8)]
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum SectionType {
69    /// Sentinel — the reader rejects this.
70    Undefined = 0,
71    /// Quantized triangle mesh (P0.4 — u16-quantized vertices within the
72    /// mesh's bounding box + u16/u32 triangle indices; see
73    /// [`super::mesh_section`]).
74    QuantizedMesh = 1,
75    /// Tensor10D node section — the 40-byte epistemic atom (P0.5).
76    Tensor10DNodes = 2,
77    /// Reconstruction output — mesh/complex/operator (P6.7).
78    Reconstruction = 3,
79    // --- spec-reserved (reader rejects in v1; do NOT read blindly) ---
80    SpecReservedGovernance = 4,
81    SpecReservedTemporalIndex = 5,
82    SpecReservedManifoldHeadTable = 6,
83    /// Provenance sidecar — source bytes + licence + verifiable credential
84    /// bundled in-envelope so context is byte-inseparable (P1; see
85    /// [`super::provenance_section`]). No longer spec-reserved.
86    ProvenanceSidecar = 7,
87    /// Optional geometry/scientific field data. The payload is self-describing;
88    /// currently includes the versioned per-vertex normal field codec.
89    FieldSidecar = 8,
90    /// Volumetric-to-surface correspondence map (`FEMC`) binding surface vertices
91    /// to tetrahedral finite elements via quantized barycentric weights.
92    CorrespondenceMap = 9,
93    /// Topology section — half-edge graph + CSR adjacency + connectivity
94    /// summary (P2.8). Contains a TopologyMiniHeader followed by the
95    /// half-edge array, vertex-adjacency CSR (offsets + neighbours), and
96    /// face-adjacency CSR (offsets + neighbours).
97    Topology = 10,
98    /// Spatial-index section — BVH + kd-tree node arrays for scan-free
99    /// spatial queries (P3.7).
100    SpatialIndex = 11,
101    /// Per-vertex surface colour reading. Not a texture, not a normal, and
102    /// not an albedo for the whole part. One RGBA8 sample per mesh vertex,
103    /// same order as the quantized mesh. See `surface_reading`.
104    SurfaceReading = 12,
105    /// Versioned physically-based/stylized material records and contiguous submesh ranges.
106    Materials = 13,
107    /// Vertex-aligned glTF TEXCOORD_0 values used by material texture sampling.
108    TextureCoordinates = 14,
109    /// Version-2 stable manifold identity and typed references to scientific/presentation fields.
110    ManifoldIdentityV2 = 15,
111    /// SKL1 rig, vertex skin influences and named VibeScript motor clips.
112    SkeletalAnimation = 16,
113    /// Entity behavioral and affordance ontology table for AI triggering and scriptability.
114    EntityOntology = 17,
115    /// Principled procedural geometry/surface synthesis descriptors (Voronoi, SDF fillets, allometry, PGA).
116    ProceduralSynthesis = 18,
117    /// Directional octahedral impostor atlas for mid-to-far field rendering (8–64 px).
118    ImpostorAtlas = 19,
119    /// Hierarchical surfel / 3D Gaussian splat primitives for far-field rendering (1–8 px).
120    HierarchicalSurfels = 20,
121    /// Multi-band sensor reflectance & emittance data cube (400nm-1000nm band stacks).
122    HyperspectralCube = 21,
123    /// 3D Sparse Voxel Octree / DAG (VOX0) with 16B nodes and material LUT indices.
124    VoxelLattice = 22,
125    /// Nanite-style hierarchical meshlet cluster DAG (`CDAG`) for continuous GPU-driven LOD.
126    ClusterDag = 23,
127}
128
129impl SectionType {
130    /// Canonical upper-case constant for SectionType::EntityOntology (personal/entity ontology).
131    pub const PERSONAL_ONTOLOGY: Self = Self::EntityOntology;
132    /// Backwards compatibility alias for SectionType::PERSONAL_ONTOLOGY.
133    #[deprecated(note = "Use SectionType::PERSONAL_ONTOLOGY or SectionType::EntityOntology")]
134    #[allow(non_upper_case_globals)]
135    pub const PersonalOntology: Self = Self::EntityOntology;
136    /// Backwards compatibility alias for [`SectionType::CorrespondenceMap`].
137    #[allow(non_upper_case_globals)]
138    pub const SpecReservedCorrespondenceMap: Self = Self::CorrespondenceMap;
139
140    /// Decode a section-type tag (0–23); `None` for unknown values.
141    #[inline]
142    pub const fn from_u8(raw: u8) -> Option<SectionType> {
143        match raw {
144            0 => Some(SectionType::Undefined),
145            1 => Some(SectionType::QuantizedMesh),
146            2 => Some(SectionType::Tensor10DNodes),
147            3 => Some(SectionType::Reconstruction),
148            4 => Some(SectionType::SpecReservedGovernance),
149            5 => Some(SectionType::SpecReservedTemporalIndex),
150            6 => Some(SectionType::SpecReservedManifoldHeadTable),
151            7 => Some(SectionType::ProvenanceSidecar),
152            8 => Some(SectionType::FieldSidecar),
153            9 => Some(SectionType::CorrespondenceMap),
154            10 => Some(SectionType::Topology),
155            11 => Some(SectionType::SpatialIndex),
156            12 => Some(SectionType::SurfaceReading),
157            13 => Some(SectionType::Materials),
158            14 => Some(SectionType::TextureCoordinates),
159            15 => Some(SectionType::ManifoldIdentityV2),
160            16 => Some(SectionType::SkeletalAnimation),
161            17 => Some(SectionType::EntityOntology),
162            18 => Some(SectionType::ProceduralSynthesis),
163            19 => Some(SectionType::ImpostorAtlas),
164            20 => Some(SectionType::HierarchicalSurfels),
165            21 => Some(SectionType::HyperspectralCube),
166            22 => Some(SectionType::VoxelLattice),
167            23 => Some(SectionType::ClusterDag),
168            _ => None,
169        }
170    }
171
172    /// True if this section type is implemented (the runtime can read/write
173    /// it) vs spec-reserved (defined in the format but not yet filled).
174    #[inline]
175    pub const fn is_implemented(self) -> bool {
176        matches!(
177            self,
178            SectionType::QuantizedMesh
179                | SectionType::Tensor10DNodes
180                | SectionType::Reconstruction
181                | SectionType::ProvenanceSidecar
182                | SectionType::FieldSidecar
183                | SectionType::CorrespondenceMap
184                | SectionType::Topology
185                | SectionType::SpatialIndex
186                | SectionType::SurfaceReading
187                | SectionType::Materials
188                | SectionType::TextureCoordinates
189                | SectionType::ManifoldIdentityV2
190                | SectionType::SkeletalAnimation
191                | SectionType::EntityOntology
192                | SectionType::ProceduralSynthesis
193                | SectionType::ImpostorAtlas
194                | SectionType::HierarchicalSurfels
195                | SectionType::HyperspectralCube
196                | SectionType::VoxelLattice
197                | SectionType::ClusterDag
198        )
199    }
200}
201
202/// Alignment tier for a section's start offset. The tier determines the
203/// power-of-two alignment the writer enforces (and the reader verifies).
204#[repr(u8)]
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum AlignmentTier {
207    /// 1-byte aligned (no requirement).
208    Byte = 0,
209    /// 4-byte aligned.
210    Word = 1,
211    /// 16-byte aligned (typical for SoA tensor lanes).
212    CacheLine = 2,
213    /// 64-byte aligned (page-aligned, matches `q42/p64_weight.rs`).
214    Page = 3,
215}
216
217impl AlignmentTier {
218    /// The alignment in bytes for this tier.
219    #[inline]
220    pub const fn to_bytes(self) -> usize {
221        match self {
222            AlignmentTier::Byte => 1,
223            AlignmentTier::Word => 4,
224            AlignmentTier::CacheLine => 16,
225            AlignmentTier::Page => 64,
226        }
227    }
228
229    /// Decode an alignment tier (0–3); `None` for unknown values.
230    #[inline]
231    pub const fn from_u8(raw: u8) -> Option<AlignmentTier> {
232        match raw {
233            0 => Some(AlignmentTier::Byte),
234            1 => Some(AlignmentTier::Word),
235            2 => Some(AlignmentTier::CacheLine),
236            3 => Some(AlignmentTier::Page),
237            _ => None,
238        }
239    }
240}
241
242/// Align `offset` up to the next multiple of `align` (power of two).
243#[inline]
244const fn align_up(offset: usize, align: usize) -> usize {
245    if align <= 1 {
246        return offset;
247    }
248    (offset + align - 1) & !(align - 1)
249}
250
251/// One row of the section table — a self-describing section descriptor.
252///
253/// Layout: 24 bytes, `repr(C)`, naturally aligned, no padding.
254/// ```text
255/// offset  size  field
256/// 0       1     section_type     (SectionType u8)
257/// 1       1     alignment_tier   (AlignmentTier u8)
258/// 2       2     reserved16       (must be zero)
259/// 4       4     byte_offset      (from file start)
260/// 8       4     byte_length      (payload length in bytes)
261/// 12      4     stride           (bytes per element for AoS sections; 0 = non-strided)
262/// 16      4     element_count    (for array sections; 0 = non-array)
263/// 20      4     crc32c           (CRC-32C over the payload bytes)
264/// ```
265#[repr(C)]
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable)]
267pub struct SectionDescriptor {
268    pub section_type: u8,
269    pub alignment_tier: u8,
270    pub reserved16: u16,
271    pub byte_offset: u32,
272    pub byte_length: u32,
273    pub stride: u32,
274    pub element_count: u32,
275    pub crc32c: u32,
276}
277
278impl SectionDescriptor {
279    /// The alignment tier as a typed enum (or `None` if the raw byte is
280    /// undefined — the reader rejects this).
281    #[inline]
282    pub fn tier(&self) -> Option<AlignmentTier> {
283        AlignmentTier::from_u8(self.alignment_tier)
284    }
285
286    /// The section type as a typed enum (or `None` if undefined).
287    #[inline]
288    pub fn typ(&self) -> Option<SectionType> {
289        SectionType::from_u8(self.section_type)
290    }
291}
292
293/// A caller-supplied section input for [`encode_container`]. The writer
294/// computes `byte_offset`, `crc32c`, and the canonical order; the caller
295/// supplies the type, tier, stride/element_count (for array sections), and
296/// the payload bytes.
297#[derive(Debug, Clone, Copy)]
298pub struct SectionInput<'a> {
299    pub section_type: SectionType,
300    pub alignment_tier: AlignmentTier,
301    /// Bytes per element for array-of-structs sections. `0` for non-strided
302    /// (blob) sections. If non-zero, `stride * element_count` must equal
303    /// `payload.len()` or the writer rejects the input as stride-inconsistent.
304    pub stride: u32,
305    /// Element count for array sections. `0` for non-array (blob) sections.
306    pub element_count: u32,
307    pub payload: &'a [u8],
308}
309
310/// Section-table encode/decode error.
311#[derive(Debug, Clone, PartialEq, Eq)]
312pub enum SectionTableError {
313    /// More than `MAX_SECTION_COUNT` sections.
314    TooManySections { count: usize },
315    /// Two sections share the same `section_type` (canonical encoding
316    /// requires unique types in v1).
317    DuplicateSectionType { section_type: u8 },
318    /// A section type byte is not a defined variant, or is `Undefined`, or is
319    /// a `SpecReserved*` type the v1 writer refuses to emit.
320    UnsupportedSectionType { got: u8 },
321    /// The section kind requires a newer outer container version.
322    SectionRequiresVersion {
323        section_type: u8,
324        minimum_version: u16,
325        actual_version: u16,
326    },
327    /// An alignment tier byte is not a defined variant.
328    UnsupportedAlignmentTier { got: u8 },
329    /// `stride * element_count != payload.len()`.
330    StrideInconsistent {
331        section_type: u8,
332        stride: u32,
333        element_count: u32,
334        payload_len: usize,
335    },
336    /// The caller-supplied output buffer is too small.
337    OutputBufferTooSmall { needed: usize, have: usize },
338    /// The input bytes are too short to hold the header + section table.
339    InputTooShort { got: usize, need: usize },
340    /// The header's section-table pointer is inconsistent (offset/count
341    /// mismatch, offset below header, or count over the max).
342    BadSectionTablePointer { offset: u32, count: u32 },
343    /// Borrowed descriptor bytes are not aligned for the zero-copy table view.
344    UnalignedSectionTable,
345    /// A nonempty payload intersects the container header or section table.
346    SectionOverlapsMetadata { index: usize },
347    /// A descriptor's `reserved16` is non-zero.
348    NonZeroDescriptorReserved { index: usize },
349    /// A descriptor's `byte_offset` is misaligned relative to its tier.
350    MisalignedSection {
351        index: usize,
352        offset: u32,
353        tier: AlignmentTier,
354    },
355    /// A descriptor's `byte_offset`/`byte_length` is out of bounds.
356    OutOfBounds {
357        index: usize,
358        offset: u32,
359        length: u32,
360        file_len: usize,
361    },
362    /// Two descriptors' payload regions overlap.
363    OverlappingSections { index_a: usize, index_b: usize },
364    /// A descriptor's `stride * element_count != byte_length`.
365    StrideInconsistentDescriptor {
366        index: usize,
367        stride: u32,
368        element_count: u32,
369        byte_length: u32,
370    },
371    /// A descriptor's section type is `Undefined` or an unknown byte.
372    UndefinedSectionType { index: usize, got: u8 },
373    /// A descriptor's alignment tier is undefined.
374    UndefinedAlignmentTier { index: usize, got: u8 },
375    /// A payload's CRC-32C does not match the stored value (a flipped bit).
376    CrcMismatch {
377        index: usize,
378        section_type: u8,
379        expected: u32,
380        got: u32,
381    },
382    /// A padding region between sections is non-zero.
383    NonZeroPadding { at: usize },
384}
385
386impl std::fmt::Display for SectionTableError {
387    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388        match self {
389            Self::TooManySections { count } => {
390                write!(f, "10d too many sections: {count} > {MAX_SECTION_COUNT}")
391            }
392            Self::DuplicateSectionType { section_type } => write!(
393                f,
394                "10d duplicate section type {section_type} (v1 requires unique types)"
395            ),
396            Self::UnsupportedSectionType { got } => {
397                write!(f, "10d unsupported section type byte {got}")
398            }
399            Self::SectionRequiresVersion {
400                section_type,
401                minimum_version,
402                actual_version,
403            } => write!(
404                f,
405                "10d section type {section_type} requires header version {minimum_version}, got {actual_version}"
406            ),
407            Self::UnsupportedAlignmentTier { got } => {
408                write!(f, "10d unsupported alignment tier byte {got}")
409            }
410            Self::StrideInconsistent {
411                section_type,
412                stride,
413                element_count,
414                payload_len,
415            } => write!(
416                f,
417                "10d stride inconsistent for type {section_type}: {stride} * {element_count} != {payload_len}"
418            ),
419            Self::OutputBufferTooSmall { needed, have } => {
420                write!(f, "10d output buffer too small: need {needed}, have {have}")
421            }
422            Self::InputTooShort { got, need } => {
423                write!(f, "10d input too short: got {got}, need {need}")
424            }
425            Self::BadSectionTablePointer { offset, count } => write!(
426                f,
427                "10d bad section-table pointer: offset={offset}, count={count}"
428            ),
429            Self::UnalignedSectionTable => write!(f, "10d section table is not aligned for borrowing"),
430            Self::SectionOverlapsMetadata { index } => write!(f, "10d section {index} overlaps header or section table"),
431            Self::NonZeroDescriptorReserved { index } => {
432                write!(f, "10d non-zero reserved16 in descriptor {index}")
433            }
434            Self::MisalignedSection {
435                index,
436                offset,
437                tier,
438            } => write!(
439                f,
440                "10d section {index} offset {offset} misaligned for tier {tier:?}"
441            ),
442            Self::OutOfBounds {
443                index,
444                offset,
445                length,
446                file_len,
447            } => write!(
448                f,
449                "10d section {index} out of bounds: offset={offset} length={length} file_len={file_len}"
450            ),
451            Self::OverlappingSections { index_a, index_b } => {
452                write!(f, "10d sections {index_a} and {index_b} overlap")
453            }
454            Self::StrideInconsistentDescriptor {
455                index,
456                stride,
457                element_count,
458                byte_length,
459            } => write!(
460                f,
461                "10d descriptor {index} stride inconsistent: {stride} * {element_count} != {byte_length}"
462            ),
463            Self::UndefinedSectionType { index, got } => {
464                write!(f, "10d descriptor {index} undefined section type {got}")
465            }
466            Self::UndefinedAlignmentTier { index, got } => {
467                write!(f, "10d descriptor {index} undefined alignment tier {got}")
468            }
469            Self::CrcMismatch {
470                index,
471                section_type,
472                expected,
473                got,
474            } => write!(
475                f,
476                "10d CRC mismatch in section {index} (type {section_type}): expected {expected:#010x}, got {got:#010x}"
477            ),
478            Self::NonZeroPadding { at } => write!(f, "10d non-zero padding at byte {at}"),
479        }
480    }
481}
482
483impl std::error::Error for SectionTableError {}
484
485// ---------------------------------------------------------------------------
486// Canonical-order index sort (stack-only, no Vec).
487// Returns the indices of `inputs` sorted by `section_type` ascending. Insertion
488// sort is fine — MAX_SECTIONS_ENCODE is small and the section count in any
489// realistic .10d is <10. No heap allocation.
490// ---------------------------------------------------------------------------
491
492fn sort_indices_stack(inputs: &[SectionInput<'_>]) -> [usize; MAX_SECTIONS_ENCODE] {
493    let mut idx = [0usize; MAX_SECTIONS_ENCODE];
494    for i in 0..inputs.len() {
495        idx[i] = i;
496    }
497    // Insertion sort by section_type (stable — preserves input order for
498    // equal keys, though equal keys are rejected later as duplicates).
499    for i in 1..inputs.len() {
500        let mut j = i;
501        while j > 0 && inputs[idx[j - 1]].section_type as u8 > inputs[idx[j]].section_type as u8 {
502            idx.swap(j - 1, j);
503            j -= 1;
504        }
505    }
506    idx
507}
508
509/// Compute the total encoded byte length for a set of sections (header +
510/// section table + aligned payloads + inter-section padding). Pure, no
511/// allocation. Returns the total and fills `order` with the canonical index
512/// order and `descs` with the computed descriptors (offsets/lengths/CRCs).
513fn plan_layout(
514    inputs: &[SectionInput<'_>],
515    order: &mut [usize; MAX_SECTIONS_ENCODE],
516    descs: &mut [SectionDescriptor; MAX_SECTIONS_ENCODE],
517) -> Result<usize, SectionTableError> {
518    if inputs.len() > MAX_SECTIONS_ENCODE {
519        return Err(SectionTableError::TooManySections {
520            count: inputs.len(),
521        });
522    }
523    *order = sort_indices_stack(inputs);
524
525    // Reject duplicate section types and unsupported types/tiers up front.
526    for k in 0..inputs.len() {
527        let i = order[k];
528        let st = inputs[i].section_type as u8;
529        if k > 0 && inputs[order[k - 1]].section_type as u8 == st {
530            return Err(SectionTableError::DuplicateSectionType { section_type: st });
531        }
532        if !inputs[i].section_type.is_implemented() {
533            return Err(SectionTableError::UnsupportedSectionType { got: st });
534        }
535        // Validate stride consistency against the payload.
536        if inputs[i].stride > 0 {
537            let expected = inputs[i].stride as usize * inputs[i].element_count as usize;
538            if expected != inputs[i].payload.len() {
539                return Err(SectionTableError::StrideInconsistent {
540                    section_type: st,
541                    stride: inputs[i].stride,
542                    element_count: inputs[i].element_count,
543                    payload_len: inputs[i].payload.len(),
544                });
545            }
546        }
547    }
548
549    // Layout: header (64) -> section table (count * 24) -> payloads (aligned).
550    let table_off = HEADER_BYTE_SIZE;
551    let table_len = inputs.len() * SECTION_DESCRIPTOR_SIZE;
552    let mut cursor = table_off + table_len;
553
554    for k in 0..inputs.len() {
555        let i = order[k];
556        let align = inputs[i].alignment_tier.to_bytes();
557        cursor = align_up(cursor, align);
558        let off = cursor;
559        let len = inputs[i].payload.len();
560        let crc = crc32c(inputs[i].payload);
561        descs[k] = SectionDescriptor {
562            section_type: inputs[i].section_type as u8,
563            alignment_tier: inputs[i].alignment_tier as u8,
564            reserved16: 0,
565            byte_offset: off as u32,
566            byte_length: len as u32,
567            stride: inputs[i].stride,
568            element_count: inputs[i].element_count,
569            crc32c: crc,
570        };
571        cursor = off + len;
572    }
573    Ok(cursor)
574}
575
576/// Encode a `.10d` container into a caller-supplied buffer. Zero-heap on the
577/// hot path (the only stack arrays are the index order and descriptor table,
578/// both fixed-size). Returns the number of bytes written.
579///
580/// The header is written with `section_table_offset` and `section_count`
581/// filled in to point at the table; `header_crc32c` is left as the caller
582/// supplied it (P0.3 wires the shared CRC-32C over the header).
583pub fn encode_container(
584    header: &Container10dHeader,
585    inputs: &[SectionInput<'_>],
586    out: &mut [u8],
587) -> Result<usize, SectionTableError> {
588    if inputs
589        .iter()
590        .any(|input| input.section_type == SectionType::ManifoldIdentityV2)
591        && header.version < super::header::HEADER_VERSION
592    {
593        return Err(SectionTableError::SectionRequiresVersion {
594            section_type: SectionType::ManifoldIdentityV2 as u8,
595            minimum_version: super::header::HEADER_VERSION,
596            actual_version: header.version,
597        });
598    }
599    let mut order = [0usize; MAX_SECTIONS_ENCODE];
600    let mut descs = [ZEROED_SECTION_DESCRIPTOR; MAX_SECTIONS_ENCODE];
601    let total = plan_layout(inputs, &mut order, &mut descs)?;
602    if out.len() < total {
603        return Err(SectionTableError::OutputBufferTooSmall {
604            needed: total,
605            have: out.len(),
606        });
607    }
608
609    // Zero the whole output region we will write into (so padding is zero).
610    for b in out[..total].iter_mut() {
611        *b = 0;
612    }
613
614    // Write the header with the section-table pointer filled in.
615    let mut h = *header;
616    if inputs.is_empty() {
617        h.section_table_offset = 0;
618        h.section_count = 0;
619    } else {
620        h.section_table_offset = HEADER_BYTE_SIZE as u32;
621        h.section_count = inputs.len() as u32;
622    }
623    let mut header_buf = [0u8; HEADER_BYTE_SIZE];
624    h.encode(&mut header_buf);
625    out[..HEADER_BYTE_SIZE].copy_from_slice(&header_buf);
626
627    if inputs.is_empty() {
628        return Ok(HEADER_BYTE_SIZE);
629    }
630
631    // Write the section table.
632    let table_off = HEADER_BYTE_SIZE;
633    for k in 0..inputs.len() {
634        let desc_bytes: &[u8; SECTION_DESCRIPTOR_SIZE] = bytemuck::cast_ref(&descs[k]);
635        let dst = table_off + k * SECTION_DESCRIPTOR_SIZE;
636        out[dst..dst + SECTION_DESCRIPTOR_SIZE].copy_from_slice(desc_bytes);
637    }
638
639    // Write the payloads (padding is already zeroed).
640    for k in 0..inputs.len() {
641        let i = order[k];
642        let off = descs[k].byte_offset as usize;
643        let len = descs[k].byte_length as usize;
644        out[off..off + len].copy_from_slice(inputs[i].payload);
645    }
646
647    Ok(total)
648}
649
650/// A const-zero `SectionDescriptor` for initialising the fixed-size stack
651/// array in [`encode_container`] without going through `Zeroable::zeroed()`.
652const ZEROED_SECTION_DESCRIPTOR: SectionDescriptor = SectionDescriptor {
653    section_type: 0,
654    alignment_tier: 0,
655    reserved16: 0,
656    byte_offset: 0,
657    byte_length: 0,
658    stride: 0,
659    element_count: 0,
660    crc32c: 0,
661};
662
663/// Parse the section table from a `.10d` byte slice. Returns a zero-copy
664/// `&[SectionDescriptor]` view into the input. Runs every P0.2 reader gate:
665/// pointer consistency, per-descriptor type/tier/reserved validation, tier
666/// alignment, in-bounds, overlap, stride consistency, and per-section CRC.
667///
668/// Padding-between-sections is verified zero as part of the overlap/scan pass.
669pub fn parse_section_table<'a>(
670    data: &'a [u8],
671    header: &Container10dHeader,
672) -> Result<&'a [SectionDescriptor], SectionTableError> {
673    let (off, cnt) = (header.section_table_offset, header.section_count);
674    if off == 0 && cnt == 0 {
675        return Ok(&[]);
676    }
677    // Pointer consistency (the header parser also checks this, but re-check
678    // for callers that construct a header by hand).
679    let both_zero = off == 0 && cnt == 0;
680    let both_nonzero = off != 0 && cnt != 0;
681    let valid_nonzero = both_nonzero
682        && off as usize >= HEADER_BYTE_SIZE
683        && off as usize <= data.len()
684        && cnt <= MAX_SECTION_COUNT;
685    if !both_zero && !valid_nonzero {
686        return Err(SectionTableError::BadSectionTablePointer {
687            offset: off,
688            count: cnt,
689        });
690    }
691    let table_start = off as usize;
692    let table_bytes = cnt as usize * SECTION_DESCRIPTOR_SIZE;
693    let table_end =
694        table_start
695            .checked_add(table_bytes)
696            .ok_or(SectionTableError::BadSectionTablePointer {
697                offset: off,
698                count: cnt,
699            })?;
700    if table_end > data.len() {
701        return Err(SectionTableError::InputTooShort {
702            got: data.len(),
703            need: table_end,
704        });
705    }
706    // Return a clear error for unaligned borrowed bytes instead of panicking.
707    let descs = table_validation::borrow_table(&data[table_start..table_end])?;
708
709    // Per-descriptor validation + cross-descriptor overlap/alignment scan.
710    // We scan in table order (which is canonical = ascending section_type
711    // order for files we wrote; for files we didn't write, we sort the
712    // offset check by byte_offset to detect overlaps correctly).
713    for (i, d) in descs.iter().enumerate() {
714        if descs[..i].iter().any(|old| old.section_type == d.section_type) {
715            return Err(SectionTableError::DuplicateSectionType { section_type: d.section_type });
716        }
717        metadata::validate_descriptor_metadata(d, i, header.version, data.len() as u64, table_start as u64, table_end as u64)?;
718        let o = d.byte_offset as usize;
719        let end = o + d.byte_length as usize;
720        // Per-section CRC.
721        let stored = d.crc32c;
722        let actual = crc32c(&data[o..end]);
723        if actual != stored {
724            return Err(SectionTableError::CrcMismatch {
725                index: i,
726                section_type: d.section_type,
727                expected: stored,
728                got: actual,
729            });
730        }
731    }
732
733    // Overlap detection: sort descriptor indices by byte_offset and check
734    // adjacent ranges don't overlap. Use a stack array (count is bounded by
735    // MAX_SECTION_COUNT, but that's 1024 — too big for a fixed stack array in
736    // a zero-heap function). Instead, do an O(n^2) pairwise check (n is small
737    // in practice; the 42MB Sentinel bounds the file and section count is
738    // realistically <10). This is zero-heap.
739    for a in 0..descs.len() {
740        for b in (a + 1)..descs.len() {
741            let (ao, al) = (descs[a].byte_offset as usize, descs[a].byte_length as usize);
742            let (bo, bl) = (descs[b].byte_offset as usize, descs[b].byte_length as usize);
743            let a_end = ao + al;
744            let b_end = bo + bl;
745            if ao < b_end && bo < a_end {
746                // Two zero-length sections at the same offset are not an
747                // overlap (an empty section is allowed to share an offset).
748                if al == 0 || bl == 0 {
749                    continue;
750                }
751                return Err(SectionTableError::OverlappingSections {
752                    index_a: a,
753                    index_b: b,
754                });
755            }
756        }
757    }
758
759    // Focused canonical validation also supports payloads before a later table.
760    table_validation::padding(data, descs, table_start, table_end)?;
761
762    Ok(descs)
763}
764
765#[cfg(test)]
766mod tests {
767    use super::*;
768    use crate::container_10d::header::Container10dHeader;
769
770    fn mesh_input(payload: &[u8]) -> SectionInput<'_> {
771        SectionInput {
772            section_type: SectionType::QuantizedMesh,
773            alignment_tier: AlignmentTier::Word,
774            stride: 0,
775            element_count: 0,
776            payload,
777        }
778    }
779
780    fn node_input(payload: &[u8]) -> SectionInput<'_> {
781        // Tensor10D nodes: 40 bytes each, 16-byte aligned (SoA lane friendly).
782        SectionInput {
783            section_type: SectionType::Tensor10DNodes,
784            alignment_tier: AlignmentTier::CacheLine,
785            stride: 40,
786            element_count: (payload.len() / 40) as u32,
787            payload,
788        }
789    }
790
791    #[test]
792    fn descriptor_is_pod_with_exact_size() {
793        assert_eq!(
794            std::mem::size_of::<SectionDescriptor>(),
795            SECTION_DESCRIPTOR_SIZE
796        );
797        assert_eq!(std::mem::offset_of!(SectionDescriptor, section_type), 0);
798        assert_eq!(std::mem::offset_of!(SectionDescriptor, alignment_tier), 1);
799        assert_eq!(std::mem::offset_of!(SectionDescriptor, reserved16), 2);
800        assert_eq!(std::mem::offset_of!(SectionDescriptor, byte_offset), 4);
801        assert_eq!(std::mem::offset_of!(SectionDescriptor, byte_length), 8);
802        assert_eq!(std::mem::offset_of!(SectionDescriptor, stride), 12);
803        assert_eq!(std::mem::offset_of!(SectionDescriptor, element_count), 16);
804        assert_eq!(std::mem::offset_of!(SectionDescriptor, crc32c), 20);
805    }
806
807    #[test]
808    fn bare_header_encodes_and_parses_with_no_sections() {
809        let h = Container10dHeader::proposed();
810        let mut out = [0u8; 128];
811        let n = encode_container(&h, &[], &mut out).expect("bare encode");
812        assert_eq!(n, HEADER_BYTE_SIZE);
813        let parsed_h = Container10dHeader::parse(&out[..n]).expect("bare parse");
814        assert_eq!(parsed_h, h);
815        let table = parse_section_table(&out[..n], &parsed_h).expect("bare table parse");
816        assert!(table.is_empty());
817    }
818
819    #[test]
820    fn round_trip_two_sections_descriptors_match() {
821        let h = Container10dHeader::proposed();
822        let mesh_payload = [0xAAu8; 100];
823        let node_payload = [0xBBu8; 40 * 3]; // 3 Tensor10D nodes
824        let inputs = [mesh_input(&mesh_payload), node_input(&node_payload)];
825        let mut out = [0u8; 512];
826        let n = encode_container(&h, &inputs, &mut out).expect("encode");
827        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
828        let descs = parse_section_table(&out[..n], &parsed_h).expect("table parse");
829        assert_eq!(descs.len(), 2);
830        // Canonical order: QuantizedMesh(1) before Tensor10DNodes(2).
831        assert_eq!(descs[0].section_type, SectionType::QuantizedMesh as u8);
832        assert_eq!(descs[1].section_type, SectionType::Tensor10DNodes as u8);
833        // Payloads round-trip.
834        assert_eq!(
835            &out[descs[0].byte_offset as usize..][..mesh_payload.len()],
836            &mesh_payload
837        );
838        assert_eq!(
839            &out[descs[1].byte_offset as usize..][..node_payload.len()],
840            &node_payload
841        );
842        // Stride/element_count for the node section.
843        assert_eq!(descs[1].stride, 40);
844        assert_eq!(descs[1].element_count, 3);
845    }
846
847    #[test]
848    fn every_section_start_meets_its_declared_tier() {
849        let h = Container10dHeader::proposed();
850        let mesh_payload = [0u8; 7]; // odd length, will force padding before next section
851        let node_payload = [0u8; 40];
852        let inputs = [mesh_input(&mesh_payload), node_input(&node_payload)];
853        let mut out = [0u8; 512];
854        let n = encode_container(&h, &inputs, &mut out).expect("encode");
855        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
856        let descs = parse_section_table(&out[..n], &parsed_h).expect("table parse");
857        for d in descs {
858            let tier = AlignmentTier::from_u8(d.alignment_tier).unwrap();
859            assert_eq!(
860                (d.byte_offset as usize) % tier.to_bytes(),
861                0,
862                "section type {} at offset {} must meet tier {:?}",
863                d.section_type,
864                d.byte_offset,
865                tier
866            );
867        }
868    }
869
870    #[test]
871    fn padding_between_sections_is_zero() {
872        let h = Container10dHeader::proposed();
873        let mesh_payload = [0u8; 7]; // forces padding before the 16-byte-aligned node section
874        let node_payload = [0u8; 40];
875        let inputs = [mesh_input(&mesh_payload), node_input(&node_payload)];
876        let mut out = [0u8; 512];
877        let n = encode_container(&h, &inputs, &mut out).expect("encode");
878        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
879        let descs = parse_section_table(&out[..n], &parsed_h).expect("table parse");
880        // The gap between the mesh payload end and the node section start must be zero.
881        let mesh_end = descs[0].byte_offset as usize + descs[0].byte_length as usize;
882        let node_start = descs[1].byte_offset as usize;
883        assert!(
884            node_start > mesh_end,
885            "there must be padding between the odd-length mesh and the 16-aligned node"
886        );
887        for b in &out[mesh_end..node_start] {
888            assert_eq!(*b, 0, "padding between sections must be zero");
889        }
890    }
891
892    #[test]
893    fn permuted_section_order_produces_byte_identical_output() {
894        let h = Container10dHeader::proposed();
895        let mesh_payload = [0xAAu8; 100];
896        let node_payload = [0xBBu8; 40 * 3];
897        let inputs_a = [mesh_input(&mesh_payload), node_input(&node_payload)];
898        let inputs_b = [node_input(&node_payload), mesh_input(&mesh_payload)]; // permuted
899        let mut out_a = [0u8; 512];
900        let mut out_b = [0u8; 512];
901        let n_a = encode_container(&h, &inputs_a, &mut out_a).expect("encode a");
902        let n_b = encode_container(&h, &inputs_b, &mut out_b).expect("encode b");
903        assert_eq!(n_a, n_b);
904        assert_eq!(
905            &out_a[..n_a],
906            &out_b[..n_b],
907            "permuted input must produce byte-identical output"
908        );
909    }
910
911    #[test]
912    fn duplicate_section_type_is_rejected() {
913        let h = Container10dHeader::proposed();
914        let p1 = [0u8; 16];
915        let p2 = [0u8; 32];
916        let inputs = [mesh_input(&p1), mesh_input(&p2)];
917        let mut out = [0u8; 512];
918        let err = encode_container(&h, &inputs, &mut out).expect_err("duplicate type must reject");
919        assert!(
920            matches!(
921                err,
922                SectionTableError::DuplicateSectionType { section_type: 1 }
923            ),
924            "{err}"
925        );
926    }
927
928    #[test]
929    fn stride_inconsistent_input_is_rejected() {
930        let h = Container10dHeader::proposed();
931        // Claim stride=40, element_count=3 (=> 120 bytes) but payload is 100.
932        let bad = SectionInput {
933            section_type: SectionType::Tensor10DNodes,
934            alignment_tier: AlignmentTier::CacheLine,
935            stride: 40,
936            element_count: 3,
937            payload: &[0u8; 100],
938        };
939        let mut out = [0u8; 512];
940        let err = encode_container(&h, std::slice::from_ref(&bad), &mut out)
941            .expect_err("stride inconsistent must reject");
942        assert!(
943            matches!(err, SectionTableError::StrideInconsistent { .. }),
944            "{err}"
945        );
946    }
947
948    #[test]
949    fn output_buffer_too_small_is_rejected() {
950        let h = Container10dHeader::proposed();
951        let payload = [0u8; 100];
952        let inputs = [mesh_input(&payload)];
953        let mut out = [0u8; 80]; // way too small
954        let err = encode_container(&h, &inputs, &mut out).expect_err("small buffer must reject");
955        assert!(
956            matches!(err, SectionTableError::OutputBufferTooSmall { .. }),
957            "{err}"
958        );
959    }
960
961    #[test]
962    fn flipped_payload_bit_is_caught_by_crc() {
963        let h = Container10dHeader::proposed();
964        let payload = [0xAAu8; 100];
965        let inputs = [mesh_input(&payload)];
966        let mut out = [0u8; 512];
967        let n = encode_container(&h, &inputs, &mut out).expect("encode");
968        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
969        // Flip one bit in the payload region.
970        let descs_ok = parse_section_table(&out[..n], &parsed_h).expect("clean table parses");
971        let p_off = descs_ok[0].byte_offset as usize;
972        out[p_off] ^= 0x01;
973        let err =
974            parse_section_table(&out[..n], &parsed_h).expect_err("flipped bit must be caught");
975        assert!(
976            matches!(err, SectionTableError::CrcMismatch { .. }),
977            "{err}"
978        );
979    }
980
981    #[test]
982    fn flipped_descriptor_byte_is_caught() {
983        let h = Container10dHeader::proposed();
984        let payload = [0xAAu8; 100];
985        let inputs = [mesh_input(&payload)];
986        let mut out = [0u8; 512];
987        let n = encode_container(&h, &inputs, &mut out).expect("encode");
988        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
989        // Corrupt the descriptor's reserved16 (offset table_start + 2).
990        let table_start = parsed_h.section_table_offset as usize;
991        out[table_start + 2] = 0xFF;
992        let err =
993            parse_section_table(&out[..n], &parsed_h).expect_err("non-zero reserved16 must reject");
994        assert!(
995            matches!(
996                err,
997                SectionTableError::NonZeroDescriptorReserved { index: 0 }
998            ),
999            "{err}"
1000        );
1001    }
1002
1003    #[test]
1004    fn misaligned_section_offset_is_rejected() {
1005        let h = Container10dHeader::proposed();
1006        let payload = [0xAAu8; 100];
1007        let inputs = [mesh_input(&payload)];
1008        let mut out = [0u8; 512];
1009        let n = encode_container(&h, &inputs, &mut out).expect("encode");
1010        let mut parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
1011        // Move the section's byte_offset to a misaligned address (the table
1012        // is at 64, descriptor 0's byte_offset is at table_start + 4).
1013        let table_start = parsed_h.section_table_offset as usize;
1014        let off_field = table_start + 4;
1015        // Set byte_offset to 65 (misaligned for Word tier = 4).
1016        out[off_field..off_field + 4].copy_from_slice(&65u32.to_le_bytes());
1017        // Re-parse the header (the section-table pointer is unchanged).
1018        parsed_h = Container10dHeader::parse(&out[..n]).expect("header still parses");
1019        let err =
1020            parse_section_table(&out[..n], &parsed_h).expect_err("misaligned offset must reject");
1021        assert!(
1022            matches!(err, SectionTableError::MisalignedSection { .. }),
1023            "{err}"
1024        );
1025    }
1026
1027    #[test]
1028    fn out_of_bounds_section_is_rejected() {
1029        let h = Container10dHeader::proposed();
1030        let payload = [0xAAu8; 100];
1031        let inputs = [mesh_input(&payload)];
1032        let mut out = [0u8; 512];
1033        let n = encode_container(&h, &inputs, &mut out).expect("encode");
1034        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
1035        // Set byte_length to a value that runs past the file end.
1036        let table_start = parsed_h.section_table_offset as usize;
1037        let len_field = table_start + 8;
1038        out[len_field..len_field + 4].copy_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
1039        let err = parse_section_table(&out[..n], &parsed_h).expect_err("OOB must reject");
1040        assert!(
1041            matches!(err, SectionTableError::OutOfBounds { .. }),
1042            "{err}"
1043        );
1044    }
1045
1046    #[test]
1047    fn overlapping_sections_are_rejected() {
1048        // Encode two valid, non-overlapping sections first, then patch the
1049        // second descriptor's byte_offset so its range overlaps the first.
1050        // Recompute the second's CRC over the patched range so the per-section
1051        // CRC passes and the reader reaches the overlap check.
1052        let h = Container10dHeader::proposed();
1053        let mesh_payload = [0xAAu8; 100];
1054        let node_payload = [0xBBu8; 40];
1055        let inputs = [mesh_input(&mesh_payload), node_input(&node_payload)];
1056        let mut out = [0u8; 512];
1057        let n = encode_container(&h, &inputs, &mut out).expect("encode");
1058        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
1059        let table_start = parsed_h.section_table_offset as usize;
1060        // Read the first section's offset.
1061        let first_off =
1062            u32::from_le_bytes(out[table_start + 4..table_start + 8].try_into().unwrap()) as usize;
1063        // Patch the second descriptor's byte_offset to overlap the first.
1064        // The node section declares CacheLine (16-byte) tier, so the patched
1065        // offset must stay 16-aligned; align up from first_off+10 so it
1066        // remains within the first section's payload range (first_off..
1067        // first_off+100) and thus overlaps.
1068        let second_desc_off = table_start + SECTION_DESCRIPTOR_SIZE;
1069        let new_second_off = align_up(first_off + 10, 16) as u32;
1070        assert!(
1071            (new_second_off as usize) < first_off + mesh_payload.len(),
1072            "patched offset must overlap the first payload"
1073        );
1074        out[second_desc_off + 4..second_desc_off + 8]
1075            .copy_from_slice(&new_second_off.to_le_bytes());
1076        let crc_start = new_second_off as usize;
1077        let crc_end = crc_start + 40;
1078        let new_crc = crc32c(&out[crc_start..crc_end]);
1079        out[second_desc_off + 20..second_desc_off + 24].copy_from_slice(&new_crc.to_le_bytes());
1080        // The patched file's header still parses (pointer unchanged).
1081        let parsed_h2 = Container10dHeader::parse(&out[..n]).expect("header still parses");
1082        let err = parse_section_table(&out[..n], &parsed_h2).expect_err("overlap must reject");
1083        assert!(
1084            matches!(err, SectionTableError::OverlappingSections { .. }),
1085            "{err}"
1086        );
1087    }
1088
1089    #[test]
1090    fn non_zero_inter_section_padding_is_rejected() {
1091        let h = Container10dHeader::proposed();
1092        let mesh_payload = [0u8; 7]; // forces a padding gap before the 16-aligned node section
1093        let node_payload = [0u8; 40];
1094        let inputs = [mesh_input(&mesh_payload), node_input(&node_payload)];
1095        let mut out = [0u8; 512];
1096        let n = encode_container(&h, &inputs, &mut out).expect("encode");
1097        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
1098        let descs = parse_section_table(&out[..n], &parsed_h).expect("clean parses");
1099        let mesh_end = descs[0].byte_offset as usize + descs[0].byte_length as usize;
1100        // Corrupt a padding byte.
1101        out[mesh_end] = 0x42;
1102        let err =
1103            parse_section_table(&out[..n], &parsed_h).expect_err("non-zero padding must reject");
1104        assert!(
1105            matches!(err, SectionTableError::NonZeroPadding { .. }),
1106            "{err}"
1107        );
1108    }
1109
1110    #[test]
1111    fn unsupported_section_type_is_rejected() {
1112        let h = Container10dHeader::proposed();
1113        let bad = SectionInput {
1114            section_type: SectionType::SpecReservedGovernance, // spec-reserved, not yet implemented
1115            alignment_tier: AlignmentTier::Word,
1116            stride: 0,
1117            element_count: 0,
1118            payload: &[0u8; 16],
1119        };
1120        let mut out = [0u8; 512];
1121        let err = encode_container(&h, std::slice::from_ref(&bad), &mut out)
1122            .expect_err("spec-reserved type must reject");
1123        assert!(
1124            matches!(err, SectionTableError::UnsupportedSectionType { .. }),
1125            "{err}"
1126        );
1127    }
1128
1129    #[test]
1130    fn manifold_identity_v2_requires_v2_outer_header() {
1131        let mut header = Container10dHeader::proposed();
1132        header.version = super::super::header::LEGACY_HEADER_VERSION;
1133        let manifest = SectionInput {
1134            section_type: SectionType::ManifoldIdentityV2,
1135            alignment_tier: AlignmentTier::Page,
1136            stride: 0,
1137            element_count: 0,
1138            payload: &[0; 112],
1139        };
1140        let mut out = [0u8; 512];
1141        assert!(matches!(
1142            encode_container(&header, std::slice::from_ref(&manifest), &mut out),
1143            Err(SectionTableError::SectionRequiresVersion {
1144                section_type: 15,
1145                minimum_version: 2,
1146                actual_version: 1,
1147            })
1148        ));
1149        assert_eq!(
1150            SectionType::from_u8(15),
1151            Some(SectionType::ManifoldIdentityV2)
1152        );
1153        assert!(SectionType::ManifoldIdentityV2.is_implemented());
1154    }
1155}