Skip to main content

qualia_core_db/container_10d/
field_section.rs

1//! FIEL v0 field descriptors and optional raster sample payloads.
2//!
3//! `encode_field_section` writes a declaration-only payload (12-byte header,
4//! 32-byte descriptors). `encode_field_section_with_rasters` also appends grid
5//! metadata (16 bytes) and little-endian f32 samples, with descriptor sample
6//! offsets locating them inside the same payload. Both existing APIs use the
7//! current version-zero schema; raster support is not a new format version.
8//!
9//! `decode_field_section` reads declarations; `decode_field_raster_samples`
10//! resolves the selected raster. Envelope, range, codec and domain validation
11//! are separate obligations. A successful declaration read does not establish
12//! scientific accuracy, meaningful units or authentication of sample data.
13//!
14//! Preserve field names, unit hashes, support/representation and sample bytes.
15//! Do not infer that a FIEL unit hash and a MID2 registry identifier are
16//! equivalent without a qualified mapping. See the typed payload companion in
17//! `docs/manuals/standards/10d-typed-field-payloads.md` for coexistence contracts.
18
19use bytemuck::{Pod, Zeroable};
20
21#[path = "field_section/checked.rs"]
22mod checked;
23pub use checked::{inspect_field_section, FieldInspection, FieldInspectionError, FieldInspectionLimits};
24
25/// Magic bytes for the Field section: "FIEL" in little-endian.
26pub const FIELD_SECTION_MAGIC: u32 = 0x4649454C;
27
28/// Current version of the Field section encoding.
29pub const FIELD_SECTION_VERSION: u16 = 0;
30
31/// Size of the FieldSectionHeader in bytes (u32 + u16 + u16 + u32 = 12).
32pub const FIELD_SECTION_HEADER_SIZE: usize = 12;
33
34/// Size of one FieldDescriptor in bytes.
35pub const FIELD_DESCRIPTOR_SIZE: usize = 32;
36
37/// Maximum fields per section (limited by u16 field_count).
38pub const MAX_FIELDS_PER_SECTION: usize = 65535;
39
40/// Field type kind — what values the field holds.
41#[repr(u8)]
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum FieldTypeKind {
44    /// Scalar field (e.g. pressure, temperature).
45    Scalar = 0,
46    /// Vector field (e.g. velocity, E-field).
47    Vector = 1,
48    /// Tensor field (e.g. stress tensor).
49    Tensor = 2,
50    /// Spectral field (e.g. EMF spectrum).
51    Spectral = 3,
52}
53
54impl FieldTypeKind {
55    /// Decode a field-type tag; `None` for values outside 0–3.
56    pub const fn from_u8(raw: u8) -> Option<Self> {
57        match raw {
58            0 => Some(Self::Scalar),
59            1 => Some(Self::Vector),
60            2 => Some(Self::Tensor),
61            3 => Some(Self::Spectral),
62            _ => None,
63        }
64    }
65}
66
67/// Field support — where the field is defined.
68#[repr(u8)]
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum FieldSupportKind {
71    /// Region-wide field (continuous across a region).
72    Region = 0,
73    /// Point field (defined at specific points).
74    Point = 1,
75    /// Continuant-bound field (attached to a continuant).
76    Continuant = 2,
77    /// Stream field (time-varying stream of values).
78    Stream = 3,
79}
80
81impl FieldSupportKind {
82    /// Decode a field-support tag; `None` for values outside 0–3.
83    pub const fn from_u8(raw: u8) -> Option<Self> {
84        match raw {
85            0 => Some(Self::Region),
86            1 => Some(Self::Point),
87            2 => Some(Self::Continuant),
88            3 => Some(Self::Stream),
89            _ => None,
90        }
91    }
92}
93
94/// Field representation — how the field is stored.
95#[repr(u8)]
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum FieldRepresentationKind {
98    /// Grid representation (regular grid of samples).
99    Grid = 0,
100    /// Mesh representation (values on mesh nodes/faces).
101    Mesh = 1,
102    /// Particle representation (values on particles).
103    Particles = 2,
104    /// Analytic representation (closed-form expression).
105    Analytic = 3,
106    /// Sampled representation (irregular samples).
107    Sampled = 4,
108}
109
110impl FieldRepresentationKind {
111    /// Decode a field-representation tag; `None` for values outside 0–4.
112    pub const fn from_u8(raw: u8) -> Option<Self> {
113        match raw {
114            0 => Some(Self::Grid),
115            1 => Some(Self::Mesh),
116            2 => Some(Self::Particles),
117            3 => Some(Self::Analytic),
118            4 => Some(Self::Sampled),
119            _ => None,
120        }
121    }
122}
123
124/// Header for the Field section.
125#[repr(C)]
126#[derive(Debug, Clone, Copy, Pod, Zeroable)]
127pub struct FieldSectionHeader {
128    /// Magic bytes: 0x4649454C ("FIEL").
129    pub magic: u32,
130    /// Encoding version (currently 0).
131    pub version: u16,
132    /// Number of FieldDescriptor entries following the header.
133    pub field_count: u16,
134    /// Reserved for future use (must be 0 in v0).
135    pub reserved: u32,
136}
137
138impl Default for FieldSectionHeader {
139    fn default() -> Self {
140        Self {
141            magic: FIELD_SECTION_MAGIC,
142            version: FIELD_SECTION_VERSION,
143            field_count: 0,
144            reserved: 0,
145        }
146    }
147}
148
149/// A single field descriptor — one entry in the Field section's ontology table.
150#[repr(C)]
151#[derive(Debug, Clone, Copy, Pod, Zeroable)]
152pub struct FieldDescriptor {
153    /// FNV-1a hash of the field name (e.g. "pressure_ambient").
154    pub name_hash: u64,
155    /// FNV-1a hash of the unit IRI (e.g. "qudt:KiloPascal").
156    pub unit_hash: u64,
157    /// Field type kind (see FieldTypeKind).
158    pub type_kind: u8,
159    /// Field support kind (see FieldSupportKind).
160    pub support: u8,
161    /// Field representation kind (see FieldRepresentationKind).
162    pub representation: u8,
163    /// Reserved (must be 0 in v0).
164    pub reserved: u8,
165    /// Reserved (must be 0 in v0).
166    pub reserved2: u32,
167    /// Offset into the data section where samples begin (0 in v0 — no samples yet).
168    pub sample_offset: u64,
169}
170
171impl Default for FieldDescriptor {
172    fn default() -> Self {
173        Self {
174            name_hash: 0,
175            unit_hash: 0,
176            type_kind: FieldTypeKind::Scalar as u8,
177            support: FieldSupportKind::Region as u8,
178            representation: FieldRepresentationKind::Grid as u8,
179            reserved: 0,
180            reserved2: 0,
181            sample_offset: 0,
182        }
183    }
184}
185
186/// Errors from the Field section encoder/decoder.
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub enum FieldSectionError {
189    /// Buffer too small for the header.
190    BufferTooSmallForHeader,
191    /// Buffer too small for the declared number of descriptors.
192    BufferTooSmallForDescriptors,
193    /// Magic bytes don't match.
194    BadMagic(u32),
195    /// Unsupported version.
196    UnsupportedVersion(u16),
197    /// Invalid type kind.
198    InvalidTypeKind(u8),
199    /// Invalid support kind.
200    InvalidSupportKind(u8),
201    /// Invalid representation kind.
202    InvalidRepresentationKind(u8),
203    /// Too many fields.
204    TooManyFields(usize),
205}
206
207impl std::fmt::Display for FieldSectionError {
208    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209        match self {
210            Self::BufferTooSmallForHeader => write!(f, "buffer too small for field section header"),
211            Self::BufferTooSmallForDescriptors => {
212                write!(f, "buffer too small for field descriptors")
213            }
214            Self::BadMagic(m) => write!(f, "bad field section magic: 0x{m:08X}"),
215            Self::UnsupportedVersion(v) => write!(f, "unsupported field section version: {v}"),
216            Self::InvalidTypeKind(k) => write!(f, "invalid field type kind: {k}"),
217            Self::InvalidSupportKind(k) => write!(f, "invalid field support kind: {k}"),
218            Self::InvalidRepresentationKind(k) => {
219                write!(f, "invalid field representation kind: {k}")
220            }
221            Self::TooManyFields(n) => {
222                write!(f, "too many fields: {n} (max {MAX_FIELDS_PER_SECTION})")
223            }
224        }
225    }
226}
227
228impl std::error::Error for FieldSectionError {}
229
230/// A field entry to encode into the Field section.
231#[derive(Debug, Clone)]
232pub struct FieldEntry {
233    /// FNV-1a hash of the field name.
234    pub name_hash: u64,
235    /// FNV-1a hash of the unit IRI (0 if no unit).
236    pub unit_hash: u64,
237    /// Field type kind.
238    pub type_kind: FieldTypeKind,
239    /// Field support kind.
240    pub support: FieldSupportKind,
241    /// Field representation kind.
242    pub representation: FieldRepresentationKind,
243}
244
245impl FieldEntry {
246    /// Create a field descriptor to encode into a Field section.
247    /// `unit_hash` is 0 when the field is unitless.
248    pub fn new(
249        name_hash: u64,
250        unit_hash: u64,
251        type_kind: FieldTypeKind,
252        support: FieldSupportKind,
253        representation: FieldRepresentationKind,
254    ) -> Self {
255        Self {
256            name_hash,
257            unit_hash,
258            type_kind,
259            support,
260            representation,
261        }
262    }
263
264    fn to_descriptor(&self) -> FieldDescriptor {
265        FieldDescriptor {
266            name_hash: self.name_hash,
267            unit_hash: self.unit_hash,
268            type_kind: self.type_kind as u8,
269            support: self.support as u8,
270            representation: self.representation as u8,
271            reserved: 0,
272            reserved2: 0,
273            sample_offset: 0, // v0: no samples yet
274        }
275    }
276}
277
278/// Encode a list of field entries into a `.10d` Field section.
279///
280/// Returns the number of bytes written, or an error if the buffer is
281/// too small or the entries are invalid.
282pub fn encode_field_section(
283    entries: &[FieldEntry],
284    out: &mut [u8],
285) -> Result<usize, FieldSectionError> {
286    if entries.len() > MAX_FIELDS_PER_SECTION {
287        return Err(FieldSectionError::TooManyFields(entries.len()));
288    }
289    let needed = FIELD_SECTION_HEADER_SIZE + entries.len() * FIELD_DESCRIPTOR_SIZE;
290    if out.len() < needed {
291        return Err(FieldSectionError::BufferTooSmallForHeader);
292    }
293
294    // Write header.
295    let header = FieldSectionHeader {
296        magic: FIELD_SECTION_MAGIC,
297        version: FIELD_SECTION_VERSION,
298        field_count: entries.len() as u16,
299        reserved: 0,
300    };
301    let header_bytes = bytemuck::bytes_of(&header);
302    out[..FIELD_SECTION_HEADER_SIZE].copy_from_slice(header_bytes);
303
304    // Write descriptors.
305    let mut offset = FIELD_SECTION_HEADER_SIZE;
306    for entry in entries {
307        let desc = entry.to_descriptor();
308        let desc_bytes = bytemuck::bytes_of(&desc);
309        out[offset..offset + FIELD_DESCRIPTOR_SIZE].copy_from_slice(desc_bytes);
310        offset += FIELD_DESCRIPTOR_SIZE;
311    }
312
313    Ok(offset)
314}
315
316/// Decode a `.10d` Field section from bytes.
317///
318/// Returns the header and a slice of field descriptors (zero-copy view
319/// into the input bytes).
320pub fn decode_field_section(
321    bytes: &[u8],
322) -> Result<(FieldSectionHeader, Vec<FieldDescriptor>), FieldSectionError> {
323    if bytes.len() < FIELD_SECTION_HEADER_SIZE {
324        return Err(FieldSectionError::BufferTooSmallForHeader);
325    }
326
327    // Copy header bytes into a stack array for alignment-safe reading.
328    let mut header_buf = [0u8; FIELD_SECTION_HEADER_SIZE];
329    header_buf.copy_from_slice(&bytes[..FIELD_SECTION_HEADER_SIZE]);
330    let header: FieldSectionHeader = *bytemuck::from_bytes(&header_buf);
331
332    if header.magic != FIELD_SECTION_MAGIC {
333        return Err(FieldSectionError::BadMagic(header.magic));
334    }
335    if header.version != FIELD_SECTION_VERSION {
336        return Err(FieldSectionError::UnsupportedVersion(header.version));
337    }
338
339    let count = header.field_count as usize;
340    let needed = FIELD_SECTION_HEADER_SIZE + count * FIELD_DESCRIPTOR_SIZE;
341    if bytes.len() < needed {
342        return Err(FieldSectionError::BufferTooSmallForDescriptors);
343    }
344
345    // Read descriptors one by one (alignment-safe).
346    let mut descriptors = Vec::with_capacity(count);
347    let mut offset = FIELD_SECTION_HEADER_SIZE;
348    for _ in 0..count {
349        let mut desc_buf = [0u8; FIELD_DESCRIPTOR_SIZE];
350        desc_buf.copy_from_slice(&bytes[offset..offset + FIELD_DESCRIPTOR_SIZE]);
351        let desc: FieldDescriptor = *bytemuck::from_bytes(&desc_buf);
352        descriptors.push(desc);
353        offset += FIELD_DESCRIPTOR_SIZE;
354    }
355
356    // Validate each descriptor's enum fields.
357    for desc in &descriptors {
358        if FieldTypeKind::from_u8(desc.type_kind).is_none() {
359            return Err(FieldSectionError::InvalidTypeKind(desc.type_kind));
360        }
361        if FieldSupportKind::from_u8(desc.support).is_none() {
362            return Err(FieldSectionError::InvalidSupportKind(desc.support));
363        }
364        if FieldRepresentationKind::from_u8(desc.representation).is_none() {
365            return Err(FieldSectionError::InvalidRepresentationKind(
366                desc.representation,
367            ));
368        }
369    }
370
371    Ok((header, descriptors))
372}
373
374/// Header preceding raw sample payload for a grid field descriptor.
375#[repr(C)]
376#[derive(Debug, Clone, Copy, Pod, Zeroable)]
377pub struct RasterGridMetadata {
378    /// Grid width in samples.
379    pub width: u32,
380    /// Grid height in samples.
381    pub height: u32,
382    /// Total sample count (`width * height`).
383    pub sample_count: u32,
384    /// Reserved for alignment / future flags.
385    pub reserved: u32,
386}
387
388pub const RASTER_GRID_METADATA_SIZE: usize = 16;
389
390/// A continuous environmental raster layer with raw sample data for encoding.
391#[derive(Debug, Clone)]
392pub struct ContinuousRasterField<'a> {
393    pub name_hash: u64,
394    pub unit_hash: u64,
395    pub width: u32,
396    pub height: u32,
397    pub samples: &'a [f32],
398}
399
400/// Encode a set of continuous raster fields (including sample payloads) into a `.10d` Field section.
401pub fn encode_field_section_with_rasters(
402    fields: &[ContinuousRasterField],
403    out: &mut [u8],
404) -> Result<usize, FieldSectionError> {
405    if fields.len() > MAX_FIELDS_PER_SECTION {
406        return Err(FieldSectionError::TooManyFields(fields.len()));
407    }
408
409    let header_and_descs_size = FIELD_SECTION_HEADER_SIZE + fields.len() * FIELD_DESCRIPTOR_SIZE;
410    let mut total_sample_bytes = 0usize;
411    for f in fields {
412        total_sample_bytes += RASTER_GRID_METADATA_SIZE + f.samples.len() * 4;
413    }
414    let total_needed = header_and_descs_size + total_sample_bytes;
415    if out.len() < total_needed {
416        return Err(FieldSectionError::BufferTooSmallForHeader);
417    }
418
419    // Write header
420    let header = FieldSectionHeader {
421        magic: FIELD_SECTION_MAGIC,
422        version: FIELD_SECTION_VERSION,
423        field_count: fields.len() as u16,
424        reserved: 0,
425    };
426    out[..FIELD_SECTION_HEADER_SIZE].copy_from_slice(bytemuck::bytes_of(&header));
427
428    // Descriptors and payload layout
429    let mut current_sample_offset = header_and_descs_size as u64;
430    let mut desc_offset = FIELD_SECTION_HEADER_SIZE;
431
432    for f in fields {
433        let desc = FieldDescriptor {
434            name_hash: f.name_hash,
435            unit_hash: f.unit_hash,
436            type_kind: FieldTypeKind::Scalar as u8,
437            support: FieldSupportKind::Region as u8,
438            representation: FieldRepresentationKind::Grid as u8,
439            reserved: 0,
440            reserved2: 0,
441            sample_offset: current_sample_offset,
442        };
443        out[desc_offset..desc_offset + FIELD_DESCRIPTOR_SIZE]
444            .copy_from_slice(bytemuck::bytes_of(&desc));
445        desc_offset += FIELD_DESCRIPTOR_SIZE;
446
447        // Write sample metadata
448        let meta = RasterGridMetadata {
449            width: f.width,
450            height: f.height,
451            sample_count: f.samples.len() as u32,
452            reserved: 0,
453        };
454        let sample_start = current_sample_offset as usize;
455        let sample_data_start = sample_start + RASTER_GRID_METADATA_SIZE;
456        let sample_data_end = sample_data_start + f.samples.len() * 4;
457
458        out[sample_start..sample_data_start].copy_from_slice(bytemuck::bytes_of(&meta));
459        let sample_bytes: &[u8] = bytemuck::cast_slice(f.samples);
460        out[sample_data_start..sample_data_end].copy_from_slice(sample_bytes);
461
462        current_sample_offset += (RASTER_GRID_METADATA_SIZE + f.samples.len() * 4) as u64;
463    }
464
465    Ok(total_needed)
466}
467
468/// Read continuous raster grid samples corresponding to a decoded descriptor.
469pub fn decode_field_raster_samples<'a>(
470    bytes: &'a [u8],
471    descriptor: &FieldDescriptor,
472) -> Result<(RasterGridMetadata, &'a [f32]), FieldSectionError> {
473    let offset = descriptor.sample_offset as usize;
474    if offset == 0 || offset + RASTER_GRID_METADATA_SIZE > bytes.len() {
475        return Err(FieldSectionError::BufferTooSmallForDescriptors);
476    }
477
478    let mut meta_buf = [0u8; RASTER_GRID_METADATA_SIZE];
479    meta_buf.copy_from_slice(&bytes[offset..offset + RASTER_GRID_METADATA_SIZE]);
480    let meta: RasterGridMetadata = *bytemuck::from_bytes(&meta_buf);
481
482    let sample_start = offset + RASTER_GRID_METADATA_SIZE;
483    let sample_bytes_len = (meta.sample_count as usize) * 4;
484    if sample_start + sample_bytes_len > bytes.len() {
485        return Err(FieldSectionError::BufferTooSmallForDescriptors);
486    }
487
488    let raw_slice = &bytes[sample_start..sample_start + sample_bytes_len];
489    let samples: &'a [f32] = bytemuck::try_cast_slice(raw_slice)
490        .map_err(|_| FieldSectionError::BufferTooSmallForDescriptors)?;
491
492    Ok((meta, samples))
493}
494
495/// Compute the byte size needed to encode the given number of fields.
496pub fn field_section_size(field_count: usize) -> usize {
497    FIELD_SECTION_HEADER_SIZE + field_count * FIELD_DESCRIPTOR_SIZE
498}
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503
504    #[test]
505    fn empty_field_section_round_trip() {
506        let entries: Vec<FieldEntry> = vec![];
507        let size = field_section_size(0);
508        assert_eq!(size, FIELD_SECTION_HEADER_SIZE);
509        let mut buf = vec![0u8; size];
510        let written = encode_field_section(&entries, &mut buf).unwrap();
511        assert_eq!(written, FIELD_SECTION_HEADER_SIZE);
512        let (header, descs) = decode_field_section(&buf).unwrap();
513        assert_eq!(header.magic, FIELD_SECTION_MAGIC);
514        assert_eq!(header.version, FIELD_SECTION_VERSION);
515        assert_eq!(header.field_count, 0);
516        assert!(descs.is_empty());
517    }
518
519    #[test]
520    fn single_field_round_trip() {
521        let entries = vec![FieldEntry::new(
522            0x1234567890ABCDEF, // name_hash
523            0xFEDCBA0987654321, // unit_hash
524            FieldTypeKind::Scalar,
525            FieldSupportKind::Region,
526            FieldRepresentationKind::Grid,
527        )];
528        let size = field_section_size(1);
529        assert_eq!(size, FIELD_SECTION_HEADER_SIZE + FIELD_DESCRIPTOR_SIZE);
530        let mut buf = vec![0u8; size];
531        encode_field_section(&entries, &mut buf).unwrap();
532        let (header, descs) = decode_field_section(&buf).unwrap();
533        assert_eq!(header.field_count, 1);
534        assert_eq!(descs.len(), 1);
535        assert_eq!(descs[0].name_hash, 0x1234567890ABCDEF);
536        assert_eq!(descs[0].unit_hash, 0xFEDCBA0987654321);
537        assert_eq!(descs[0].type_kind, FieldTypeKind::Scalar as u8);
538        assert_eq!(descs[0].support, FieldSupportKind::Region as u8);
539        assert_eq!(descs[0].representation, FieldRepresentationKind::Grid as u8);
540        assert_eq!(descs[0].sample_offset, 0); // v0: no samples
541    }
542
543    #[test]
544    fn multiple_fields_round_trip() {
545        let entries = vec![
546            FieldEntry::new(
547                100,
548                200,
549                FieldTypeKind::Scalar,
550                FieldSupportKind::Region,
551                FieldRepresentationKind::Grid,
552            ),
553            FieldEntry::new(
554                101,
555                201,
556                FieldTypeKind::Vector,
557                FieldSupportKind::Point,
558                FieldRepresentationKind::Mesh,
559            ),
560            FieldEntry::new(
561                102,
562                202,
563                FieldTypeKind::Spectral,
564                FieldSupportKind::Stream,
565                FieldRepresentationKind::Sampled,
566            ),
567        ];
568        let size = field_section_size(3);
569        let mut buf = vec![0u8; size];
570        encode_field_section(&entries, &mut buf).unwrap();
571        let (header, descs) = decode_field_section(&buf).unwrap();
572        assert_eq!(header.field_count, 3);
573        assert_eq!(descs.len(), 3);
574        assert_eq!(descs[0].name_hash, 100);
575        assert_eq!(descs[1].type_kind, FieldTypeKind::Vector as u8);
576        assert_eq!(
577            descs[2].representation,
578            FieldRepresentationKind::Sampled as u8
579        );
580    }
581
582    #[test]
583    fn bad_magic_rejected() {
584        let mut buf = vec![0u8; FIELD_SECTION_HEADER_SIZE];
585        let header = FieldSectionHeader {
586            magic: 0xDEADBEEF,
587            version: FIELD_SECTION_VERSION,
588            field_count: 0,
589            reserved: 0,
590        };
591        buf[..FIELD_SECTION_HEADER_SIZE].copy_from_slice(bytemuck::bytes_of(&header));
592        let err = decode_field_section(&buf).unwrap_err();
593        assert!(matches!(err, FieldSectionError::BadMagic(0xDEADBEEF)));
594    }
595
596    #[test]
597    fn unsupported_version_rejected() {
598        let mut buf = vec![0u8; FIELD_SECTION_HEADER_SIZE];
599        let header = FieldSectionHeader {
600            magic: FIELD_SECTION_MAGIC,
601            version: 99,
602            field_count: 0,
603            reserved: 0,
604        };
605        buf[..FIELD_SECTION_HEADER_SIZE].copy_from_slice(bytemuck::bytes_of(&header));
606        let err = decode_field_section(&buf).unwrap_err();
607        assert!(matches!(err, FieldSectionError::UnsupportedVersion(99)));
608    }
609
610    #[test]
611    fn buffer_too_small_rejected() {
612        let buf = [0u8; 8]; // too small for header (12 bytes)
613        let err = decode_field_section(&buf).unwrap_err();
614        assert!(matches!(err, FieldSectionError::BufferTooSmallForHeader));
615    }
616
617    #[test]
618    fn buffer_too_small_for_descriptors_rejected() {
619        let mut buf = vec![0u8; FIELD_SECTION_HEADER_SIZE + 16]; // room for header + half a descriptor
620        let header = FieldSectionHeader {
621            magic: FIELD_SECTION_MAGIC,
622            version: FIELD_SECTION_VERSION,
623            field_count: 1, // claims 1 descriptor but buffer is too small
624            reserved: 0,
625        };
626        buf[..FIELD_SECTION_HEADER_SIZE].copy_from_slice(bytemuck::bytes_of(&header));
627        let err = decode_field_section(&buf).unwrap_err();
628        assert!(matches!(
629            err,
630            FieldSectionError::BufferTooSmallForDescriptors
631        ));
632    }
633
634    #[test]
635    fn invalid_type_kind_rejected() {
636        let size = field_section_size(1);
637        let mut buf = vec![0u8; size];
638        let entries = vec![FieldEntry::new(
639            1,
640            2,
641            FieldTypeKind::Scalar,
642            FieldSupportKind::Region,
643            FieldRepresentationKind::Grid,
644        )];
645        encode_field_section(&entries, &mut buf).unwrap();
646        // Corrupt the type_kind byte. Within FieldDescriptor, type_kind is at
647        // offset 16 (after name_hash:u64 + unit_hash:u64). In the buffer, that's
648        // FIELD_SECTION_HEADER_SIZE + 16.
649        buf[FIELD_SECTION_HEADER_SIZE + 16] = 99;
650        let err = decode_field_section(&buf).unwrap_err();
651        assert!(matches!(err, FieldSectionError::InvalidTypeKind(99)));
652    }
653
654    #[test]
655    fn field_section_size_calculation() {
656        assert_eq!(field_section_size(0), 12);
657        assert_eq!(field_section_size(1), 44);
658        assert_eq!(field_section_size(10), 12 + 320);
659    }
660
661    #[test]
662    fn header_default_is_valid() {
663        let h = FieldSectionHeader::default();
664        assert_eq!(h.magic, FIELD_SECTION_MAGIC);
665        assert_eq!(h.version, FIELD_SECTION_VERSION);
666        assert_eq!(h.field_count, 0);
667        assert_eq!(h.reserved, 0);
668    }
669
670    #[test]
671    fn descriptor_default_is_valid() {
672        let d = FieldDescriptor::default();
673        assert_eq!(d.type_kind, FieldTypeKind::Scalar as u8);
674        assert_eq!(d.support, FieldSupportKind::Region as u8);
675        assert_eq!(d.representation, FieldRepresentationKind::Grid as u8);
676        assert_eq!(d.sample_offset, 0);
677    }
678
679    #[test]
680    fn continuous_raster_round_trip() {
681        let elev_samples = [100.5f32, 102.0, 105.5, 110.0];
682        let canopy_samples = [12.0f32, 14.5, 0.0, 8.2];
683
684        let fields = [
685            ContinuousRasterField {
686                name_hash: 0xAAAA,
687                unit_hash: 0xBBBB,
688                width: 2,
689                height: 2,
690                samples: &elev_samples,
691            },
692            ContinuousRasterField {
693                name_hash: 0xCCCC,
694                unit_hash: 0xDDDD,
695                width: 2,
696                height: 2,
697                samples: &canopy_samples,
698            },
699        ];
700
701        let mut buf = vec![0u8; 1024];
702        let written = encode_field_section_with_rasters(&fields, &mut buf).unwrap();
703        assert!(written > 0);
704
705        let (header, descs) = decode_field_section(&buf[..written]).unwrap();
706        assert_eq!(header.field_count, 2);
707        assert_eq!(descs.len(), 2);
708
709        let (meta0, samples0) = decode_field_raster_samples(&buf[..written], &descs[0]).unwrap();
710        assert_eq!(meta0.width, 2);
711        assert_eq!(meta0.height, 2);
712        assert_eq!(meta0.sample_count, 4);
713        assert_eq!(samples0, elev_samples);
714
715        let (meta1, samples1) = decode_field_raster_samples(&buf[..written], &descs[1]).unwrap();
716        assert_eq!(meta1.width, 2);
717        assert_eq!(meta1.height, 2);
718        assert_eq!(meta1.sample_count, 4);
719        assert_eq!(samples1, canopy_samples);
720    }
721}