1use bytemuck::{Pod, Zeroable};
20
21#[path = "field_section/checked.rs"]
22mod checked;
23pub use checked::{inspect_field_section, FieldInspection, FieldInspectionError, FieldInspectionLimits};
24
25pub const FIELD_SECTION_MAGIC: u32 = 0x4649454C;
27
28pub const FIELD_SECTION_VERSION: u16 = 0;
30
31pub const FIELD_SECTION_HEADER_SIZE: usize = 12;
33
34pub const FIELD_DESCRIPTOR_SIZE: usize = 32;
36
37pub const MAX_FIELDS_PER_SECTION: usize = 65535;
39
40#[repr(u8)]
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum FieldTypeKind {
44 Scalar = 0,
46 Vector = 1,
48 Tensor = 2,
50 Spectral = 3,
52}
53
54impl FieldTypeKind {
55 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#[repr(u8)]
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum FieldSupportKind {
71 Region = 0,
73 Point = 1,
75 Continuant = 2,
77 Stream = 3,
79}
80
81impl FieldSupportKind {
82 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#[repr(u8)]
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum FieldRepresentationKind {
98 Grid = 0,
100 Mesh = 1,
102 Particles = 2,
104 Analytic = 3,
106 Sampled = 4,
108}
109
110impl FieldRepresentationKind {
111 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#[repr(C)]
126#[derive(Debug, Clone, Copy, Pod, Zeroable)]
127pub struct FieldSectionHeader {
128 pub magic: u32,
130 pub version: u16,
132 pub field_count: u16,
134 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#[repr(C)]
151#[derive(Debug, Clone, Copy, Pod, Zeroable)]
152pub struct FieldDescriptor {
153 pub name_hash: u64,
155 pub unit_hash: u64,
157 pub type_kind: u8,
159 pub support: u8,
161 pub representation: u8,
163 pub reserved: u8,
165 pub reserved2: u32,
167 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#[derive(Debug, Clone, PartialEq, Eq)]
188pub enum FieldSectionError {
189 BufferTooSmallForHeader,
191 BufferTooSmallForDescriptors,
193 BadMagic(u32),
195 UnsupportedVersion(u16),
197 InvalidTypeKind(u8),
199 InvalidSupportKind(u8),
201 InvalidRepresentationKind(u8),
203 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#[derive(Debug, Clone)]
232pub struct FieldEntry {
233 pub name_hash: u64,
235 pub unit_hash: u64,
237 pub type_kind: FieldTypeKind,
239 pub support: FieldSupportKind,
241 pub representation: FieldRepresentationKind,
243}
244
245impl FieldEntry {
246 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, }
275 }
276}
277
278pub 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 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 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
316pub 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 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 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 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#[repr(C)]
376#[derive(Debug, Clone, Copy, Pod, Zeroable)]
377pub struct RasterGridMetadata {
378 pub width: u32,
380 pub height: u32,
382 pub sample_count: u32,
384 pub reserved: u32,
386}
387
388pub const RASTER_GRID_METADATA_SIZE: usize = 16;
389
390#[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
400pub 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 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 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 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
468pub 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
495pub 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, 0xFEDCBA0987654321, 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); }
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]; 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]; let header = FieldSectionHeader {
621 magic: FIELD_SECTION_MAGIC,
622 version: FIELD_SECTION_VERSION,
623 field_count: 1, 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 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}