1#[path = "section/table_validation.rs"]
36mod table_validation;
37pub mod metadata;
39
40#[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
55pub const SECTION_DESCRIPTOR_SIZE: usize = 24;
57
58const MAX_SECTIONS_ENCODE: usize = MAX_SECTION_COUNT as usize;
61
62#[repr(u8)]
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum SectionType {
69 Undefined = 0,
71 QuantizedMesh = 1,
75 Tensor10DNodes = 2,
77 Reconstruction = 3,
79 SpecReservedGovernance = 4,
81 SpecReservedTemporalIndex = 5,
82 SpecReservedManifoldHeadTable = 6,
83 ProvenanceSidecar = 7,
87 FieldSidecar = 8,
90 CorrespondenceMap = 9,
93 Topology = 10,
98 SpatialIndex = 11,
101 SurfaceReading = 12,
105 Materials = 13,
107 TextureCoordinates = 14,
109 ManifoldIdentityV2 = 15,
111 SkeletalAnimation = 16,
113 EntityOntology = 17,
115 ProceduralSynthesis = 18,
117 ImpostorAtlas = 19,
119 HierarchicalSurfels = 20,
121 HyperspectralCube = 21,
123 VoxelLattice = 22,
125 ClusterDag = 23,
127}
128
129impl SectionType {
130 pub const PERSONAL_ONTOLOGY: Self = Self::EntityOntology;
132 #[deprecated(note = "Use SectionType::PERSONAL_ONTOLOGY or SectionType::EntityOntology")]
134 #[allow(non_upper_case_globals)]
135 pub const PersonalOntology: Self = Self::EntityOntology;
136 #[allow(non_upper_case_globals)]
138 pub const SpecReservedCorrespondenceMap: Self = Self::CorrespondenceMap;
139
140 #[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 #[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#[repr(u8)]
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum AlignmentTier {
207 Byte = 0,
209 Word = 1,
211 CacheLine = 2,
213 Page = 3,
215}
216
217impl AlignmentTier {
218 #[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 #[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#[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#[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 #[inline]
282 pub fn tier(&self) -> Option<AlignmentTier> {
283 AlignmentTier::from_u8(self.alignment_tier)
284 }
285
286 #[inline]
288 pub fn typ(&self) -> Option<SectionType> {
289 SectionType::from_u8(self.section_type)
290 }
291}
292
293#[derive(Debug, Clone, Copy)]
298pub struct SectionInput<'a> {
299 pub section_type: SectionType,
300 pub alignment_tier: AlignmentTier,
301 pub stride: u32,
305 pub element_count: u32,
307 pub payload: &'a [u8],
308}
309
310#[derive(Debug, Clone, PartialEq, Eq)]
312pub enum SectionTableError {
313 TooManySections { count: usize },
315 DuplicateSectionType { section_type: u8 },
318 UnsupportedSectionType { got: u8 },
321 SectionRequiresVersion {
323 section_type: u8,
324 minimum_version: u16,
325 actual_version: u16,
326 },
327 UnsupportedAlignmentTier { got: u8 },
329 StrideInconsistent {
331 section_type: u8,
332 stride: u32,
333 element_count: u32,
334 payload_len: usize,
335 },
336 OutputBufferTooSmall { needed: usize, have: usize },
338 InputTooShort { got: usize, need: usize },
340 BadSectionTablePointer { offset: u32, count: u32 },
343 UnalignedSectionTable,
345 SectionOverlapsMetadata { index: usize },
347 NonZeroDescriptorReserved { index: usize },
349 MisalignedSection {
351 index: usize,
352 offset: u32,
353 tier: AlignmentTier,
354 },
355 OutOfBounds {
357 index: usize,
358 offset: u32,
359 length: u32,
360 file_len: usize,
361 },
362 OverlappingSections { index_a: usize, index_b: usize },
364 StrideInconsistentDescriptor {
366 index: usize,
367 stride: u32,
368 element_count: u32,
369 byte_length: u32,
370 },
371 UndefinedSectionType { index: usize, got: u8 },
373 UndefinedAlignmentTier { index: usize, got: u8 },
375 CrcMismatch {
377 index: usize,
378 section_type: u8,
379 expected: u32,
380 got: u32,
381 },
382 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
485fn 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 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
509fn 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 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 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 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
576pub 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 for b in out[..total].iter_mut() {
611 *b = 0;
612 }
613
614 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 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 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
650const 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
663pub 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 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 let descs = table_validation::borrow_table(&data[table_start..table_end])?;
708
709 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 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 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 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 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 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]; 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 assert_eq!(descs[0].section_type, SectionType::QuantizedMesh as u8);
832 assert_eq!(descs[1].section_type, SectionType::Tensor10DNodes as u8);
833 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 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]; 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]; 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 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)]; 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 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]; 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 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 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 let table_start = parsed_h.section_table_offset as usize;
1014 let off_field = table_start + 4;
1015 out[off_field..off_field + 4].copy_from_slice(&65u32.to_le_bytes());
1017 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 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 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 let first_off =
1062 u32::from_le_bytes(out[table_start + 4..table_start + 8].try_into().unwrap()) as usize;
1063 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 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]; 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 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, 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}