ctb_formats_pan/
parser.rs

1/* SPDX-License-Identifier: MIT */
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! Parser for .pan files.
27
28#![allow(clippy::too_many_lines, reason = "complicated")]
29
30use serde::{Deserialize, Serialize};
31
32#[allow(
33    unused_imports,
34    clippy::wildcard_imports,
35    reason = "Standard workspace module prelude"
36)]
37use crate::utilities::*;
38
39/// Serde helper for serializing `Vec<u8>` as MacRoman-decoded UTF-8 string
40/// and deserializing from either a string or a byte sequence.
41pub mod serde_pan_bytes {
42    use ctb_formats_encoding::CharEncoding;
43    use serde::{
44        Deserializer, Serializer,
45        de::{self, Visitor},
46    };
47    use std::fmt;
48
49    /// Serializes byte slices into a MacRoman-decoded UTF-8 string.
50    pub fn serialize<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
51    where
52        S: Serializer,
53    {
54        let enc = CharEncoding::mac_roman();
55        let mut s = String::with_capacity(bytes.len());
56        for &b in bytes {
57            if let Ok(c) = ctb_formats_encoding::chr_char(enc, b) {
58                s.push(c);
59            } else {
60                s.push(char::from(b));
61            }
62        }
63        serializer.serialize_str(&s)
64    }
65
66    /// Deserializes a string or byte integer array back into `Vec<u8>`.
67    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
68    where
69        D: Deserializer<'de>,
70    {
71        struct BytesVisitor;
72
73        impl<'de> Visitor<'de> for BytesVisitor {
74            type Value = Vec<u8>;
75
76            fn expecting(
77                &self,
78                formatter: &mut fmt::Formatter<'_>,
79            ) -> fmt::Result {
80                formatter.write_str(
81                    "a string encoded as MacRoman or an array of byte integers",
82                )
83            }
84
85            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
86            where
87                E: de::Error,
88            {
89                let enc = CharEncoding::mac_roman();
90                let mut bytes = Vec::with_capacity(v.len());
91                for ch in v.chars() {
92                    let cp = u32::from(ch);
93                    if cp <= 0x7F {
94                        if let Ok(b) = u8::try_from(cp) {
95                            bytes.push(b);
96                        }
97                    } else if let Some(b) =
98                        ctb_formats_encoding::asc(enc, &ch.to_string())
99                    {
100                        bytes.push(b);
101                    } else if let Ok(b) = u8::try_from(cp) {
102                        bytes.push(b);
103                    } else {
104                        bytes.push(b'?');
105                    }
106                }
107                Ok(bytes)
108            }
109
110            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
111            where
112                A: de::SeqAccess<'de>,
113            {
114                let mut bytes = Vec::new();
115                while let Some(byte) = seq.next_element::<u8>()? {
116                    bytes.push(byte);
117                }
118                Ok(bytes)
119            }
120        }
121
122        deserializer.deserialize_any(BytesVisitor)
123    }
124}
125
126/// The leading u32 and symbolic prelude entries before tagged sections.
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128pub struct PanPrelude {
129    /// First 4 bytes of the file as little-endian u32.
130    pub first_u32_le: u32,
131    /// Decoded symbolic entries before the first section.
132    pub entries: Vec<PanPreludeEntry>,
133    /// Raw bytes for the entire prelude region.
134    #[serde(with = "serde_pan_bytes")]
135    pub raw_bytes: Vec<u8>,
136}
137
138/// A symbolic prelude entry (kind + name + optional pointer-like value).
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140pub struct PanPreludeEntry {
141    pub offset: usize,
142    pub kind: u8,
143    #[serde(with = "serde_pan_bytes")]
144    pub name_raw: Vec<u8>,
145    pub name: String,
146    pub has_zero_delimiter_before_value: bool,
147    pub value_u32_le: Option<u32>,
148}
149
150/// One top-level section in a PAN file. Note that the section names are
151/// sometimes immediately followed by a letter, so they might look like "DATAS"
152/// or "DATA2" but the real section name is "DATA".
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct PanSection {
155    /// Byte offset where the 4-byte section length begins.
156    pub offset: usize,
157    /// Declared section size in bytes, including the 4-byte size field.
158    pub declared_size: u32,
159    /// Section kind byte directly after the size field.
160    pub kind: u8,
161    /// Raw name bytes for this section.
162    #[serde(with = "serde_pan_bytes")]
163    pub name_raw: Vec<u8>,
164    /// Section name decoded as Mac OS Roman.
165    pub name: String,
166    /// Raw section payload bytes.
167    #[serde(with = "serde_pan_bytes")]
168    pub payload: Vec<u8>,
169}
170
171/// Parsed representation of a PAN file.
172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
173pub struct PanDocument {
174    pub prelude: PanPrelude,
175    pub sections: Vec<PanSection>,
176    pub schema: Option<PanSchema>,
177    pub data: Option<PanData>,
178    pub launch_form: Option<String>,
179    pub record_count: Option<usize>,
180    pub macros: Vec<PanMacroInfo>,
181    #[serde(with = "serde_pan_bytes")]
182    pub trailing_bytes: Vec<u8>,
183}
184
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
186pub struct PanMacroInfo {
187    pub name: String,
188    pub size: usize,
189    pub is_procedure: bool,
190    pub code: Option<String>,
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub ast: Option<crate::procedure_parser::PanProcedureAst>,
193    #[serde(with = "serde_pan_bytes")]
194    pub payload: Vec<u8>,
195}
196
197#[derive(
198    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default,
199)]
200pub enum PanJustification {
201    #[default]
202    Left,
203    Right,
204    Center,
205}
206
207#[derive(
208    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default,
209)]
210pub enum PanCapitalization {
211    #[default]
212    None,
213    AllUpper,
214    InitialCaps,
215}
216
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218pub struct PanData {
219    pub sections: Vec<PanDataSection>,
220    pub records: Vec<PanDataRecord>,
221    pub parse_warnings: Vec<String>,
222}
223
224#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
225pub struct PanDataSection {
226    pub offset: usize,
227    pub name: String,
228    #[serde(with = "serde_pan_bytes")]
229    pub header_bytes: Vec<u8>,
230    #[serde(with = "serde_pan_bytes")]
231    pub trailing_bytes: Vec<u8>,
232    pub record_count: usize,
233}
234
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236pub struct PanDataRecord {
237    pub index: usize,
238    pub section_offset: usize,
239    pub declared_size: u32,
240    pub fields: Vec<PanDataFieldValue>,
241    #[serde(with = "serde_pan_bytes")]
242    pub trailing_bytes: Vec<u8>,
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
246enum PanDataRecordFormat {
247    Le32,
248    Be32,
249    Byte8WithStatus,
250    Le24WithStatus,
251    Be16WithStatus,
252    Le16WithStatus,
253    Be16WithStatusNoMarker,
254    Le16WithStatusNoMarker,
255    Be24LargeRecord,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259pub struct PanDataFieldValue {
260    pub field_index: usize,
261    pub field_name: String,
262    pub field_type: PanFieldType,
263    pub type_label: String,
264    pub output_pattern: Option<String>,
265    pub formula: Option<String>,
266    #[serde(with = "serde_pan_bytes")]
267    pub raw_bytes: Vec<u8>,
268    pub value: PanDataValue,
269    pub formatted_value: Option<String>,
270}
271
272#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273pub enum PanDataValue {
274    Text(String),
275    Integer(String),
276    Fixed(String),
277    Float(String),
278    Date {
279        /// Formula date number (Julian day number), matching `date.rs`.
280        raw_serial: i64,
281        /// Human-readable `m/d/yy` form when conversion succeeds.
282        pan_date_mdy: Option<String>,
283    },
284    Unknown(String),
285}
286
287impl PanDataValue {
288    #[must_use]
289    pub fn to_display_string(&self) -> String {
290        match self {
291            Self::Text(s)
292            | Self::Integer(s)
293            | Self::Fixed(s)
294            | Self::Float(s)
295            | Self::Unknown(s) => s.clone(),
296            Self::Date {
297                pan_date_mdy,
298                raw_serial,
299            } => match pan_date_mdy {
300                Some(s) => s.clone(),
301                None => raw_serial.to_string(),
302            },
303        }
304    }
305}
306
307#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
308pub struct PanSchema {
309    pub names_section_offset: usize,
310    pub widths_section_offset: usize,
311    pub types_section_offset: usize,
312    pub fields: Vec<PanSchemaField>,
313}
314
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316pub struct PanSchemaField {
317    pub index: usize,
318    pub name: String,
319    pub width: u16,
320    pub type_code: u8,
321    pub type_label: String,
322    pub field_type: PanFieldType,
323    pub output_pattern: Option<String>,
324    pub formula: Option<String>,
325    pub default_value: Option<String>,
326    pub prompt: Option<String>,
327    pub link: Option<String>,
328    pub range: Option<String>,
329    pub digits: u8,
330    pub justification: PanJustification,
331    pub clairvoyance: bool,
332    pub capitalization: PanCapitalization,
333}
334
335impl Default for PanSchemaField {
336    fn default() -> Self {
337        Self {
338            index: 0,
339            name: String::new(),
340            width: 0,
341            type_code: 0,
342            type_label: "Text".to_string(),
343            field_type: PanFieldType::Text,
344            output_pattern: None,
345            formula: None,
346            default_value: None,
347            prompt: None,
348            link: None,
349            range: None,
350            digits: 0,
351            justification: PanJustification::Left,
352            clairvoyance: false,
353            capitalization: PanCapitalization::None,
354        }
355    }
356}
357
358#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
359pub enum PanFieldType {
360    Text,
361    Picture,
362    Choices,
363    Date,
364    Float,
365    Integer,
366    Fixed1,
367    Fixed2,
368    Fixed3,
369    Fixed4,
370    Unknown(u8),
371}
372
373/// Parse PAN bytes into a structured representation.
374pub fn parse_pan(pan_file: &[u8]) -> anyhow::Result<PanDocument> {
375    if pan_file.len() < 4 {
376        bail!("PAN file is too short to contain a prelude header")
377    }
378
379    let first_u32_le = read_u32_le(pan_file, 0)?;
380    let is_be = detect_is_big_endian(pan_file);
381    let (entries, first_section_offset) =
382        parse_prelude_entries(pan_file, is_be)?;
383    let raw_bytes = pan_file
384        .get(..first_section_offset)
385        .context("Prelude boundary extends beyond file end")?
386        .to_vec();
387    let prelude = PanPrelude {
388        first_u32_le,
389        entries: entries.clone(),
390        raw_bytes,
391    };
392    let (top_level_sections, consumed_until) =
393        parse_section_streams(pan_file, first_section_offset, &entries)?;
394    let sections = collect_sections_recursively(pan_file, &top_level_sections)?;
395    let schemas = extract_schemas_from_sections(&sections, is_be)?;
396    let schema = schemas.first().cloned();
397    let data = extract_data_from_sections(&sections, &schemas)?;
398    let launch_form = sections
399        .iter()
400        .find(|s| s.name == "LAUNCH")
401        .and_then(|s| parse_launch_payload(&s.payload));
402    let record_count = sections
403        .iter()
404        .find(|s| s.name == "RC")
405        .and_then(|s| parse_rc_payload(&s.payload, is_be))
406        .or_else(|| data.as_ref().map(|d| d.records.len()));
407    let macros = sections
408        .iter()
409        .find(|s| s.name == "MACROS")
410        .map(|s| parse_macros_payload(&s.payload))
411        // Reason for fallback: empty macros list if MACROS section is not found
412        .unwrap_or_default();
413    let trailing_full = pan_file
414        .get(consumed_until..)
415        .context("Consumed offset extends beyond file end")?;
416    let trailing_non_zero_end = trailing_full
417        .iter()
418        .rposition(|byte| *byte != 0)
419        // Reason for fallback: empty trailing PAN byte slice returns offset 0
420        .map_or(0, |idx| idx.saturating_add(1));
421    let trailing_bytes = trailing_full
422        .get(..trailing_non_zero_end)
423        .context("Could not trim trailing PAN bytes")?
424        .to_vec();
425
426    Ok(PanDocument {
427        prelude,
428        sections,
429        schema,
430        data,
431        launch_form,
432        record_count,
433        macros,
434        trailing_bytes,
435    })
436}
437
438fn detect_is_big_endian(pan_file: &[u8]) -> bool {
439    let Ok(size_be) = read_u32_be(pan_file, 0) else {
440        return false;
441    };
442    let Ok(file_len_u32) = u32::try_from(pan_file.len()) else {
443        return false;
444    };
445    size_be.saturating_add(4) == file_len_u32
446}
447
448/// Build a human-readable diagnostic message for missing PAN DATA rows.
449pub fn diagnose_missing_data(pan: &PanDocument) -> String {
450    let Some(schema) = pan.schema.as_ref() else {
451        return "PAN data is missing (schema is missing, so DATA rows cannot be decoded)"
452            .to_string();
453    };
454
455    let data_sections = pan
456        .sections
457        .iter()
458        .filter(|section| section.name.starts_with("DATA"))
459        .collect::<Vec<_>>();
460    if data_sections.is_empty() {
461        return "PAN data is missing (no top-level DATA sections found)"
462            .to_string();
463    }
464
465    let mut parsed_count = 0usize;
466    let mut failures = Vec::new();
467    for section in data_sections {
468        match parse_data_payload(&section.payload, section.offset, schema) {
469            Ok((records, _header, _trailing)) => {
470                parsed_count = parsed_count.saturating_add(records.len());
471            }
472            Err(error) => {
473                failures.push(format!(
474                    "offset={offset:#x}, name={name}, declared_size={declared_size}, payload_len={payload_len}: {error:#}",
475                    offset = section.offset,
476                    name = section.name,
477                    declared_size = section.declared_size,
478                    payload_len = section.payload.len(),
479                ));
480            }
481        }
482    }
483
484    if !failures.is_empty() {
485        let preview = failures
486            .iter()
487            .take(4)
488            .cloned()
489            .collect::<Vec<_>>()
490            .join(" | ");
491        let omitted = failures.len().saturating_sub(4);
492        if omitted == 0 {
493            return format!(
494                "PAN data is missing (failed to parse {} DATA sections; parsed row count from successful sections: {}): {}",
495                failures.len(),
496                parsed_count,
497                preview
498            );
499        }
500
501        return format!(
502            "PAN data is missing (failed to parse {} DATA sections; parsed row count from successful sections: {}): {} | ... and {} more failures",
503            failures.len(),
504            parsed_count,
505            preview,
506            omitted
507        );
508    }
509
510    "PAN data is missing (DATA sections were present and parseable, but produced no row metadata)"
511        .to_string()
512}
513
514fn parse_section_streams(
515    pan_file: &[u8],
516    first_section_offset: usize,
517    prelude_entries: &[PanPreludeEntry],
518) -> anyhow::Result<(Vec<PanSection>, usize)> {
519    let mut stream_starts = vec![first_section_offset];
520    for entry in prelude_entries {
521        let Some(pointer_u32) = entry.value_u32_le else {
522            continue;
523        };
524        let pointer = usize::try_from(pointer_u32)
525            .context("Prelude pointer does not fit in usize")?;
526        if pointer < first_section_offset {
527            continue;
528        }
529        if pointer.saturating_add(6) > pan_file.len() {
530            continue;
531        }
532        if !section_header_looks_valid(pan_file, pointer)? {
533            continue;
534        }
535        if !stream_starts.contains(&pointer) {
536            stream_starts.push(pointer);
537        }
538    }
539    stream_starts.sort_unstable();
540
541    let mut all_top_sections = Vec::new();
542    let mut seen_offsets = std::collections::BTreeSet::new();
543    let mut consumed_until = first_section_offset;
544
545    for stream_start in stream_starts {
546        let Ok((sections, stream_consumed_until)) =
547            parse_top_level_sections(pan_file, stream_start)
548        else {
549            continue;
550        };
551        consumed_until = consumed_until.max(stream_consumed_until);
552        for section in sections {
553            if seen_offsets.insert(section.offset) {
554                all_top_sections.push(section);
555            }
556        }
557    }
558
559    if all_top_sections.is_empty() {
560        bail!("No top-level PAN sections found at expected offsets")
561    }
562
563    all_top_sections.sort_by_key(|section| section.offset);
564    Ok((all_top_sections, consumed_until))
565}
566
567fn extract_data_from_sections(
568    sections: &[PanSection],
569    schemas: &[PanSchema],
570) -> anyhow::Result<Option<PanData>> {
571    if schemas.is_empty() {
572        return Ok(None);
573    }
574
575    let data_sections = sections
576        .iter()
577        .filter(|section| section.name.starts_with("DATA"))
578        .collect::<Vec<_>>();
579    if data_sections.is_empty() {
580        return Ok(None);
581    }
582
583    let mut all_records = Vec::new();
584    let mut metadata = Vec::new();
585    let mut parse_warnings = Vec::new();
586    for section in data_sections {
587        let schema = select_schema_for_data_section(schemas, section.offset)
588            .context(
589                "Expected at least one PAN schema for DATA section parsing",
590            )?;
591
592        if section
593            .payload
594            .get(..6)
595            .is_some_and(data_section_has_unsupported_marker)
596        {
597            continue;
598        }
599
600        let deobfuscated_storage;
601        let payload_ref = if is_obfuscated_data_payload(&section.payload) {
602            deobfuscated_storage =
603                deobfuscate_pan_data_payload(&section.payload)?;
604            &deobfuscated_storage
605        } else {
606            &section.payload
607        };
608
609        let parsed = parse_data_payload(payload_ref, section.offset, schema);
610        let Ok((records, header_bytes, trailing_bytes)) = parsed else {
611            let error =
612                parsed.err().context("Missing DATA section parse error")?;
613            parse_warnings.push(format!(
614                "Could not parse DATA section at offset {offset:#x} ({name}): {error:#}",
615                offset = section.offset,
616                name = section.name,
617            ));
618            continue;
619        };
620        let section_name = data_section_name(&section.name, &header_bytes)?;
621        let non_zero_count =
622            trailing_bytes.iter().filter(|byte| **byte != 0).count();
623        if non_zero_count > 0
624            && !(trailing_bytes.len() <= 2 && non_zero_count <= 1)
625        {
626            parse_warnings.push(format!(
627                "DATA section at offset {offset:#x} ({name}) has {non_zero_count} non-zero trailing bytes after parsed records",
628                offset = section.offset,
629                name = section_name,
630            ));
631        }
632        metadata.push(PanDataSection {
633            offset: section.offset,
634            name: section_name,
635            header_bytes,
636            trailing_bytes,
637            record_count: records.len(),
638        });
639        all_records.extend(records);
640    }
641
642    if metadata.is_empty() {
643        return Ok(None);
644    }
645
646    Ok(Some(PanData {
647        sections: metadata,
648        records: all_records,
649        parse_warnings,
650    }))
651}
652
653#[derive(Debug, Clone, Copy, PartialEq, Eq)]
654pub(crate) enum PanDataObfuscation {
655    Add { key_start: u8, step: u8 },
656    Sub { key_start: u8, step: u8 },
657}
658
659/// Detect parameters `PanDataObfuscation` for position-dependent XOR obfuscated
660/// DATA payload.
661///
662/// Panorama obfuscates DATA payloads using a linear key sequence.
663/// In databases with standard headers, the first 6 bytes of the DATA payload
664/// represent an empty prefix that decodes to `00 00 00 00 00 00` via
665/// `key_start + step * i`.
666/// In databases with large records , bytes 0, 4, and 5 decode to `0x00` via
667/// `key_start - step * i`.
668fn detect_data_obfuscation_params(
669    payload: &[u8],
670) -> Option<PanDataObfuscation> {
671    if payload.len() < 10 {
672        return None;
673    }
674    let &b0 = payload.first()?;
675    let &b1 = payload.get(1)?;
676
677    // 1. Consecutive additive header check: bytes 0..6 all have constant delta
678    let step_add = b1.wrapping_sub(b0);
679    if step_add != 0 {
680        let is_consecutive = (0..6u8).all(|i| {
681            let offset = i.wrapping_mul(step_add);
682            let expected = b0.wrapping_add(offset);
683            payload.get(usize::from(i)).copied() == Some(expected)
684        });
685        if is_consecutive {
686            return Some(PanDataObfuscation::Add {
687                key_start: b0,
688                step: step_add,
689            });
690        }
691    }
692
693    // 2. Large-record subtractive header check
694    if b0 == 0 {
695        return None;
696    }
697    let &b4 = payload.get(4)?;
698    let &b5 = payload.get(5)?;
699    let &b6 = payload.get(6)?;
700
701    let key_start = b0;
702    let diff = key_start.wrapping_sub(b4);
703    let step = diff.checked_div(4)?;
704    if diff.checked_rem(4) != Some(0) || step == 0 {
705        return None;
706    }
707
708    let key5 = key_start.wrapping_sub(step.wrapping_mul(5));
709    if (b5 ^ key5) != 0x00 {
710        return None;
711    }
712
713    let key6 = key_start.wrapping_sub(step.wrapping_mul(6));
714    let dec6 = b6 ^ key6;
715    if dec6 == 0xff || dec6 < 0x80 {
716        Some(PanDataObfuscation::Sub { key_start, step })
717    } else {
718        None
719    }
720}
721
722/// Check whether a DATA section payload is read-only, which uses
723/// position-dependent XOR obfuscation.
724fn is_obfuscated_data_payload(payload: &[u8]) -> bool {
725    detect_data_obfuscation_params(payload).is_some()
726}
727
728/// Deobfuscate DATA payload bytes using the Panorama position-dependent XOR key.
729fn deobfuscate_pan_data_payload(payload: &[u8]) -> Result<Vec<u8>> {
730    let mode = detect_data_obfuscation_params(payload)
731        .context("Missing expected DATA obfuscation parameters")?;
732
733    Ok(payload
734        .iter()
735        .enumerate()
736        .map(|(idx, &b)| {
737            // Reason for fallback: idx & 0xff is strictly <= 255 and fits in u8
738            let idx_u8 = u8::try_from(idx & 0xff).unwrap_or(0);
739            let key = match mode {
740                PanDataObfuscation::Add { key_start, step } => {
741                    key_start.wrapping_add(idx_u8.wrapping_mul(step))
742                }
743                PanDataObfuscation::Sub { key_start, step } => {
744                    key_start.wrapping_sub(idx_u8.wrapping_mul(step))
745                }
746            };
747            b ^ key
748        })
749        .collect())
750}
751
752fn select_schema_for_data_section(
753    schemas: &[PanSchema],
754    section_offset: usize,
755) -> Option<&PanSchema> {
756    schemas.iter().min_by_key(|schema| {
757        let distance = schema.names_section_offset.abs_diff(section_offset);
758        (distance, schema.names_section_offset > section_offset)
759    })
760}
761
762fn parse_data_payload(
763    payload: &[u8],
764    section_offset: usize,
765    schema: &PanSchema,
766) -> anyhow::Result<(Vec<PanDataRecord>, Vec<u8>, Vec<u8>)> {
767    if payload.len() < 2 {
768        bail!(
769            "DATA payload at offset {section_offset:#x} is smaller than 2-byte header"
770        );
771    }
772
773    let candidate_starts: &[usize] = if payload.len() >= 6 {
774        &[6, 4, 2, 0]
775    } else if payload.len() >= 4 {
776        &[4, 2, 0]
777    } else if payload.len() >= 2 {
778        &[2, 0]
779    } else {
780        &[0]
781    };
782
783    let mut selected = None;
784    let mut last_error = None;
785    for &start_candidate in candidate_starts {
786        match select_data_record_format(
787            payload,
788            start_candidate,
789            schema,
790            section_offset,
791        ) {
792            Ok(fmt) => {
793                selected = Some((start_candidate, fmt));
794                break;
795            }
796            Err(err) => {
797                last_error = Some(err);
798            }
799        }
800    }
801
802    let (start_cursor, record_format) = match selected {
803        Some(pair) => pair,
804        None => {
805            return Err(
806                // Reason for fallback: last_error holds candidate parse failure
807                last_error.unwrap_or_else(|| {
808                    anyhow::anyhow!("Could not determine DATA record format")
809                }),
810            );
811        }
812    };
813    let header_bytes = payload
814        .get(..start_cursor)
815        // Reason for fallback: start_cursor is within payload bounds
816        .unwrap_or_default()
817        .to_vec();
818    let mut cursor = start_cursor;
819    let mut records = Vec::new();
820    let mut record_format = record_format;
821    while cursor < payload.len() {
822        let remaining = payload
823            .get(cursor..)
824            .context("Invalid DATA payload cursor")?;
825        if remaining.iter().all(|byte| *byte == 0) {
826            break;
827        }
828        if cursor.saturating_add(4) > payload.len() {
829            break;
830        }
831
832        let record_index = records.len();
833        let parsed = parse_data_record_with_fallback(
834            payload,
835            cursor,
836            schema,
837            section_offset,
838            record_index,
839            record_format,
840        )?;
841        let (row, record_end, selected_format) = parsed;
842        if row.declared_size == 0 {
843            break;
844        }
845        record_format = selected_format;
846        records.push(row);
847        cursor = record_end;
848    }
849
850    let trailing_bytes = payload
851        .get(cursor..)
852        .context("Could not read DATA payload trailing bytes")?
853        .to_vec();
854
855    Ok((records, header_bytes, trailing_bytes))
856}
857
858fn parse_data_record_with_fallback(
859    payload: &[u8],
860    cursor: usize,
861    schema: &PanSchema,
862    section_offset: usize,
863    record_index: usize,
864    record_format: PanDataRecordFormat,
865) -> anyhow::Result<(PanDataRecord, usize, PanDataRecordFormat)> {
866    let primary_parse = parse_data_record_at_cursor(
867        payload,
868        cursor,
869        schema,
870        section_offset,
871        record_index,
872        record_format,
873    );
874    if let Ok((row, record_end)) = primary_parse {
875        return Ok((row, record_end, record_format));
876    }
877
878    let mut parse_errors = vec![format!(
879        "{}: {}",
880        record_format_label(record_format),
881        primary_parse.err().context("Missing primary parse error")?
882    )];
883
884    if let Ok(header_candidates) = parse_data_record_headers(payload, cursor) {
885        for (_, _, candidate_format, _) in header_candidates {
886            if candidate_format == record_format {
887                continue;
888            }
889
890            let candidate_parse = parse_data_record_at_cursor(
891                payload,
892                cursor,
893                schema,
894                section_offset,
895                record_index,
896                candidate_format,
897            );
898            if let Ok((row, record_end)) = candidate_parse {
899                return Ok((row, record_end, candidate_format));
900            }
901
902            parse_errors.push(format!(
903                "{}: {}",
904                record_format_label(candidate_format),
905                candidate_parse
906                    .err()
907                    .context("Missing candidate parse error")?
908            ));
909        }
910    }
911
912    if record_index > 0 {
913        let empty_trailing = PanDataRecord {
914            index: record_index,
915            section_offset,
916            declared_size: 0,
917            fields: Vec::new(),
918            trailing_bytes: Vec::new(),
919        };
920        return Ok((empty_trailing, cursor, record_format));
921    }
922
923    let preview_end = cursor.saturating_add(16).min(payload.len());
924    let preview = payload
925        .get(cursor..preview_end)
926        .map(hex_string)
927        // Reason for fallback: cursor slice read error defaults raw byte preview string to empty
928        .unwrap_or_default();
929    bail!(
930        "DATA record decode failed at cursor {cursor:#x}; bytes={preview}; candidates={}",
931        parse_errors.join(" | ")
932    )
933}
934
935fn select_data_record_format(
936    payload: &[u8],
937    cursor: usize,
938    schema: &PanSchema,
939    section_offset: usize,
940) -> anyhow::Result<PanDataRecordFormat> {
941    let candidates = parse_data_record_headers(payload, cursor)?;
942    let mut formats = Vec::new();
943    for (_, _, format, _) in candidates {
944        if !formats.contains(&format) {
945            formats.push(format);
946        }
947    }
948
949    let mut best_format = None;
950    let mut best_count = 0usize;
951    let mut probe_errors = Vec::new();
952
953    for format in formats {
954        let mut probe_cursor = cursor;
955        let mut count = 0usize;
956        let mut first_error = None;
957
958        while count < 8 && probe_cursor < payload.len() {
959            let Some(remaining) = payload.get(probe_cursor..) else {
960                break;
961            };
962            if remaining.iter().all(|byte| *byte == 0) {
963                break;
964            }
965
966            let header = parse_data_record_header_for_format(
967                payload,
968                probe_cursor,
969                format,
970            );
971            let Ok((declared_size_usize, record_header_size)) = header else {
972                first_error = Some(
973                    header
974                        .err()
975                        .context("Missing probe header error")?
976                        .to_string(),
977                );
978                break;
979            };
980            let record_end = probe_cursor
981                .checked_add(declared_size_usize)
982                .context("Probe DATA record boundary overflow")?;
983            if record_end > payload.len() {
984                first_error =
985                    Some("Probe DATA record extends past payload".to_string());
986                break;
987            }
988
989            let Some(row_payload) = payload.get(
990                probe_cursor.saturating_add(record_header_size)..record_end,
991            ) else {
992                first_error =
993                    Some("Probe DATA row payload slice failed".to_string());
994                break;
995            };
996            let declared_size_u32 = u32::try_from(declared_size_usize)
997                .context("Probe DATA record size does not fit in u32")?;
998            if let Err(error) = parse_data_record(
999                row_payload,
1000                schema,
1001                section_offset,
1002                count,
1003                declared_size_u32,
1004                format,
1005            ) {
1006                first_error = Some(error.to_string());
1007                break;
1008            }
1009
1010            count = count.saturating_add(1);
1011            probe_cursor = record_end;
1012        }
1013
1014        if count > best_count {
1015            best_count = count;
1016            best_format = Some(format);
1017        }
1018
1019        if let Some(error) = first_error {
1020            probe_errors.push(format!(
1021                "{}: {}",
1022                record_format_label(format),
1023                error
1024            ));
1025        }
1026    }
1027
1028    if let Some(format) = best_format {
1029        if best_count > 0 {
1030            return Ok(format);
1031        }
1032    }
1033
1034    let summary = if probe_errors.is_empty() {
1035        "no probe candidates succeeded".to_string()
1036    } else {
1037        probe_errors.join(" | ")
1038    };
1039    bail!("Could not select DATA record format: {summary}")
1040}
1041
1042#[expect(clippy::similar_names, reason = "field names matching specification")]
1043fn parse_data_record_headers(
1044    payload: &[u8],
1045    cursor: usize,
1046) -> anyhow::Result<Vec<(usize, usize, PanDataRecordFormat, &'static str)>> {
1047    if cursor.saturating_add(4) > payload.len() {
1048        if cursor < payload.len() {
1049            let b0 = *payload
1050                .get(cursor)
1051                .context("DATA record length is truncated")?;
1052            if (2..0xfe).contains(&b0) {
1053                let mut candidates = Vec::new();
1054                let mut dedupe = Vec::new();
1055                add_data_record_header_candidate(
1056                    &mut candidates,
1057                    &mut dedupe,
1058                    payload.len(),
1059                    cursor,
1060                    usize::from(b0),
1061                    1,
1062                    PanDataRecordFormat::Byte8WithStatus,
1063                )?;
1064                if !candidates.is_empty() {
1065                    return Ok(candidates);
1066                }
1067            }
1068        }
1069        bail!("DATA record length is truncated")
1070    }
1071
1072    let mut candidates = Vec::new();
1073    let mut dedupe = Vec::new();
1074
1075    let b0 = *payload
1076        .get(cursor)
1077        .context("Could not read DATA record byte 0")?;
1078
1079    let len16_high_byte = payload
1080        .get(cursor.saturating_add(1))
1081        .copied()
1082        .context("Could not read DATA record length high byte")?;
1083    let len16_low_byte = payload
1084        .get(cursor.saturating_add(2))
1085        .copied()
1086        .context("Could not read DATA record length low byte")?;
1087    let be16_record_size =
1088        usize::from(u16::from_be_bytes([len16_high_byte, len16_low_byte]));
1089
1090    if b0 == 0xfe {
1091        add_data_record_header_candidate(
1092            &mut candidates,
1093            &mut dedupe,
1094            payload.len(),
1095            cursor,
1096            be16_record_size,
1097            6,
1098            PanDataRecordFormat::Be16WithStatus,
1099        )?;
1100    }
1101
1102    if b0 == 0xff {
1103        let b1 = usize::from(
1104            *payload
1105                .get(cursor.saturating_add(1))
1106                .context("Could not read BE24 len 1")?,
1107        );
1108        let b2 = usize::from(
1109            *payload
1110                .get(cursor.saturating_add(2))
1111                .context("Could not read BE24 len 2")?,
1112        );
1113        let b3 = usize::from(
1114            *payload
1115                .get(cursor.saturating_add(3))
1116                .context("Could not read BE24 len 3")?,
1117        );
1118        let be24_record_size = (b1 << 16) | (b2 << 8) | b3;
1119        if be24_record_size >= 15 {
1120            add_data_record_header_candidate(
1121                &mut candidates,
1122                &mut dedupe,
1123                payload.len(),
1124                cursor,
1125                be24_record_size,
1126                7,
1127                PanDataRecordFormat::Be24LargeRecord,
1128            )?;
1129        }
1130    }
1131
1132    if (2..0xfe).contains(&b0) {
1133        let b0_usize = usize::from(b0);
1134        if payload.get(cursor.saturating_add(b0_usize).saturating_sub(1))
1135            == Some(&b0)
1136        {
1137            add_data_record_header_candidate(
1138                &mut candidates,
1139                &mut dedupe,
1140                payload.len(),
1141                cursor,
1142                b0_usize,
1143                4,
1144                PanDataRecordFormat::Byte8WithStatus,
1145            )?;
1146        }
1147    }
1148
1149    if b0 != 0xfe && b0 != 0xff {
1150        let declared_size_le = read_u32_le(payload, cursor)?;
1151        let declared_size_le = usize::try_from(declared_size_le)
1152            .context("DATA record size does not fit in usize")?;
1153        add_data_record_header_candidate(
1154            &mut candidates,
1155            &mut dedupe,
1156            payload.len(),
1157            cursor,
1158            declared_size_le,
1159            4,
1160            PanDataRecordFormat::Le32,
1161        )?;
1162
1163        let declared_size_be = read_u32_be(payload, cursor)?;
1164        let declared_size_be = usize::try_from(declared_size_be)
1165            .context("DATA record BE size does not fit in usize")?;
1166        add_data_record_header_candidate(
1167            &mut candidates,
1168            &mut dedupe,
1169            payload.len(),
1170            cursor,
1171            declared_size_be,
1172            4,
1173            PanDataRecordFormat::Be32,
1174        )?;
1175
1176        let len24_low_byte = payload
1177            .get(cursor)
1178            .copied()
1179            .context("Could not read DATA record length low byte")?;
1180        let len24_middle_byte = payload
1181            .get(cursor.saturating_add(1))
1182            .copied()
1183            .context("Could not read DATA record length middle byte")?;
1184        let len24_high_byte = payload
1185            .get(cursor.saturating_add(2))
1186            .copied()
1187            .context("Could not read DATA record length high byte")?;
1188        let le24_record_size = usize::try_from(u32::from_le_bytes([
1189            len24_low_byte,
1190            len24_middle_byte,
1191            len24_high_byte,
1192            0,
1193        ]))
1194        .context("LE24 record size does not fit in usize")?;
1195        add_data_record_header_candidate(
1196            &mut candidates,
1197            &mut dedupe,
1198            payload.len(),
1199            cursor,
1200            le24_record_size,
1201            4,
1202            PanDataRecordFormat::Le24WithStatus,
1203        )?;
1204
1205        let le16_record_size =
1206            usize::from(u16::from_le_bytes([len16_high_byte, len16_low_byte]));
1207        add_data_record_header_candidate(
1208            &mut candidates,
1209            &mut dedupe,
1210            payload.len(),
1211            cursor,
1212            le16_record_size,
1213            5,
1214            PanDataRecordFormat::Le16WithStatus,
1215        )?;
1216        add_data_record_header_candidate(
1217            &mut candidates,
1218            &mut dedupe,
1219            payload.len(),
1220            cursor,
1221            le16_record_size,
1222            4,
1223            PanDataRecordFormat::Le16WithStatusNoMarker,
1224        )?;
1225    }
1226
1227    if b0 == 0xfe {
1228        add_data_record_header_candidate(
1229            &mut candidates,
1230            &mut dedupe,
1231            payload.len(),
1232            cursor,
1233            be16_record_size,
1234            4,
1235            PanDataRecordFormat::Be16WithStatusNoMarker,
1236        )?;
1237    }
1238
1239    if candidates.is_empty() {
1240        bail!("DATA record has unsupported length encoding")
1241    }
1242
1243    Ok(candidates)
1244}
1245
1246fn add_data_record_header_candidate(
1247    candidates: &mut Vec<(usize, usize, PanDataRecordFormat, &'static str)>,
1248    dedupe: &mut Vec<(usize, usize, PanDataRecordFormat)>,
1249    payload_len: usize,
1250    cursor: usize,
1251    declared_size: usize,
1252    header_size: usize,
1253    format: PanDataRecordFormat,
1254) -> anyhow::Result<()> {
1255    let minimum = header_size.saturating_add(1);
1256    if declared_size < minimum {
1257        return Ok(());
1258    }
1259
1260    let record_end = cursor
1261        .checked_add(declared_size)
1262        .context("DATA record candidate boundary overflow")?;
1263    let key = (declared_size, header_size, format);
1264    if record_end <= payload_len && !dedupe.contains(&key) {
1265        dedupe.push(key);
1266        candidates.push((
1267            declared_size,
1268            header_size,
1269            format,
1270            record_format_label(format),
1271        ));
1272    }
1273
1274    Ok(())
1275}
1276
1277#[expect(clippy::too_many_lines, reason = "+/- more readable")]
1278fn parse_data_record_header_for_format(
1279    payload: &[u8],
1280    cursor: usize,
1281    format: PanDataRecordFormat,
1282) -> anyhow::Result<(usize, usize)> {
1283    if cursor.saturating_add(4) > payload.len() {
1284        bail!("DATA record length is truncated")
1285    }
1286
1287    match format {
1288        PanDataRecordFormat::Le32 => {
1289            let declared_size_u32 = read_u32_le(payload, cursor)?;
1290            let declared_size = usize::try_from(declared_size_u32)
1291                .context("DATA record LE size does not fit in usize")?;
1292            if declared_size < 5 {
1293                bail!("DATA record LE32 size is too small")
1294            }
1295            Ok((declared_size, 4))
1296        }
1297        PanDataRecordFormat::Be32 => {
1298            let declared_size_u32 = read_u32_be(payload, cursor)?;
1299            let declared_size = usize::try_from(declared_size_u32)
1300                .context("DATA record BE size does not fit in usize")?;
1301            if declared_size < 5 {
1302                bail!("DATA record BE32 size is too small")
1303            }
1304            Ok((declared_size, 4))
1305        }
1306        PanDataRecordFormat::Byte8WithStatus => {
1307            let b0 = payload
1308                .get(cursor)
1309                .copied()
1310                .context("DATA Byte8 record byte is missing")?;
1311            if !(2..0xfe).contains(&b0) {
1312                bail!("DATA Byte8 record size is outside 2..=0xfd")
1313            }
1314            let b0_usize = usize::from(b0);
1315            if payload.get(cursor.saturating_add(b0_usize).saturating_sub(1))
1316                != Some(&b0)
1317            {
1318                bail!("DATA Byte8 record trailer mismatch")
1319            }
1320            Ok((b0_usize, 4))
1321        }
1322        PanDataRecordFormat::Le24WithStatus => {
1323            let len_lo = payload
1324                .get(cursor)
1325                .copied()
1326                .context("DATA LE24 length low byte is missing")?;
1327            if len_lo == 0xfe {
1328                bail!("DATA record starts with 0xfe marker, not LE24");
1329            }
1330            let len_mid = payload
1331                .get(cursor.saturating_add(1))
1332                .copied()
1333                .context("DATA LE24 length middle byte is missing")?;
1334            let len_hi = payload
1335                .get(cursor.saturating_add(2))
1336                .copied()
1337                .context("DATA LE24 length high byte is missing")?;
1338            let declared_size = usize::from(len_lo)
1339                | (usize::from(len_mid) << 8)
1340                | (usize::from(len_hi) << 16);
1341            if declared_size < 5 {
1342                bail!("DATA record LE24 size is too small")
1343            }
1344            Ok((declared_size, 4))
1345        }
1346        PanDataRecordFormat::Be16WithStatus => {
1347            let prefix = payload
1348                .get(cursor)
1349                .copied()
1350                .context("DATA BE16 prefix byte is missing")?;
1351            if prefix != 0xfe {
1352                bail!("DATA BE16 prefix byte is not 0xfe")
1353            }
1354            let len_hi = payload
1355                .get(cursor.saturating_add(1))
1356                .copied()
1357                .context("DATA BE16 length high byte is missing")?;
1358            let len_lo = payload
1359                .get(cursor.saturating_add(2))
1360                .copied()
1361                .context("DATA BE16 length low byte is missing")?;
1362            let declared_size =
1363                usize::from(u16::from_be_bytes([len_hi, len_lo]));
1364            if declared_size < 7 {
1365                bail!("DATA record BE16 size is too small")
1366            }
1367            Ok((declared_size, 6))
1368        }
1369        PanDataRecordFormat::Le16WithStatus => {
1370            let marker = payload
1371                .get(cursor.saturating_add(3))
1372                .copied()
1373                .context("DATA LE16 marker byte is missing")?;
1374            if marker != 0 {
1375                bail!("DATA LE16 marker byte is not zero")
1376            }
1377            let len_hi = payload
1378                .get(cursor.saturating_add(1))
1379                .copied()
1380                .context("DATA LE16 length high byte is missing")?;
1381            let len_lo = payload
1382                .get(cursor.saturating_add(2))
1383                .copied()
1384                .context("DATA LE16 length low byte is missing")?;
1385            let declared_size =
1386                usize::from(u16::from_le_bytes([len_hi, len_lo]));
1387            if declared_size < 6 {
1388                bail!("DATA record LE16 size is too small")
1389            }
1390            Ok((declared_size, 5))
1391        }
1392        PanDataRecordFormat::Be16WithStatusNoMarker => {
1393            let prefix = payload
1394                .get(cursor)
1395                .copied()
1396                .context("DATA BE16 no-marker prefix byte is missing")?;
1397            if prefix != 0xfe {
1398                bail!("DATA BE16 no-marker prefix byte is not 0xfe")
1399            }
1400            let len_hi = payload
1401                .get(cursor.saturating_add(1))
1402                .copied()
1403                .context("DATA BE16 no-marker length high byte is missing")?;
1404            let len_lo = payload
1405                .get(cursor.saturating_add(2))
1406                .copied()
1407                .context("DATA BE16 no-marker length low byte is missing")?;
1408            let declared_size =
1409                usize::from(u16::from_be_bytes([len_hi, len_lo]));
1410            if declared_size < 5 {
1411                bail!("DATA record BE16 no-marker size is too small")
1412            }
1413            Ok((declared_size, 4))
1414        }
1415        PanDataRecordFormat::Le16WithStatusNoMarker => {
1416            let len_hi = payload
1417                .get(cursor.saturating_add(1))
1418                .copied()
1419                .context("DATA LE16 no-marker length high byte is missing")?;
1420            let len_lo = payload
1421                .get(cursor.saturating_add(2))
1422                .copied()
1423                .context("DATA LE16 no-marker length low byte is missing")?;
1424            let declared_size =
1425                usize::from(u16::from_le_bytes([len_hi, len_lo]));
1426            if declared_size < 5 {
1427                bail!("DATA record LE16 no-marker size is too small")
1428            }
1429            Ok((declared_size, 4))
1430        }
1431        PanDataRecordFormat::Be24LargeRecord => {
1432            let prefix = payload
1433                .get(cursor)
1434                .copied()
1435                .context("DATA BE24 prefix byte is missing")?;
1436            if prefix != 0xff {
1437                bail!("DATA BE24 prefix byte is not 0xff");
1438            }
1439            let b1 = usize::from(
1440                payload
1441                    .get(cursor.saturating_add(1))
1442                    .copied()
1443                    .context("DATA BE24 len 1 missing")?,
1444            );
1445            let b2 = usize::from(
1446                payload
1447                    .get(cursor.saturating_add(2))
1448                    .copied()
1449                    .context("DATA BE24 len 2 missing")?,
1450            );
1451            let b3 = usize::from(
1452                payload
1453                    .get(cursor.saturating_add(3))
1454                    .copied()
1455                    .context("DATA BE24 len 3 missing")?,
1456            );
1457            let declared_size = (b1 << 16) | (b2 << 8) | b3;
1458            if declared_size < 15 {
1459                bail!("DATA record BE24 size is too small");
1460            }
1461            Ok((declared_size, 7))
1462        }
1463    }
1464}
1465
1466fn parse_data_record_at_cursor(
1467    payload: &[u8],
1468    cursor: usize,
1469    schema: &PanSchema,
1470    section_offset: usize,
1471    record_index: usize,
1472    format: PanDataRecordFormat,
1473) -> anyhow::Result<(PanDataRecord, usize)> {
1474    let (declared_size_usize, record_header_size) =
1475        parse_data_record_header_for_format(payload, cursor, format)
1476            .with_context(|| {
1477                format!(
1478                    "DATA record header parse failed at cursor {cursor:#x} using {}",
1479                    record_format_label(format)
1480                )
1481            })?;
1482    let declared_size = u32::try_from(declared_size_usize)
1483        .context("DATA record size does not fit in u32")?;
1484    let record_end = cursor
1485        .checked_add(declared_size_usize)
1486        .context("DATA record boundary overflow")?;
1487    if record_end > payload.len() {
1488        bail!(
1489            "DATA record at section offset {section_offset:#x} extends past payload"
1490        );
1491    }
1492
1493    let (trailer_len, expected_trailer) =
1494        if format == PanDataRecordFormat::Be24LargeRecord {
1495            let b1 = *payload
1496                .get(cursor.saturating_add(1))
1497                .context("DATA BE24 len 1 missing")?;
1498            let b2 = *payload
1499                .get(cursor.saturating_add(2))
1500                .context("DATA BE24 len 2 missing")?;
1501            let b3 = *payload
1502                .get(cursor.saturating_add(3))
1503                .context("DATA BE24 len 3 missing")?;
1504            (4usize, Some([b3, b2, b1, 0xff]))
1505        } else if format == PanDataRecordFormat::Byte8WithStatus
1506            && record_header_size == 3
1507            && payload.get(record_end.saturating_sub(1)) == payload.get(cursor)
1508        {
1509            (1usize, None)
1510        } else {
1511            (0usize, None)
1512        };
1513
1514    if let Some(trailer) = expected_trailer {
1515        let trailer_start = record_end.saturating_sub(4);
1516        if trailer_start < cursor.saturating_add(record_header_size)
1517            || payload.get(trailer_start..record_end) != Some(&trailer[..])
1518        {
1519            bail!("DATA record BE24 reversed trailer mismatch");
1520        }
1521    }
1522
1523    let row_payload = payload
1524        .get(
1525            cursor.saturating_add(record_header_size)
1526                ..record_end.saturating_sub(trailer_len),
1527        )
1528        .context("Could not read DATA row payload")?;
1529    let row = parse_data_record(
1530        row_payload,
1531        schema,
1532        section_offset,
1533        record_index,
1534        declared_size,
1535        format,
1536    )
1537    .with_context(|| {
1538        format!(
1539            "DATA record decode failed at cursor {cursor:#x} using {}",
1540            record_format_label(format)
1541        )
1542    })?;
1543
1544    Ok((row, record_end))
1545}
1546
1547fn record_format_label(format: PanDataRecordFormat) -> &'static str {
1548    match format {
1549        PanDataRecordFormat::Le32 => "le32",
1550        PanDataRecordFormat::Be32 => "be32",
1551        PanDataRecordFormat::Byte8WithStatus => "status+byte8",
1552        PanDataRecordFormat::Le24WithStatus => "status+le24(no-marker)",
1553        PanDataRecordFormat::Be16WithStatus => "status+be16",
1554        PanDataRecordFormat::Le16WithStatus => "status+le16",
1555        PanDataRecordFormat::Be16WithStatusNoMarker => "status+be16(no-marker)",
1556        PanDataRecordFormat::Le16WithStatusNoMarker => "status+le16(no-marker)",
1557        PanDataRecordFormat::Be24LargeRecord => "status+be24(marker-ff)",
1558    }
1559}
1560
1561fn data_section_name(
1562    base_name: &str,
1563    header_bytes: &[u8],
1564) -> anyhow::Result<String> {
1565    let Some(marker) = header_bytes.first() else {
1566        return Ok(base_name.to_string());
1567    };
1568    if *marker == 0 {
1569        return Ok(base_name.to_string());
1570    }
1571    let Some(header_tail) = header_bytes.get(1..) else {
1572        return Ok(base_name.to_string());
1573    };
1574    if header_tail.iter().any(|byte| *byte != 0) {
1575        return Ok(base_name.to_string());
1576    }
1577
1578    let _marker_text = ctb_formats_encoding::decode(
1579        ctb_formats_encoding::CharEncoding::mac_roman(),
1580        &[*marker],
1581    )
1582    .context("Invalid MacRoman DATA section marker")?;
1583    Ok(base_name.to_string())
1584}
1585
1586fn data_section_has_unsupported_marker(header_bytes: &[u8]) -> bool {
1587    let Some(marker) = header_bytes.first().copied() else {
1588        return false;
1589    };
1590    if marker == 0 {
1591        return false;
1592    }
1593
1594    let Some(tail) = header_bytes.get(1..) else {
1595        return false;
1596    };
1597    if tail.iter().any(|byte| *byte != 0) {
1598        return false;
1599    }
1600
1601    !marker.is_ascii()
1602}
1603
1604fn extract_raw_field_slices<'a>(
1605    row_payload: &'a [u8],
1606    schema: &PanSchema,
1607    _record_format: PanDataRecordFormat,
1608) -> Vec<&'a [u8]> {
1609    let slice = row_payload;
1610
1611    let mut pos = 0usize;
1612    let mut std_fields = Vec::new();
1613    let mut std_valid = true;
1614    while pos < slice.len() {
1615        let Some(mut len_byte) = slice.get(pos).copied() else {
1616            std_valid = false;
1617            break;
1618        };
1619        let mut control_len = 0usize;
1620        if len_byte & 0xc0 == 0xc0 {
1621            control_len = 1;
1622            let Some(&actual_len) = slice.get(pos.saturating_add(1)) else {
1623                std_valid = false;
1624                break;
1625            };
1626            len_byte = actual_len;
1627        }
1628        let (header_len, payload_len) = if len_byte == 0x7e {
1629            let Some(&hi) = slice.get(pos.saturating_add(1)) else {
1630                std_valid = false;
1631                break;
1632            };
1633            let Some(&lo) = slice.get(pos.saturating_add(2)) else {
1634                std_valid = false;
1635                break;
1636            };
1637            let total_len = usize::from(u16::from_be_bytes([hi, lo]));
1638            (3usize, total_len.saturating_sub(3))
1639        } else if len_byte == 0x7f {
1640            let Some(&b1) = slice.get(pos.saturating_add(1)) else {
1641                std_valid = false;
1642                break;
1643            };
1644            let Some(&b2) = slice.get(pos.saturating_add(2)) else {
1645                std_valid = false;
1646                break;
1647            };
1648            let Some(&b3) = slice.get(pos.saturating_add(3)) else {
1649                std_valid = false;
1650                break;
1651            };
1652            let total_len = (usize::from(b1) << 16)
1653                | (usize::from(b2) << 8)
1654                | usize::from(b3);
1655            (4usize, total_len.saturating_sub(4))
1656        } else if len_byte == 0 {
1657            if std_fields.len() >= schema.fields.len() {
1658                break;
1659            }
1660            (1usize, 0usize)
1661        } else {
1662            let total_len = usize::from(len_byte);
1663            let overhead = 1usize.saturating_add(control_len);
1664            (1usize, total_len.saturating_sub(overhead))
1665        };
1666        let start = pos.saturating_add(control_len).saturating_add(header_len);
1667        let end = start.saturating_add(payload_len);
1668        if end > slice.len() {
1669            std_valid = false;
1670            break;
1671        }
1672        if let Some(f_slice) = slice.get(start..end) {
1673            std_fields.push(f_slice);
1674        }
1675        pos = end;
1676        if std_fields.len() == schema.fields.len() {
1677            break;
1678        }
1679    }
1680    if std_valid && std_fields.len() >= schema.fields.len() {
1681        std_fields
1682    } else {
1683        Vec::new()
1684    }
1685}
1686
1687fn parse_data_record(
1688    row_payload: &[u8],
1689    schema: &PanSchema,
1690    section_offset: usize,
1691    record_index: usize,
1692    declared_size: u32,
1693    record_format: PanDataRecordFormat,
1694) -> anyhow::Result<PanDataRecord> {
1695    if schema.fields.is_empty() {
1696        bail!("Cannot parse DATA records without schema fields");
1697    }
1698
1699    let raw_slices =
1700        extract_raw_field_slices(row_payload, schema, record_format);
1701    if !raw_slices.is_empty() {
1702        let mut values = Vec::with_capacity(schema.fields.len());
1703        for (field_position, field) in schema.fields.iter().enumerate() {
1704            if let Some(raw_bytes) = raw_slices.get(field_position) {
1705                push_data_field_with_raw_bytes(&mut values, field, raw_bytes)?;
1706            } else {
1707                append_empty_data_fields(
1708                    &mut values,
1709                    schema,
1710                    field_position,
1711                    "Could not get trailing DATA schema fields",
1712                )?;
1713                break;
1714            }
1715        }
1716
1717        return Ok(PanDataRecord {
1718            index: record_index,
1719            section_offset,
1720            declared_size,
1721            fields: values,
1722            trailing_bytes: Vec::new(),
1723        });
1724    }
1725
1726    let mut values = Vec::with_capacity(schema.fields.len());
1727    let mut cursor = 0usize;
1728    for (field_position, field) in schema.fields.iter().enumerate() {
1729        if cursor >= row_payload.len() {
1730            append_empty_data_fields(
1731                &mut values,
1732                schema,
1733                field_position,
1734                "Could not get trailing DATA schema fields",
1735            )?;
1736            break;
1737        }
1738
1739        let len_byte = *row_payload.get(cursor).with_context(|| {
1740            format!(
1741                "DATA row {record_index} in section {section_offset:#x} is missing field length"
1742            )
1743        })?;
1744        let (header_len, payload_len) = if len_byte == 0x7e {
1745            let hi = *row_payload.get(cursor.saturating_add(1)).with_context(|| {
1746                format!(
1747                    "DATA row {record_index} in section {section_offset:#x} is missing extended 0x7e high byte"
1748                )
1749            })?;
1750            let lo = *row_payload.get(cursor.saturating_add(2)).with_context(|| {
1751                format!(
1752                    "DATA row {record_index} in section {section_offset:#x} is missing extended 0x7e low byte"
1753                )
1754            })?;
1755            let total_len = usize::from(u16::from_be_bytes([hi, lo]));
1756            (3usize, total_len.saturating_sub(3))
1757        } else if len_byte == 0x7f {
1758            let b1 = *row_payload.get(cursor.saturating_add(1)).with_context(|| {
1759                format!(
1760                    "DATA row {record_index} in section {section_offset:#x} is missing extended 0x7f byte 1"
1761                )
1762            })?;
1763            let b2 = *row_payload.get(cursor.saturating_add(2)).with_context(|| {
1764                format!(
1765                    "DATA row {record_index} in section {section_offset:#x} is missing extended 0x7f byte 2"
1766                )
1767            })?;
1768            let b3 = *row_payload.get(cursor.saturating_add(3)).with_context(|| {
1769                format!(
1770                    "DATA row {record_index} in section {section_offset:#x} is missing extended 0x7f byte 3"
1771                )
1772            })?;
1773            let total_len = (usize::from(b1) << 16)
1774                | (usize::from(b2) << 8)
1775                | usize::from(b3);
1776            (4usize, total_len.saturating_sub(4))
1777        } else {
1778            let total_len = usize::from(len_byte);
1779            (1usize, total_len.saturating_sub(1))
1780        };
1781
1782        cursor = cursor
1783            .checked_add(header_len)
1784            .context("DATA row cursor overflow after field length")?;
1785        let payload_end = cursor
1786            .checked_add(payload_len)
1787            .context("DATA field payload boundary overflow")?;
1788        if payload_end > row_payload.len() {
1789            let available_len = row_payload.len().saturating_sub(cursor);
1790            let raw_bytes = row_payload
1791                .get(cursor..cursor.saturating_add(available_len))
1792                // Reason for fallback: slice boundary checked above
1793                .unwrap_or(&[]);
1794            push_data_field_with_raw_bytes(&mut values, field, raw_bytes)?;
1795            append_empty_data_fields(
1796                &mut values,
1797                schema,
1798                field_position.saturating_add(1),
1799                "Could not get trailing DATA schema fields",
1800            )?;
1801            cursor = row_payload.len();
1802            break;
1803        }
1804
1805        let raw_bytes = row_payload
1806            .get(cursor..payload_end)
1807            .context("Could not read DATA field payload bytes")?
1808            .to_vec();
1809        cursor = payload_end;
1810
1811        push_data_field_with_raw_bytes(&mut values, field, &raw_bytes)?;
1812    }
1813
1814    let trailing_bytes = row_payload
1815        .get(cursor..)
1816        .context("Could not read trailing bytes in DATA row")?
1817        .to_vec();
1818
1819    Ok(PanDataRecord {
1820        index: record_index,
1821        section_offset,
1822        declared_size,
1823        fields: values,
1824        trailing_bytes,
1825    })
1826}
1827
1828fn push_data_field_with_raw_bytes(
1829    values: &mut Vec<PanDataFieldValue>,
1830    field: &PanSchemaField,
1831    raw_bytes: &[u8],
1832) -> anyhow::Result<()> {
1833    let value = decode_data_field_value(field, raw_bytes)?;
1834    let formatted_value = format_data_field_value(field, &value)?;
1835    values.push(PanDataFieldValue {
1836        field_index: field.index,
1837        field_name: field.name.clone(),
1838        field_type: field.field_type.clone(),
1839        type_label: field.type_label.clone(),
1840        output_pattern: field.output_pattern.clone(),
1841        formula: field.formula.clone(),
1842        raw_bytes: raw_bytes.to_vec(),
1843        value,
1844        formatted_value,
1845    });
1846    Ok(())
1847}
1848
1849fn append_empty_data_fields(
1850    values: &mut Vec<PanDataFieldValue>,
1851    schema: &PanSchema,
1852    from_index: usize,
1853    context_message: &str,
1854) -> anyhow::Result<()> {
1855    let Some(remaining_fields) = schema.fields.get(from_index..) else {
1856        bail!("{context_message}")
1857    };
1858    for remaining_field in remaining_fields {
1859        push_data_field_with_raw_bytes(values, remaining_field, &[])?;
1860    }
1861    Ok(())
1862}
1863
1864fn decode_data_field_value(
1865    field: &PanSchemaField,
1866    raw_bytes: &[u8],
1867) -> anyhow::Result<PanDataValue> {
1868    let is_date_field = field.field_type == PanFieldType::Date
1869        || field.name.to_ascii_lowercase().contains("date");
1870
1871    if is_date_field && raw_bytes == [100, 174, 218] {
1872        return Ok(PanDataValue::Date {
1873            raw_serial: 0,
1874            pan_date_mdy: None,
1875        });
1876    }
1877
1878    match field.field_type {
1879        PanFieldType::Text => {
1880            if is_date_field && raw_bytes.len() == 2 {
1881                if let Ok((serial, pan_date_mdy)) =
1882                    decode_pan_date_field(raw_bytes)
1883                {
1884                    if serial > 2_400_000 && serial < 2_600_000 {
1885                        return Ok(PanDataValue::Date {
1886                            raw_serial: serial,
1887                            pan_date_mdy,
1888                        });
1889                    }
1890                }
1891            }
1892            let decoded = ctb_formats_encoding::decode(
1893                ctb_formats_encoding::CharEncoding::mac_roman(),
1894                raw_bytes,
1895            );
1896            if let Ok(decoded) = decoded {
1897                return Ok(PanDataValue::Text(decoded.replace('\r', "\n")));
1898            }
1899            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1900        }
1901        PanFieldType::Integer => {
1902            if raw_bytes.is_empty() {
1903                return Ok(PanDataValue::Integer(String::new()));
1904            }
1905            let integer = decode_i64_from_le_varint(raw_bytes);
1906            if let Ok(integer) = integer {
1907                return Ok(PanDataValue::Integer(integer.to_string()));
1908            }
1909            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1910        }
1911        PanFieldType::Fixed1 => {
1912            if raw_bytes.is_empty() {
1913                return Ok(PanDataValue::Fixed(String::new()));
1914            }
1915            let integer = decode_i64_from_le_varint(raw_bytes);
1916            if let Ok(integer) = integer {
1917                return Ok(PanDataValue::Fixed(format_fixed_point(
1918                    integer, 1u8,
1919                )?));
1920            }
1921            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1922        }
1923        PanFieldType::Fixed2 => {
1924            if raw_bytes.is_empty() {
1925                return Ok(PanDataValue::Fixed(String::new()));
1926            }
1927            let integer = decode_i64_from_le_varint(raw_bytes);
1928            if let Ok(integer) = integer {
1929                return Ok(PanDataValue::Fixed(format_fixed_point(
1930                    integer, 2u8,
1931                )?));
1932            }
1933            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1934        }
1935        PanFieldType::Fixed3 => {
1936            if raw_bytes.is_empty() {
1937                return Ok(PanDataValue::Fixed(String::new()));
1938            }
1939            let integer = decode_i64_from_le_varint(raw_bytes);
1940            if let Ok(integer) = integer {
1941                return Ok(PanDataValue::Fixed(format_fixed_point(
1942                    integer, 3u8,
1943                )?));
1944            }
1945            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1946        }
1947        PanFieldType::Fixed4 => {
1948            if raw_bytes.is_empty() {
1949                return Ok(PanDataValue::Fixed(String::new()));
1950            }
1951            let integer = decode_i64_from_le_varint(raw_bytes);
1952            if let Ok(integer) = integer {
1953                return Ok(PanDataValue::Fixed(format_fixed_point(
1954                    integer, 4u8,
1955                )?));
1956            }
1957            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1958        }
1959        PanFieldType::Float => {
1960            if raw_bytes.is_empty() {
1961                return Ok(PanDataValue::Float(String::new()));
1962            }
1963            if raw_bytes.len() != 8 {
1964                return Ok(PanDataValue::Unknown(hex_string(raw_bytes)));
1965            }
1966            let raw_float: [u8; 8] = <[u8; 8]>::try_from(raw_bytes)
1967                .context("Failed to read f64 bytes from DATA record")?;
1968            let float = f64::from_be_bytes(raw_float);
1969            Ok(PanDataValue::Float(float.to_string()))
1970        }
1971        PanFieldType::Date => {
1972            if let Ok((serial, pan_date_mdy)) = decode_pan_date_field(raw_bytes)
1973            {
1974                return Ok(PanDataValue::Date {
1975                    raw_serial: serial,
1976                    pan_date_mdy,
1977                });
1978            }
1979            let decoded = ctb_formats_encoding::decode(
1980                ctb_formats_encoding::CharEncoding::mac_roman(),
1981                raw_bytes,
1982            );
1983            if let Ok(decoded) = decoded {
1984                return Ok(PanDataValue::Text(decoded.replace('\r', "\n")));
1985            }
1986            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1987        }
1988        PanFieldType::Choices => {
1989            if raw_bytes.is_empty() {
1990                return Ok(PanDataValue::Unknown(String::new()));
1991            }
1992            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1993        }
1994        PanFieldType::Picture => {
1995            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1996        }
1997        PanFieldType::Unknown(_type_code) => {
1998            Ok(PanDataValue::Unknown(hex_string(raw_bytes)))
1999        }
2000    }
2001}
2002
2003fn format_data_field_value(
2004    field: &PanSchemaField,
2005    value: &PanDataValue,
2006) -> anyhow::Result<Option<String>> {
2007    let Some(pattern) = field.output_pattern.as_deref() else {
2008        return Ok(None);
2009    };
2010    if pattern.is_empty() {
2011        return Ok(None);
2012    }
2013
2014    match value {
2015        PanDataValue::Integer(integer) => {
2016            if integer.is_empty() {
2017                return Ok(None);
2018            }
2019            let number = integer.parse::<f64>().with_context(|| {
2020                format!(
2021                    "Could not parse integer '{integer}' as f64 for field '{field_name}'",
2022                    field_name = field.name
2023                )
2024            })?;
2025            crate::string::pattern::pattern(number, pattern).map(Some)
2026        }
2027        PanDataValue::Fixed(fixed) => {
2028            if fixed.is_empty() {
2029                return Ok(None);
2030            }
2031            let number = fixed.parse::<f64>().with_context(|| {
2032                format!(
2033                    "Could not parse fixed '{fixed}' as f64 for field '{field_name}'",
2034                    field_name = field.name
2035                )
2036            })?;
2037            let formatted = crate::string::pattern::pattern(number, pattern)
2038                .with_context(|| {
2039                    format!(
2040                        "Could not format fixed field '{}' with pattern '{}'",
2041                        field.name, pattern
2042                    )
2043                })?;
2044            Ok(Some(formatted))
2045        }
2046        PanDataValue::Float(float_value) => {
2047            if float_value.is_empty() {
2048                return Ok(None);
2049            }
2050            let number = float_value.parse::<f64>().with_context(|| {
2051                format!(
2052                    "Could not parse float '{float_value}' as f64 for field '{field_name}'",
2053                    field_name = field.name
2054                )
2055            })?;
2056            let formatted = crate::string::pattern::pattern(number, pattern)
2057                .with_context(|| {
2058                    format!(
2059                        "Could not format float field '{}' with pattern '{}'",
2060                        field.name, pattern
2061                    )
2062                })?;
2063            Ok(Some(formatted))
2064        }
2065        PanDataValue::Date { raw_serial, .. } => {
2066            if *raw_serial == 0 {
2067                return Ok(Some(String::new()));
2068            }
2069            let formatted = crate::date::datepattern(*raw_serial, pattern)
2070                .with_context(|| {
2071                    format!(
2072                        "Could not format date field '{}' with pattern '{}'",
2073                        field.name, pattern
2074                    )
2075                })?;
2076            Ok(Some(formatted))
2077        }
2078        PanDataValue::Text(_) | PanDataValue::Unknown(_) => Ok(None),
2079    }
2080}
2081
2082fn decode_pan_date_field(
2083    raw_bytes: &[u8],
2084) -> anyhow::Result<(i64, Option<String>)> {
2085    if raw_bytes.is_empty() || raw_bytes == [100, 174, 218] {
2086        return Ok((0, None));
2087    }
2088
2089    if raw_bytes.len() == 1 {
2090        let date_raw: [u8; 1] = <[u8; 1]>::try_from(raw_bytes)
2091            .context("Failed to read 1-byte PAN date payload")?;
2092        let day_offset = i64::from(i8::from_le_bytes(date_raw));
2093        let epoch = crate::date::datevalue(1984, 1, 24)
2094            .context("Could not compute PAN date epoch")?;
2095        let jdn = epoch
2096            .checked_add(day_offset)
2097            .context("PAN date offset overflow")?;
2098        let pan_date_mdy = crate::date::datestr(jdn).ok();
2099        return Ok((jdn, pan_date_mdy));
2100    }
2101
2102    if raw_bytes.len() == 2 {
2103        let date_raw: [u8; 2] = <[u8; 2]>::try_from(raw_bytes)
2104            .context("Failed to read 2-byte PAN date payload")?;
2105        let day_offset = i64::from(i16::from_le_bytes(date_raw));
2106        let epoch = crate::date::datevalue(1984, 1, 24)
2107            .context("Could not compute PAN date epoch")?;
2108        let jdn = epoch
2109            .checked_add(day_offset)
2110            .context("PAN date offset overflow")?;
2111        let pan_date_mdy = crate::date::datestr(jdn).ok();
2112        return Ok((jdn, pan_date_mdy));
2113    }
2114
2115    let serial = decode_i64_from_le_varint(raw_bytes)?;
2116    let pan_date_mdy = crate::date::datestr(serial).ok();
2117    Ok((serial, pan_date_mdy))
2118}
2119
2120fn decode_i64_from_le_varint(raw_bytes: &[u8]) -> anyhow::Result<i64> {
2121    if raw_bytes.is_empty() {
2122        return Ok(0);
2123    }
2124    if raw_bytes.len() > 8 {
2125        bail!(
2126            "Variable-length integer has {} bytes, max supported is 8",
2127            raw_bytes.len()
2128        )
2129    }
2130
2131    let mut full = [0u8; 8];
2132    let payload_len = raw_bytes.len();
2133    let destination = full
2134        .get_mut(..payload_len)
2135        .context("Could not copy variable-length integer bytes")?;
2136    destination.copy_from_slice(raw_bytes);
2137
2138    let sign_bit_set = raw_bytes.last().is_some_and(|last| (last & 0x80) != 0);
2139    if sign_bit_set {
2140        let extension = full
2141            .get_mut(payload_len..)
2142            .context("Could not sign-extend variable-length integer")?;
2143        extension.fill(0xff);
2144    }
2145
2146    Ok(i64::from_le_bytes(full))
2147}
2148
2149fn format_fixed_point(value: i64, scale: u8) -> Result<String> {
2150    if scale == 0 {
2151        return Ok(value.to_string());
2152    }
2153
2154    let scale_usize = usize::from(scale);
2155    let negative = value < 0;
2156    let mut digits = i128::from(value).abs().to_string();
2157
2158    if digits.len() <= scale_usize {
2159        let needed = scale_usize
2160            .checked_add(1)
2161            .and_then(|required| required.checked_sub(digits.len()))
2162            .context("fixed point scale padding overflow")?;
2163        let mut prefixed =
2164            String::with_capacity(needed.saturating_add(digits.len()));
2165        prefixed.push_str(&"0".repeat(needed));
2166        prefixed.push_str(&digits);
2167        digits = prefixed;
2168    }
2169
2170    let whole_len = digits
2171        .len()
2172        .checked_sub(scale_usize)
2173        .context("digits length underflow")?;
2174    let whole = digits
2175        .get(..whole_len)
2176        .context("whole digits slice out of bounds")?;
2177    let fraction = digits
2178        .get(whole_len..)
2179        .context("fraction digits slice out of bounds")?;
2180
2181    if negative {
2182        Ok(format!("-{whole}.{fraction}"))
2183    } else {
2184        Ok(format!("{whole}.{fraction}"))
2185    }
2186}
2187
2188fn hex_string(bytes: &[u8]) -> String {
2189    string::to_hex(bytes)
2190}
2191
2192fn parse_prelude_entries(
2193    pan_file: &[u8],
2194    is_be: bool,
2195) -> anyhow::Result<(Vec<PanPreludeEntry>, usize)> {
2196    let mut entries = Vec::new();
2197    let mut cursor = 4usize;
2198    while cursor.saturating_add(2) <= pan_file.len() {
2199        let kind = *pan_file
2200            .get(cursor)
2201            .context("Prelude cursor extends beyond file end")?;
2202        if !matches!(kind, 0x00..=0x03) {
2203            break;
2204        }
2205
2206        let name_len = usize::from(
2207            *pan_file
2208                .get(cursor.saturating_add(1))
2209                .context("Prelude name length byte is missing")?,
2210        );
2211        if name_len == 0 {
2212            bail!("Prelude entry at offset {cursor:#x} has empty name")
2213        }
2214
2215        let name_start = cursor
2216            .checked_add(2)
2217            .context("Prelude name start overflow")?;
2218        let name_end = name_start
2219            .checked_add(name_len)
2220            .context("Prelude name length overflow")?;
2221        if name_end > pan_file.len() {
2222            bail!("Prelude name at offset {cursor:#x} extends beyond file end")
2223        }
2224
2225        let name_raw = pan_file
2226            .get(name_start..name_end)
2227            .context("Prelude name range is invalid")?
2228            .to_vec();
2229        let name = ctb_formats_encoding::decode(
2230            ctb_formats_encoding::CharEncoding::mac_roman(),
2231            &name_raw,
2232        )
2233        .with_context(|| {
2234            format!("Invalid MacRoman prelude name at offset {cursor:#x}")
2235        })?;
2236
2237        let mut value_cursor = name_end;
2238        let mut has_zero_delimiter_before_value = false;
2239        if (name_end % 2) != 0 {
2240            has_zero_delimiter_before_value = true;
2241            value_cursor = value_cursor.saturating_add(1);
2242        }
2243
2244        let value_u32_le = match kind {
2245            0x00 | 0x01 => {
2246                let value = parse_prelude_kind_0_or_1_value(
2247                    pan_file,
2248                    cursor,
2249                    &mut value_cursor,
2250                    has_zero_delimiter_before_value,
2251                    is_be,
2252                )?;
2253                Some(value)
2254            }
2255            0x02 | 0x03 => parse_prelude_kind_2_or_3_value(
2256                pan_file,
2257                &mut value_cursor,
2258                is_be,
2259            )?,
2260            _ => bail!(
2261                "Unsupported prelude entry kind {kind:#x} at offset {cursor:#x}"
2262            ),
2263        };
2264
2265        entries.push(PanPreludeEntry {
2266            offset: cursor,
2267            kind,
2268            name_raw,
2269            name,
2270            has_zero_delimiter_before_value,
2271            value_u32_le,
2272        });
2273
2274        if value_cursor <= cursor {
2275            bail!("PAN prelude parser did not make progress")
2276        }
2277        cursor = value_cursor;
2278
2279        if matches!(kind, 0x02 | 0x03) && value_u32_le.is_none() {
2280            break;
2281        }
2282    }
2283
2284    if entries.is_empty() {
2285        bail!("PAN prelude has no symbolic entries")
2286    }
2287
2288    Ok((entries, cursor))
2289}
2290
2291fn parse_prelude_kind_0_or_1_value(
2292    pan_file: &[u8],
2293    entry_offset: usize,
2294    value_cursor: &mut usize,
2295    has_zero_delimiter_before_value: bool,
2296    is_be: bool,
2297) -> anyhow::Result<u32> {
2298    if (*value_cursor).saturating_add(4) > pan_file.len() {
2299        bail!(
2300            "Prelude value for entry at offset {entry_offset:#x} extends beyond file end"
2301        )
2302    }
2303
2304    let mut selected_value_cursor = *value_cursor;
2305    let boundary_after_unshifted = (*value_cursor)
2306        .checked_add(4)
2307        .context("Prelude boundary cursor overflow")?;
2308    let unshifted_score =
2309        prelude_boundary_score(pan_file, boundary_after_unshifted)?;
2310
2311    if !has_zero_delimiter_before_value && unshifted_score <= 1 && !is_be {
2312        let shifted_value_cursor = (*value_cursor)
2313            .checked_add(1)
2314            .context("Prelude value cursor overflow")?;
2315        let shifted_score =
2316            if shifted_value_cursor.saturating_add(4) <= pan_file.len() {
2317                let boundary_after_shifted = shifted_value_cursor
2318                    .checked_add(4)
2319                    .context("Prelude shifted boundary cursor overflow")?;
2320                prelude_boundary_score(pan_file, boundary_after_shifted)?
2321            } else {
2322                0
2323            };
2324
2325        if shifted_score > unshifted_score {
2326            selected_value_cursor = shifted_value_cursor;
2327        }
2328    }
2329
2330    let value = if is_be {
2331        read_u32_be(pan_file, selected_value_cursor)?
2332    } else {
2333        read_u32_le(pan_file, selected_value_cursor)?
2334    };
2335    *value_cursor = selected_value_cursor
2336        .checked_add(4)
2337        .context("Prelude cursor overflow after reading value")?;
2338    Ok(value)
2339}
2340
2341fn parse_prelude_kind_2_or_3_value(
2342    _pan_file: &[u8],
2343    _value_cursor: &mut usize,
2344    _is_be: bool,
2345) -> anyhow::Result<Option<u32>> {
2346    Ok(None)
2347}
2348
2349fn prelude_boundary_score(
2350    pan_file: &[u8],
2351    cursor: usize,
2352) -> anyhow::Result<u8> {
2353    if cursor >= pan_file.len() {
2354        return Ok(4);
2355    }
2356
2357    let Some(kind) = pan_file.get(cursor) else {
2358        return Ok(0);
2359    };
2360    if matches!(*kind, 0x00..=0x03) {
2361        let score = match kind {
2362            0x01 => 3,
2363            0x02 | 0x03 => 2,
2364            0x00 => 1,
2365            _ => 0,
2366        };
2367        return Ok(score);
2368    }
2369
2370    if section_header_looks_valid(pan_file, cursor)? {
2371        return Ok(2);
2372    }
2373
2374    Ok(0)
2375}
2376
2377fn parse_top_level_sections(
2378    pan_file: &[u8],
2379    first_section_offset: usize,
2380) -> anyhow::Result<(Vec<PanSection>, usize)> {
2381    let mut sections = Vec::new();
2382    let mut cursor = first_section_offset;
2383
2384    while cursor.saturating_add(6) <= pan_file.len() {
2385        if !section_header_looks_valid(pan_file, cursor)? {
2386            break;
2387        }
2388        let section = parse_section_at(pan_file, cursor)?;
2389        let declared_size = usize::try_from(section.declared_size)
2390            .context("Section size does not fit in usize")?;
2391        let next_cursor = cursor
2392            .checked_add(declared_size)
2393            .context("Section end overflow")?;
2394        sections.push(section);
2395        cursor = next_cursor;
2396    }
2397
2398    if sections.is_empty() {
2399        bail!("No top-level PAN sections found at expected offset")
2400    }
2401
2402    Ok((sections, cursor))
2403}
2404
2405fn collect_sections_recursively(
2406    pan_file: &[u8],
2407    root_sections: &[PanSection],
2408) -> anyhow::Result<Vec<PanSection>> {
2409    let mut all_sections = Vec::new();
2410    for section in root_sections {
2411        all_sections.push(section.clone());
2412        collect_nested_sections(pan_file, section, &mut all_sections)?;
2413    }
2414    Ok(all_sections)
2415}
2416
2417fn collect_nested_sections(
2418    pan_file: &[u8],
2419    parent: &PanSection,
2420    output: &mut Vec<PanSection>,
2421) -> anyhow::Result<()> {
2422    if !matches!(parent.name.as_str(), "SHEET" | "H") {
2423        return Ok(());
2424    }
2425
2426    let payload_start = parent
2427        .offset
2428        .checked_add(6)
2429        .and_then(|value| value.checked_add(parent.name_raw.len()))
2430        .context("Nested section payload start overflow")?;
2431    let payload_len = usize::try_from(parent.declared_size)
2432        .context("Nested section size does not fit in usize")?
2433        .checked_sub(6)
2434        .and_then(|value| value.checked_sub(parent.name_raw.len()))
2435        .context("Nested section payload length underflow")?;
2436    let payload_end = payload_start
2437        .checked_add(payload_len)
2438        .context("Nested section payload end overflow")?;
2439    if payload_start.saturating_add(6) > payload_end {
2440        return Ok(());
2441    }
2442
2443    let mut cursor = payload_start;
2444    while cursor.saturating_add(6) <= payload_end {
2445        if section_header_looks_valid_within_range(
2446            pan_file,
2447            cursor,
2448            payload_end,
2449        )? {
2450            let section =
2451                parse_section_at_within_range(pan_file, cursor, payload_end)?;
2452            let declared_size = usize::try_from(section.declared_size)
2453                .context("Nested section size does not fit in usize")?;
2454            let next_cursor = cursor
2455                .checked_add(declared_size)
2456                .context("Nested section end overflow")?;
2457
2458            output.push(section.clone());
2459            collect_nested_sections(pan_file, &section, output)?;
2460            cursor = next_cursor;
2461            continue;
2462        }
2463
2464        cursor = cursor
2465            .checked_add(1)
2466            .context("Nested section scan cursor overflow")?;
2467    }
2468
2469    Ok(())
2470}
2471
2472fn parse_section_at(
2473    pan_file: &[u8],
2474    offset: usize,
2475) -> anyhow::Result<PanSection> {
2476    parse_section_at_within_range(pan_file, offset, pan_file.len())
2477}
2478
2479fn parse_section_at_within_range(
2480    pan_file: &[u8],
2481    offset: usize,
2482    end_offset: usize,
2483) -> anyhow::Result<PanSection> {
2484    if offset.saturating_add(6) > pan_file.len() {
2485        bail!("Section header is truncated at offset {offset:#x}")
2486    }
2487
2488    let candidate_sizes = section_declared_size_candidates(pan_file, offset)?;
2489    let mut parse_error = None;
2490    for declared_size in candidate_sizes {
2491        let parsed = parse_section_at_with_size(
2492            pan_file,
2493            offset,
2494            end_offset,
2495            declared_size,
2496        );
2497        if let Ok(parsed) = parsed {
2498            return Ok(parsed);
2499        }
2500
2501        if parse_error.is_none() {
2502            parse_error = parsed.err().map(|error| error.to_string());
2503        }
2504    }
2505
2506    // Reason for fallback: section header parse failure falls back to default size encoding error description
2507    let reason = parse_error.unwrap_or_else(|| {
2508        "section header did not match a supported size encoding".to_string()
2509    });
2510    bail!("Section at offset {offset:#x} is invalid: {reason}")
2511}
2512
2513fn section_header_looks_valid(
2514    pan_file: &[u8],
2515    offset: usize,
2516) -> anyhow::Result<bool> {
2517    section_header_looks_valid_within_range(pan_file, offset, pan_file.len())
2518}
2519
2520fn section_header_looks_valid_within_range(
2521    pan_file: &[u8],
2522    offset: usize,
2523    end_offset: usize,
2524) -> anyhow::Result<bool> {
2525    if offset.saturating_add(6) > pan_file.len() {
2526        return Ok(false);
2527    }
2528
2529    let candidate_sizes = section_declared_size_candidates(pan_file, offset)?;
2530    for declared_size in candidate_sizes {
2531        if section_layout_looks_valid_for_size(
2532            pan_file,
2533            offset,
2534            end_offset,
2535            declared_size,
2536        ) {
2537            return Ok(true);
2538        }
2539    }
2540
2541    Ok(false)
2542}
2543
2544fn parse_section_at_with_size(
2545    pan_file: &[u8],
2546    offset: usize,
2547    end_offset: usize,
2548    declared_size: usize,
2549) -> anyhow::Result<PanSection> {
2550    if declared_size < 7 {
2551        bail!("Section at offset {offset:#x} is too small")
2552    }
2553
2554    let section_start =
2555        offset.checked_add(4).context("Section start overflow")?;
2556    let section_end = offset
2557        .checked_add(declared_size)
2558        .context("Section end overflow")?;
2559    if section_end > pan_file.len() || section_end > end_offset {
2560        bail!("Section at offset {offset:#x} extends beyond file end")
2561    }
2562
2563    let kind = *pan_file
2564        .get(section_start)
2565        .context("Section kind byte is missing")?;
2566    let name_len = usize::from(
2567        *pan_file
2568            .get(section_start.saturating_add(1))
2569            .context("Section name length byte is missing")?,
2570    );
2571    if name_len == 0 {
2572        bail!("Section name at offset {offset:#x} is empty")
2573    }
2574    let name_start = section_start
2575        .checked_add(2)
2576        .context("Section name start overflow")?;
2577    let name_end = name_start
2578        .checked_add(name_len)
2579        .context("Section name length overflow")?;
2580    if name_end > section_end {
2581        bail!(
2582            "Section name at offset {offset:#x} extends beyond section boundary"
2583        )
2584    }
2585
2586    if !is_section_kind_valid(kind) {
2587        bail!("Section kind {kind:#x} at offset {offset:#x} is invalid")
2588    }
2589
2590    let name_raw = pan_file
2591        .get(name_start..name_end)
2592        .context("Section name range is invalid")?
2593        .to_vec();
2594    let name = ctb_formats_encoding::decode(
2595        ctb_formats_encoding::CharEncoding::mac_roman(),
2596        &name_raw,
2597    )
2598    .with_context(|| {
2599        format!("Invalid MacRoman section name at offset {offset:#x}")
2600    })?;
2601
2602    let payload = pan_file
2603        .get(name_end..section_end)
2604        .context("Section payload range is invalid")?
2605        .to_vec();
2606
2607    Ok(PanSection {
2608        offset,
2609        declared_size: u32::try_from(declared_size)
2610            .context("Section size does not fit in u32")?,
2611        kind,
2612        name_raw,
2613        name,
2614        payload,
2615    })
2616}
2617
2618#[expect(clippy::similar_names, reason = "field names matching specification")]
2619fn section_declared_size_candidates(
2620    pan_file: &[u8],
2621    offset: usize,
2622) -> anyhow::Result<Vec<usize>> {
2623    let mut candidates = Vec::new();
2624    let is_be = detect_is_big_endian(pan_file);
2625
2626    let size_u32_little_endian = read_u32_le(pan_file, offset)?;
2627    let section_size_little_endian = usize::try_from(size_u32_little_endian)
2628        .context("Section LE size does not fit in usize")?;
2629
2630    let size_u32_big_endian = read_u32_be(pan_file, offset)?;
2631    let section_size_big_endian = usize::try_from(size_u32_big_endian)
2632        .context("Section BE size does not fit in usize")?;
2633
2634    if is_be {
2635        candidates.push(section_size_big_endian);
2636        if section_size_little_endian != section_size_big_endian {
2637            candidates.push(section_size_little_endian);
2638        }
2639    } else {
2640        candidates.push(section_size_little_endian);
2641        if section_size_big_endian != section_size_little_endian {
2642            candidates.push(section_size_big_endian);
2643        }
2644    }
2645
2646    Ok(candidates)
2647}
2648
2649fn section_layout_looks_valid_for_size(
2650    pan_file: &[u8],
2651    offset: usize,
2652    end_offset: usize,
2653    declared_size: usize,
2654) -> bool {
2655    if declared_size < 7 {
2656        return false;
2657    }
2658
2659    let Some(section_start) = offset.checked_add(4) else {
2660        return false;
2661    };
2662    let Some(section_end) = offset.checked_add(declared_size) else {
2663        return false;
2664    };
2665    if section_end > pan_file.len() || section_end > end_offset {
2666        return false;
2667    }
2668
2669    let Some(kind) = pan_file.get(section_start) else {
2670        return false;
2671    };
2672    if !is_section_kind_valid(*kind) {
2673        return false;
2674    }
2675
2676    let Some(name_len_byte) = pan_file.get(section_start.saturating_add(1))
2677    else {
2678        return false;
2679    };
2680    let name_len = usize::from(*name_len_byte);
2681    if name_len == 0 {
2682        return false;
2683    }
2684
2685    let Some(name_start) = section_start.checked_add(2) else {
2686        return false;
2687    };
2688    let Some(name_end) = name_start.checked_add(name_len) else {
2689        return false;
2690    };
2691    if name_end > section_end {
2692        return false;
2693    }
2694
2695    let Some(name_bytes) = pan_file.get(name_start..name_end) else {
2696        return false;
2697    };
2698    if name_bytes.is_empty() || name_bytes.contains(&0) {
2699        return false;
2700    }
2701    if ctb_formats_encoding::decode(
2702        ctb_formats_encoding::CharEncoding::mac_roman(),
2703        name_bytes,
2704    )
2705    .is_err()
2706    {
2707        return false;
2708    }
2709
2710    true
2711}
2712
2713fn is_section_kind_valid(kind: u8) -> bool {
2714    matches!(kind, 0x01..=0x06 | 0x80..=0x8f)
2715}
2716
2717fn extract_schemas_from_sections(
2718    sections: &[PanSection],
2719    is_be: bool,
2720) -> anyhow::Result<Vec<PanSchema>> {
2721    if sections.is_empty() {
2722        return Ok(Vec::new());
2723    }
2724
2725    let mut schemas = Vec::new();
2726    let mut seen_schema_offsets = std::collections::BTreeSet::new();
2727
2728    for preferred_kind in [Some(0x83u8), None] {
2729        for (index, section) in sections.iter().enumerate() {
2730            if let Some(kind) = preferred_kind {
2731                if section.kind != kind {
2732                    continue;
2733                }
2734            } else if section.kind == 0x83 {
2735                continue;
2736            }
2737
2738            if section.name != "NAMES" {
2739                continue;
2740            }
2741            if seen_schema_offsets.contains(&section.offset) {
2742                continue;
2743            }
2744
2745            let Some(schema) =
2746                build_schema_from_names_section(sections, index, is_be)?
2747            else {
2748                continue;
2749            };
2750
2751            seen_schema_offsets.insert(schema.names_section_offset);
2752            schemas.push(schema);
2753        }
2754    }
2755
2756    Ok(schemas)
2757}
2758
2759fn build_schema_from_names_section(
2760    sections: &[PanSection],
2761    index: usize,
2762    is_be: bool,
2763) -> anyhow::Result<Option<PanSchema>> {
2764    let Some(section) = sections.get(index) else {
2765        return Ok(None);
2766    };
2767    if section.name != "NAMES" {
2768        return Ok(None);
2769    }
2770
2771    let Some(next_index) = index.checked_add(1) else {
2772        return Ok(None);
2773    };
2774    let Some(remaining_sections) = sections.get(next_index..) else {
2775        return Ok(None);
2776    };
2777
2778    let Some(widths_section) = remaining_sections
2779        .iter()
2780        .find(|candidate| candidate.name == "WIDTHS")
2781    else {
2782        return Ok(None);
2783    };
2784
2785    let Some(types_section) = remaining_sections
2786        .iter()
2787        .find(|candidate| candidate.name == "TYPES")
2788    else {
2789        return Ok(None);
2790    };
2791
2792    let widths = parse_widths_payload(&widths_section.payload, is_be)?;
2793    if widths.is_empty() {
2794        return Ok(None);
2795    }
2796
2797    let type_codes = parse_types_payload(&types_section.payload, widths.len())?;
2798    let field_count = widths.len().min(type_codes.len());
2799    if field_count == 0 {
2800        return Ok(None);
2801    }
2802
2803    let names = parse_names_payload(&section.payload, field_count)?;
2804
2805    if names.len() != field_count {
2806        return Ok(None);
2807    }
2808
2809    let output_patterns = if let Some(using_section) =
2810        remaining_sections.iter().find(|candidate| {
2811            candidate.name == "USING" || candidate.name == "PATTERNS"
2812        }) {
2813        parse_string_array_payload(&using_section.payload, field_count)?
2814    } else {
2815        vec![None; field_count]
2816    };
2817
2818    let formulas = if let Some(eq_section) = remaining_sections
2819        .iter()
2820        .find(|candidate| candidate.name == "EQUATIONS")
2821    {
2822        parse_string_array_payload(&eq_section.payload, field_count)?
2823    } else {
2824        vec![None; field_count]
2825    };
2826
2827    let default_values = if let Some(def_section) = remaining_sections
2828        .iter()
2829        .find(|candidate| candidate.name == "DEFAULTS")
2830    {
2831        parse_string_array_payload(&def_section.payload, field_count)?
2832    } else {
2833        vec![None; field_count]
2834    };
2835
2836    let prompts = if let Some(prompt_section) = remaining_sections
2837        .iter()
2838        .find(|candidate| candidate.name == "PROMPTS")
2839    {
2840        parse_string_array_payload(&prompt_section.payload, field_count)?
2841    } else {
2842        vec![None; field_count]
2843    };
2844
2845    let links = if let Some(link_section) = remaining_sections
2846        .iter()
2847        .find(|candidate| candidate.name == "LINKS")
2848    {
2849        parse_string_array_payload(&link_section.payload, field_count)?
2850    } else {
2851        vec![None; field_count]
2852    };
2853
2854    let ranges = if let Some(range_section) = remaining_sections
2855        .iter()
2856        .find(|candidate| candidate.name == "RANGE")
2857    {
2858        parse_string_array_payload(&range_section.payload, field_count)?
2859    } else {
2860        vec![None; field_count]
2861    };
2862
2863    let justifications = if let Some(just_section) = remaining_sections
2864        .iter()
2865        .find(|candidate| candidate.name == "JUSTIFICATION")
2866    {
2867        parse_bytes_payload(&just_section.payload, field_count)?
2868            .into_iter()
2869            .map(|b| match b {
2870                1 => PanJustification::Right,
2871                2 => PanJustification::Center,
2872                _ => PanJustification::Left,
2873            })
2874            .collect::<Vec<_>>()
2875    } else {
2876        vec![PanJustification::Left; field_count]
2877    };
2878
2879    let digits_list = if let Some(digits_section) = remaining_sections
2880        .iter()
2881        .find(|candidate| candidate.name == "DIGITS")
2882    {
2883        parse_bytes_payload(&digits_section.payload, field_count)?
2884    } else {
2885        vec![0u8; field_count]
2886    };
2887
2888    let clairvoyance_list = if let Some(clair_section) = remaining_sections
2889        .iter()
2890        .find(|candidate| candidate.name == "CLAIRVOYANCE")
2891    {
2892        parse_bytes_payload(&clair_section.payload, field_count)?
2893            .into_iter()
2894            .map(|b| b != 0)
2895            .collect::<Vec<_>>()
2896    } else {
2897        vec![false; field_count]
2898    };
2899
2900    let capitalization_list = if let Some(case_section) = remaining_sections
2901        .iter()
2902        .find(|candidate| candidate.name == "UPPER CASE")
2903    {
2904        parse_bytes_payload(&case_section.payload, field_count)?
2905            .into_iter()
2906            .map(|b| match b {
2907                1 => PanCapitalization::AllUpper,
2908                2 => PanCapitalization::InitialCaps,
2909                _ => PanCapitalization::None,
2910            })
2911            .collect::<Vec<_>>()
2912    } else {
2913        vec![PanCapitalization::None; field_count]
2914    };
2915
2916    let fields = names
2917        .into_iter()
2918        .zip(widths.into_iter().take(field_count))
2919        .zip(type_codes.into_iter().take(field_count))
2920        .enumerate()
2921        .map(|(field_index, ((name, width), type_code))| PanSchemaField {
2922            index: field_index,
2923            name,
2924            width,
2925            type_code,
2926            type_label: type_code_label(type_code).to_string(),
2927            field_type: map_type_code(type_code),
2928            output_pattern: output_patterns.get(field_index).cloned().flatten(),
2929            formula: formulas.get(field_index).cloned().flatten(),
2930            default_value: default_values.get(field_index).cloned().flatten(),
2931            prompt: prompts.get(field_index).cloned().flatten(),
2932            link: links.get(field_index).cloned().flatten(),
2933            range: ranges.get(field_index).cloned().flatten(),
2934            digits: match digits_list.get(field_index) {
2935                Some(d) => *d,
2936                None => 0,
2937            },
2938            justification: match justifications.get(field_index) {
2939                Some(j) => *j,
2940                None => PanJustification::Left,
2941            },
2942            clairvoyance: match clairvoyance_list.get(field_index) {
2943                Some(c) => *c,
2944                None => false,
2945            },
2946            capitalization: match capitalization_list.get(field_index) {
2947                Some(c) => *c,
2948                None => PanCapitalization::None,
2949            },
2950        })
2951        .collect::<Vec<_>>();
2952
2953    Ok(Some(PanSchema {
2954        names_section_offset: section.offset,
2955        widths_section_offset: widths_section.offset,
2956        types_section_offset: types_section.offset,
2957        fields,
2958    }))
2959}
2960
2961fn parse_names_payload(
2962    payload: &[u8],
2963    expected_count: usize,
2964) -> anyhow::Result<Vec<String>> {
2965    if expected_count == 0 {
2966        return Ok(Vec::new());
2967    }
2968
2969    let names_bytes = if payload.len() >= 7
2970        && payload.get(0..2) == Some(&[0x00, 0xfe][..])
2971    {
2972        let len_hi = *payload
2973            .get(2)
2974            .context("NAMES BE16 length high byte missing")?;
2975        let len_lo = *payload
2976            .get(3)
2977            .context("NAMES BE16 length low byte missing")?;
2978        let declared_bytes = usize::from(u16::from_be_bytes([len_hi, len_lo]));
2979        if declared_bytes < 7 {
2980            bail!("NAMES BE16 framed byte count is smaller than header size")
2981        }
2982        let names_data_len = declared_bytes
2983            .checked_sub(7)
2984            .context("NAMES framed byte count underflow")?;
2985        let names_data_end = 7usize
2986            .checked_add(names_data_len)
2987            .context("NAMES framed byte count overflow")?;
2988        payload
2989            .get(7..names_data_end)
2990            .context("Invalid NAMES framed payload range")?
2991    } else if payload.len() >= 6
2992        && payload.get(0..2) == Some(&[0x53, 0x00][..])
2993    {
2994        let declared_bytes = usize::try_from(read_u32_le(payload, 2)?)
2995            .context("NAMES byte count does not fit in usize")?;
2996
2997        if declared_bytes < 6 {
2998            bail!("NAMES framed byte count is smaller than header size")
2999        }
3000
3001        let names_data_len = declared_bytes
3002            .checked_sub(6)
3003            .context("NAMES framed byte count underflow")?;
3004        let names_data_end = 6usize
3005            .checked_add(names_data_len)
3006            .context("NAMES framed byte count overflow")?;
3007
3008        payload
3009            .get(6..names_data_end)
3010            .context("Invalid NAMES framed payload range")?
3011    } else if payload.len() >= 5 && payload.first() == Some(&0) {
3012        let declared_bytes = usize::try_from(read_u32_le(payload, 1)?)
3013            .context("NAMES byte count does not fit in usize")?;
3014
3015        if declared_bytes < 5 {
3016            bail!("NAMES framed byte count is smaller than header size")
3017        }
3018
3019        let names_data_len = declared_bytes
3020            .checked_sub(5)
3021            .context("NAMES framed byte count underflow")?;
3022        let names_data_end = 5usize
3023            .checked_add(names_data_len)
3024            .context("NAMES framed byte count overflow")?;
3025
3026        payload
3027            .get(5..names_data_end)
3028            .context("Invalid NAMES framed payload range")?
3029    } else {
3030        payload
3031    };
3032
3033    let mut names = Vec::with_capacity(expected_count);
3034    let mut cursor = 0usize;
3035    for _ in 0..expected_count {
3036        let record_len = usize::from(
3037            *names_bytes
3038                .get(cursor)
3039                .context("NAMES entry length is missing")?,
3040        );
3041        if record_len <= 1 {
3042            bail!(
3043                "NAMES entry length is zero before expected field count is reached"
3044            )
3045        }
3046
3047        cursor = cursor
3048            .checked_add(1)
3049            .context("NAMES cursor overflow after length")?;
3050
3051        let name_len = record_len
3052            .checked_sub(1)
3053            .context("NAMES entry length underflow")?;
3054        let name_end = cursor
3055            .checked_add(name_len)
3056            .context("NAMES entry length overflow")?;
3057        let name_raw = names_bytes
3058            .get(cursor..name_end)
3059            .context("NAMES entry extends beyond payload")?;
3060        let name = ctb_formats_encoding::decode(
3061            ctb_formats_encoding::CharEncoding::mac_roman(),
3062            name_raw,
3063        )
3064        .context("Invalid MacRoman string in NAMES payload")?;
3065        names.push(name);
3066        cursor = name_end;
3067    }
3068
3069    Ok(names)
3070}
3071
3072fn parse_widths_payload(
3073    payload: &[u8],
3074    is_be: bool,
3075) -> anyhow::Result<Vec<u16>> {
3076    let width_bytes = if payload.get(0..2) == Some(b"HS".as_slice()) {
3077        payload.get(2..).context("Invalid WIDTHS payload range")?
3078    } else if (payload.len() & 1) == 1 && payload.first() == Some(&0) {
3079        payload.get(1..).context("Invalid WIDTHS payload range")?
3080    } else {
3081        payload
3082    };
3083
3084    if (width_bytes.len() & 1) != 0 {
3085        bail!("WIDTHS payload length is not an even number of bytes")
3086    }
3087
3088    let mut widths = Vec::with_capacity(width_bytes.len() >> 1);
3089    let mut cursor = 0usize;
3090    while cursor.saturating_add(2) <= width_bytes.len() {
3091        let b0 = *width_bytes.get(cursor).context("WIDTHS byte 0 missing")?;
3092        let b1 = *width_bytes
3093            .get(cursor.saturating_add(1))
3094            .context("WIDTHS byte 1 missing")?;
3095        let width = if is_be {
3096            u16::from_be_bytes([b0, b1])
3097        } else {
3098            u16::from_le_bytes([b0, b1])
3099        };
3100        widths.push(width);
3101        cursor = cursor.saturating_add(2);
3102    }
3103
3104    Ok(widths)
3105}
3106
3107fn parse_types_payload(
3108    payload: &[u8],
3109    expected_count: usize,
3110) -> anyhow::Result<Vec<u8>> {
3111    let payload = if payload.get(0..2) == Some(&[0x53, 0x00][..]) {
3112        payload.get(2..).context("Invalid TYPES payload range")?
3113    } else {
3114        payload
3115    };
3116
3117    let payload =
3118        if payload.len() > expected_count && payload.first() == Some(&0) {
3119            payload.get(1..).context("Invalid TYPES payload range")?
3120        } else {
3121            payload
3122        };
3123
3124    if payload.len() < expected_count {
3125        bail!("TYPES payload has fewer values than NAMES")
3126    }
3127
3128    Ok(payload
3129        .get(..expected_count)
3130        .context("Invalid TYPES payload range")?
3131        .to_vec())
3132}
3133
3134fn parse_string_array_payload(
3135    payload: &[u8],
3136    expected_count: usize,
3137) -> anyhow::Result<Vec<Option<String>>> {
3138    if expected_count == 0 || payload.is_empty() {
3139        return Ok(vec![None; expected_count]);
3140    }
3141
3142    let array_bytes = if payload.len() >= 7
3143        && payload.get(0..2) == Some(&[0x00, 0xfe][..])
3144    {
3145        let len_hi = *payload
3146            .get(2)
3147            .context("String array BE16 length high byte missing")?;
3148        let len_lo = *payload
3149            .get(3)
3150            .context("String array BE16 length low byte missing")?;
3151        let declared_bytes = usize::from(u16::from_be_bytes([len_hi, len_lo]));
3152        let end = declared_bytes.min(payload.len());
3153        match payload.get(7..end) {
3154            Some(slice) => slice,
3155            None => &[],
3156        }
3157    } else if payload.len() >= 6
3158        && payload.get(0..2) == Some(&[0x47, 0x00][..])
3159    {
3160        let declared_bytes = usize::try_from(read_u32_le(payload, 2)?)
3161            .context("String array byte count does not fit in usize")?;
3162        let end = declared_bytes.min(payload.len());
3163        match payload.get(6..end) {
3164            Some(slice) => slice,
3165            None => &[],
3166        }
3167    } else if payload.len() >= 5 && payload.first() == Some(&0) {
3168        let declared_bytes = usize::try_from(read_u32_le(payload, 1)?)
3169            .context("String array byte count does not fit in usize")?;
3170        let end = declared_bytes.min(payload.len());
3171        match payload.get(5..end) {
3172            Some(slice) => slice,
3173            None => &[],
3174        }
3175    } else if payload.len() >= 4
3176        && payload.get(1..4) == Some(&[0x00, 0x00, 0x00][..])
3177    {
3178        let first_byte = match payload.first() {
3179            Some(&b) => b,
3180            None => 0,
3181        };
3182        let declared_bytes = usize::from(first_byte);
3183        let end = declared_bytes.min(payload.len());
3184        match payload.get(4..end) {
3185            Some(slice) => slice,
3186            None => &[],
3187        }
3188    } else {
3189        payload
3190    };
3191
3192    let mut items = Vec::with_capacity(expected_count);
3193    let mut cursor = 0usize;
3194    for _ in 0..expected_count {
3195        let Some(&len_b) = array_bytes.get(cursor) else {
3196            items.push(None);
3197            continue;
3198        };
3199
3200        let (header_len, item_len) = if len_b == 0x7e {
3201            let hi = match array_bytes.get(cursor.saturating_add(1)) {
3202                Some(&b) => b,
3203                None => 0,
3204            };
3205            let lo = match array_bytes.get(cursor.saturating_add(2)) {
3206                Some(&b) => b,
3207                None => 0,
3208            };
3209            let total = usize::from(u16::from_be_bytes([hi, lo]));
3210            (3usize, total.saturating_sub(3))
3211        } else if len_b == 0x7f {
3212            let b1 = match array_bytes.get(cursor.saturating_add(1)) {
3213                Some(&b) => b,
3214                None => 0,
3215            };
3216            let b2 = match array_bytes.get(cursor.saturating_add(2)) {
3217                Some(&b) => b,
3218                None => 0,
3219            };
3220            let b3 = match array_bytes.get(cursor.saturating_add(3)) {
3221                Some(&b) => b,
3222                None => 0,
3223            };
3224            let total = (usize::from(b1) << 16)
3225                | (usize::from(b2) << 8)
3226                | usize::from(b3);
3227            (4usize, total.saturating_sub(4))
3228        } else {
3229            let total = usize::from(len_b);
3230            (1usize, total.saturating_sub(1))
3231        };
3232
3233        cursor = cursor.saturating_add(header_len);
3234        let end = cursor.saturating_add(item_len).min(array_bytes.len());
3235        let raw = match array_bytes.get(cursor..end) {
3236            Some(slice) => slice,
3237            None => &[],
3238        };
3239        cursor = end;
3240
3241        if raw.is_empty() {
3242            items.push(None);
3243        } else {
3244            let s = ctb_formats_encoding::decode(
3245                ctb_formats_encoding::CharEncoding::mac_roman(),
3246                raw,
3247            )
3248            .context("Invalid MacRoman string in string array payload")?;
3249            items.push(Some(s));
3250        }
3251    }
3252
3253    Ok(items)
3254}
3255
3256fn parse_using_payload(
3257    payload: &[u8],
3258    expected_count: usize,
3259) -> anyhow::Result<Vec<Option<String>>> {
3260    parse_string_array_payload(payload, expected_count)
3261}
3262
3263fn parse_bytes_payload(
3264    payload: &[u8],
3265    expected_count: usize,
3266) -> anyhow::Result<Vec<u8>> {
3267    let payload =
3268        if payload.len() > expected_count && payload.first() == Some(&0) {
3269            payload.get(1..).context("Invalid bytes payload range")?
3270        } else {
3271            payload
3272        };
3273
3274    let mut result = Vec::with_capacity(expected_count);
3275    for i in 0..expected_count {
3276        let byte = match payload.get(i) {
3277            Some(&b) => b,
3278            None => 0,
3279        };
3280        result.push(byte);
3281    }
3282    Ok(result)
3283}
3284
3285fn parse_launch_payload(payload: &[u8]) -> Option<String> {
3286    if payload.len() < 2 {
3287        return None;
3288    }
3289    let last_len = usize::from(*payload.last()?);
3290    if last_len > 0 && last_len < payload.len() {
3291        let start = payload.len().saturating_sub(last_len);
3292        let name_bytes = payload.get(start..)?;
3293        if name_bytes
3294            .iter()
3295            .all(|&b| b.is_ascii_graphic() || b == b' ')
3296        {
3297            return String::from_utf8(name_bytes.to_vec()).ok();
3298        }
3299    }
3300    if payload.len() >= 8 {
3301        for offset in (20..payload.len().saturating_sub(2)).rev() {
3302            let slen = usize::from(*payload.get(offset)?);
3303            if (3..=32).contains(&slen)
3304                && offset.saturating_add(1).saturating_add(slen)
3305                    <= payload.len()
3306            {
3307                let start = offset.saturating_add(1);
3308                let end = start.saturating_add(slen);
3309                let name_bytes = payload.get(start..end)?;
3310                if name_bytes
3311                    .iter()
3312                    .all(|&b| b.is_ascii_graphic() || b == b' ')
3313                {
3314                    return String::from_utf8(name_bytes.to_vec()).ok();
3315                }
3316            }
3317        }
3318    }
3319    None
3320}
3321
3322fn parse_rc_payload(payload: &[u8], is_be: bool) -> Option<usize> {
3323    if payload.len() < 4 {
3324        return None;
3325    }
3326    let b0 = *payload.first()?;
3327    let b1 = *payload.get(1)?;
3328    let b2 = *payload.get(2)?;
3329    let b3 = *payload.get(3)?;
3330    let raw_u32 = if is_be {
3331        u32::from_be_bytes([b0, b1, b2, b3])
3332    } else {
3333        u32::from_le_bytes([b0, b1, b2, b3])
3334    };
3335    let val = usize::try_from(raw_u32).ok()?;
3336    if val > 0 { Some(val) } else { None }
3337}
3338
3339fn decode_macro_procedure_bytes(chunk: &[u8]) -> Option<String> {
3340    if chunk.is_empty() {
3341        return None;
3342    }
3343    let is_valid = chunk.iter().all(|&b| {
3344        (0x20..=0x7E).contains(&b)
3345            || b == b'\r'
3346            || b == b'\n'
3347            || b == b'\t'
3348            || b >= 0x80
3349    });
3350    if !is_valid {
3351        return None;
3352    }
3353
3354    let decoded = ctb_formats_encoding::decode(
3355        ctb_formats_encoding::CharEncoding::mac_roman(),
3356        chunk,
3357    )
3358    .ok()?;
3359
3360    let mut result = String::new();
3361    for line in decoded.split('\r') {
3362        let trimmed = line.trim_end();
3363        result.push_str(trimmed);
3364        result.push('\n');
3365    }
3366    Some(result)
3367}
3368
3369pub fn extract_macro_code_bytes(
3370    macro_bytes: &[u8],
3371    name_len: usize,
3372) -> Option<&[u8]> {
3373    let body = macro_bytes.get(6usize.saturating_add(name_len)..)?;
3374    if body.len() < 3 {
3375        return None;
3376    }
3377
3378    // 1. Structural parse: 2-byte BE or LE length prefix at pos - 2
3379    for pos in (2..body.len()).rev() {
3380        if let (Some(&b0), Some(&b1)) = (
3381            body.get(pos.saturating_sub(2)),
3382            body.get(pos.saturating_sub(1)),
3383        ) {
3384            let l_be = usize::from(u16::from_be_bytes([b0, b1]));
3385            let l_le = usize::from(u16::from_le_bytes([b0, b1]));
3386
3387            for len in [l_be, l_le] {
3388                if len > 0
3389                    && pos.saturating_add(len) <= body.len()
3390                    && (pos.saturating_add(len) == body.len()
3391                        || pos.saturating_add(len)
3392                            == body.len().saturating_sub(1))
3393                {
3394                    if let Some(chunk) = body.get(pos..pos.saturating_add(len))
3395                    {
3396                        let is_valid = chunk.iter().all(|&b| {
3397                            (0x20..=0x7E).contains(&b)
3398                                || b == b'\r'
3399                                || b == b'\n'
3400                                || b == b'\t'
3401                                || b >= 0x80
3402                        });
3403                        if is_valid {
3404                            return Some(chunk);
3405                        }
3406                    }
3407                }
3408            }
3409        }
3410    }
3411
3412    // 2. Fallback: 4-byte BE or LE length prefix at pos - 4
3413    for pos in (4..body.len()).rev() {
3414        if let (Some(&b0), Some(&b1), Some(&b2), Some(&b3)) = (
3415            body.get(pos.saturating_sub(4)),
3416            body.get(pos.saturating_sub(3)),
3417            body.get(pos.saturating_sub(2)),
3418            body.get(pos.saturating_sub(1)),
3419        ) {
3420            let l_be =
3421                match usize::try_from(u32::from_be_bytes([b0, b1, b2, b3])) {
3422                    Ok(l) => l,
3423                    Err(_) => 0,
3424                };
3425            let l_le =
3426                match usize::try_from(u32::from_le_bytes([b0, b1, b2, b3])) {
3427                    Ok(l) => l,
3428                    Err(_) => 0,
3429                };
3430
3431            for len in [l_be, l_le] {
3432                if len > 0
3433                    && pos.saturating_add(len) <= body.len()
3434                    && (pos.saturating_add(len) == body.len()
3435                        || pos.saturating_add(len)
3436                            == body.len().saturating_sub(1))
3437                {
3438                    if let Some(chunk) = body.get(pos..pos.saturating_add(len))
3439                    {
3440                        let is_valid = chunk.iter().all(|&b| {
3441                            (0x20..=0x7E).contains(&b)
3442                                || b == b'\r'
3443                                || b == b'\n'
3444                                || b == b'\t'
3445                                || b >= 0x80
3446                        });
3447                        if is_valid {
3448                            return Some(chunk);
3449                        }
3450                    }
3451                }
3452            }
3453        }
3454    }
3455
3456    None
3457}
3458
3459fn extract_macro_code(macro_bytes: &[u8], name_len: usize) -> Option<String> {
3460    let chunk = extract_macro_code_bytes(macro_bytes, name_len)?;
3461    decode_macro_procedure_bytes(chunk)
3462}
3463
3464/// Deobfuscate a Panorama macro from a read-only ("locked") database using a
3465/// position-dependent XOR stream cipher.
3466///
3467/// In locked Panorama databases, the macro body (from the compiled bytecode
3468/// header through the trailing source code) is obfuscated with a linear XOR
3469/// stream cipher. In big-endian files, the bytecode header
3470/// `[0xFF, 0xEC, 0x00, 0x00, 0x00, 0x00]` appears as
3471/// `[0xF9, 0xE5, 0x0C, 0x0F, 0x12, 0x15]`, and in little-endian files
3472/// `[0xEC, 0xFF, 0x00, 0x00, 0x00, 0x00]` appears as
3473/// `[0xEA, 0xF6, 0x0C, 0x0F, 0x12, 0x15]`.
3474/// The stream cipher parameters are derived directly from the header differences:
3475/// `k0 = w[0] ^ expected_0`, `k1 = w[1] ^ expected_1`, `step = k1 - k0`, and
3476/// `start = k0 / step`, giving key `((k + start) * step) & 0xFF`.
3477fn deobfuscate_macro_payload(macro_bytes: &[u8], name_len: usize) -> Vec<u8> {
3478    let header_len = 6usize.saturating_add(name_len);
3479    let Some(body) = macro_bytes.get(header_len..) else {
3480        return macro_bytes.to_vec();
3481    };
3482
3483    const BE_LOCKED_MAGIC: [u8; 6] = [0xf9, 0xe5, 0x0c, 0x0f, 0x12, 0x15];
3484    const LE_LOCKED_MAGIC: [u8; 6] = [0xea, 0xf6, 0x0c, 0x0f, 0x12, 0x15];
3485
3486    let magic_info = body.windows(6).enumerate().find_map(|(pos, w)| {
3487        if w == BE_LOCKED_MAGIC {
3488            Some((pos, true))
3489        } else if w == LE_LOCKED_MAGIC {
3490            Some((pos, false))
3491        } else {
3492            None
3493        }
3494    });
3495
3496    let Some((pos, is_be)) = magic_info else {
3497        return macro_bytes.to_vec();
3498    };
3499
3500    let body_split = header_len.saturating_add(pos);
3501    let Some(prefix) = macro_bytes.get(..body_split) else {
3502        return macro_bytes.to_vec();
3503    };
3504    let Some(ciphertext) = macro_bytes.get(body_split..) else {
3505        return macro_bytes.to_vec();
3506    };
3507
3508    let expected_0 = if is_be { 0xff } else { 0xec };
3509    let expected_1 = if is_be { 0xec } else { 0xff };
3510    let Some(&b0) = ciphertext.first() else {
3511        return macro_bytes.to_vec();
3512    };
3513    let Some(&b1) = ciphertext.get(1) else {
3514        return macro_bytes.to_vec();
3515    };
3516    let k0 = b0 ^ expected_0;
3517    let k1 = b1 ^ expected_1;
3518    let step = k1.wrapping_sub(k0);
3519    // Reason for fallback: default starting key offset is 2 for standard macro magic
3520    let start = k0.checked_div(step).unwrap_or(2);
3521
3522    let mut result = Vec::with_capacity(macro_bytes.len());
3523    result.extend_from_slice(prefix);
3524
3525    for (idx, &b) in ciphertext.iter().enumerate() {
3526        // Reason for fallback: idx & 0xff is strictly <= 255 and fits in u8
3527        let idx_u8 = u8::try_from(idx & 0xff).unwrap_or(0);
3528        let key = idx_u8.wrapping_add(start).wrapping_mul(step);
3529        result.push(b ^ key);
3530    }
3531
3532    result
3533}
3534
3535impl PanMacroInfo {
3536    /// Returns the raw byte slice of the procedure source code from the macro payload.
3537    pub fn raw_code_bytes(&self) -> Option<&[u8]> {
3538        let name_len = usize::from(*self.payload.get(5)?);
3539        extract_macro_code_bytes(&self.payload, name_len)
3540    }
3541}
3542
3543fn parse_macros_payload(payload: &[u8]) -> Vec<PanMacroInfo> {
3544    let mut macros = Vec::new();
3545    let mut cursor = 0usize;
3546    while cursor.saturating_add(6) < payload.len() {
3547        let b0 = match payload.get(cursor) {
3548            Some(&b) => b,
3549            None => 0,
3550        };
3551        let b1 = match payload.get(cursor.saturating_add(1)) {
3552            Some(&b) => b,
3553            None => 0,
3554        };
3555        let b2 = match payload.get(cursor.saturating_add(2)) {
3556            Some(&b) => b,
3557            None => 0,
3558        };
3559        let b3 = match payload.get(cursor.saturating_add(3)) {
3560            Some(&b) => b,
3561            None => 0,
3562        };
3563        let s_be = match usize::try_from(u32::from_be_bytes([b0, b1, b2, b3])) {
3564            Ok(s) => s,
3565            Err(_) => 0,
3566        };
3567        let s_le = match usize::try_from(u32::from_le_bytes([b0, b1, b2, b3])) {
3568            Ok(s) => s,
3569            Err(_) => 0,
3570        };
3571
3572        let b4 = match payload.get(cursor.saturating_add(4)) {
3573            Some(&b) => b,
3574            None => 0,
3575        };
3576        if cursor.saturating_add(5) < payload.len() && b4 == 0x84 {
3577            let nlen = match payload.get(cursor.saturating_add(5)) {
3578                Some(&b) => usize::from(b),
3579                None => 0,
3580            };
3581            if cursor.saturating_add(6).saturating_add(nlen) <= payload.len() {
3582                let name_start = cursor.saturating_add(6);
3583                let name_end = name_start.saturating_add(nlen);
3584                let raw_name = match payload.get(name_start..name_end) {
3585                    Some(slice) => slice,
3586                    None => &[],
3587                };
3588                let name = match ctb_formats_encoding::decode(
3589                    ctb_formats_encoding::CharEncoding::mac_roman(),
3590                    raw_name,
3591                ) {
3592                    Ok(decoded) => decoded,
3593                    Err(_) => String::from_utf8_lossy(raw_name).into_owned(),
3594                };
3595
3596                let chosen_size = if cursor.saturating_add(s_le)
3597                    <= payload.len()
3598                    && s_le >= 6usize.saturating_add(nlen)
3599                {
3600                    s_le
3601                } else if cursor.saturating_add(s_be) <= payload.len()
3602                    && s_be >= 6usize.saturating_add(nlen)
3603                {
3604                    s_be
3605                } else {
3606                    0
3607                };
3608
3609                if chosen_size > 0 {
3610                    let raw_macro = match payload
3611                        .get(cursor..cursor.saturating_add(chosen_size))
3612                    {
3613                        Some(slice) => slice,
3614                        None => &[],
3615                    };
3616                    let deobfuscated_macro =
3617                        deobfuscate_macro_payload(raw_macro, nlen);
3618                    let code = extract_macro_code(&deobfuscated_macro, nlen);
3619                    let ast = code.as_deref().and_then(|c| {
3620                        crate::procedure_parser::parse_procedure(c).ok()
3621                    });
3622                    let is_procedure = name.starts_with('.');
3623
3624                    macros.push(PanMacroInfo {
3625                        name,
3626                        size: chosen_size,
3627                        is_procedure,
3628                        code,
3629                        ast,
3630                        payload: deobfuscated_macro,
3631                    });
3632                    cursor = cursor.saturating_add(chosen_size);
3633                    continue;
3634                }
3635            }
3636        }
3637        cursor = cursor.saturating_add(1);
3638    }
3639    macros
3640}
3641
3642fn map_type_code(type_code: u8) -> PanFieldType {
3643    match type_code {
3644        0 => PanFieldType::Text,
3645        1 => PanFieldType::Picture,
3646        2 => PanFieldType::Choices,
3647        4 => PanFieldType::Date,
3648        5 => PanFieldType::Float,
3649        6 => PanFieldType::Integer,
3650        7 => PanFieldType::Fixed1,
3651        8 => PanFieldType::Fixed2,
3652        9 => PanFieldType::Fixed3,
3653        10 => PanFieldType::Fixed4,
3654        value => PanFieldType::Unknown(value),
3655    }
3656}
3657
3658fn type_code_label(type_code: u8) -> &'static str {
3659    match type_code {
3660        0 => "Text",
3661        1 => "Picture",
3662        2 => "Choices",
3663        4 => "Date",
3664        5 => "Float",
3665        6 => "Integer",
3666        7 => "Fixed(1)",
3667        8 => "Fixed(2)",
3668        9 => "Fixed(3)",
3669        10 => "Fixed(4)",
3670        _ => "Unknown",
3671    }
3672}
3673
3674fn read_u32_le(bytes: &[u8], offset: usize) -> anyhow::Result<u32> {
3675    let end = offset.checked_add(4).context("u32 read offset overflow")?;
3676    let raw = bytes.get(offset..end).with_context(|| {
3677        format!("Could not read u32 at offset {offset:#x}: out of range")
3678    })?;
3679    let four: [u8; 4] = <[u8; 4]>::try_from(raw)
3680        .context("u32 conversion failed for 4-byte slice")?;
3681    Ok(u32::from_le_bytes(four))
3682}
3683
3684fn read_u32_be(bytes: &[u8], offset: usize) -> anyhow::Result<u32> {
3685    let end = offset.checked_add(4).context("u32 read offset overflow")?;
3686    let raw = bytes.get(offset..end).with_context(|| {
3687        format!("Could not read u32 at offset {offset:#x}: out of range")
3688    })?;
3689    let four: [u8; 4] = <[u8; 4]>::try_from(raw)
3690        .context("u32 conversion failed for 4-byte slice")?;
3691    Ok(u32::from_be_bytes(four))
3692}
3693
3694#[cfg(test)]
3695#[allow(
3696    clippy::panic,
3697    clippy::expect_used,
3698    clippy::unwrap_used,
3699    clippy::unwrap_in_result,
3700    clippy::panic_in_result_fn,
3701    clippy::indexing_slicing,
3702    clippy::arithmetic_side_effects,
3703    reason = "Standard repository test boilerplate"
3704)]
3705mod tests {
3706    use ctb_utilities::anyhow::ensure;
3707
3708    use super::*;
3709
3710    #[crate::ctb_test]
3711    fn test_parse_prelude_entries_handles_single_byte_pre_value_marker()
3712    -> anyhow::Result<()> {
3713        let mut pan_file = Vec::new();
3714        pan_file.extend_from_slice(&0u32.to_le_bytes());
3715
3716        pan_file.push(0x00);
3717        pan_file.push(3);
3718        pan_file.extend_from_slice(b"ABC");
3719        pan_file.push(b'e');
3720        pan_file.extend_from_slice(&12u32.to_le_bytes());
3721
3722        pan_file.push(0x01);
3723        pan_file.push(1);
3724        pan_file.extend_from_slice(b"D");
3725        pan_file.push(0);
3726        pan_file.extend_from_slice(&24u32.to_le_bytes());
3727
3728        pan_file.push(0x02);
3729        pan_file.push(1);
3730        pan_file.extend_from_slice(b"H");
3731        pan_file.push(0);
3732
3733        let section_start = pan_file.len();
3734        pan_file.extend_from_slice(&18u32.to_le_bytes());
3735        pan_file.push(0x83);
3736        pan_file.push(7);
3737        pan_file.extend_from_slice(b"VERSION");
3738        pan_file.extend_from_slice(&[0, 0, 0, 0, 0]);
3739
3740        let (entries, first_section_offset) =
3741            parse_prelude_entries(&pan_file, false)?;
3742
3743        ensure!(entries.len() == 3);
3744        ensure!(entries.first().is_some_and(|entry| entry.name == "ABC"));
3745        ensure!(
3746            entries
3747                .first()
3748                .is_some_and(|entry| entry.value_u32_le == Some(12))
3749        );
3750        ensure!(entries.get(1).is_some_and(|entry| entry.name == "D"));
3751        ensure!(
3752            entries
3753                .get(1)
3754                .is_some_and(|entry| entry.value_u32_le == Some(24))
3755        );
3756        ensure!(entries.get(2).is_some_and(|entry| entry.name == "H"));
3757        ensure!(
3758            entries
3759                .get(2)
3760                .is_some_and(|entry| entry.value_u32_le.is_none())
3761        );
3762        ensure!(first_section_offset == section_start);
3763        ensure!(section_header_looks_valid(&pan_file, first_section_offset)?);
3764
3765        Ok(())
3766    }
3767
3768    #[crate::ctb_test]
3769    #[expect(
3770        clippy::manual_assert,
3771        clippy::panic_in_result_fn,
3772        reason = "Standard repository test boilerplate"
3773    )]
3774    fn test_parse_pan_parses_sample_fixture_structure() -> anyhow::Result<()> {
3775        let pan_file = crate::get_pan_data("fixtures/SAMPLE.pan")
3776            .context("Could not load fixtures/SAMPLE.pan")?;
3777
3778        let parsed = parse_pan(&pan_file)?;
3779
3780        ensure!(parsed.prelude.first_u32_le == 0x10e4);
3781        ensure!(
3782            parsed
3783                .prelude
3784                .entries
3785                .iter()
3786                .map(|entry| entry.name.as_str())
3787                .collect::<Vec<_>>()
3788                == vec!["SAMPLE", "DESIGN", "SHEET", "H"]
3789        );
3790
3791        ensure!(!parsed.sections.is_empty());
3792        let first_section = parsed
3793            .sections
3794            .first()
3795            .context("Expected at least one section")?;
3796        ensure!(first_section.offset == 0x2c);
3797        ensure!(first_section.name == "VERSION");
3798        ensure!(first_section.declared_size == 0x12);
3799
3800        let section_names: Vec<&str> = parsed
3801            .sections
3802            .iter()
3803            .map(|section| section.name.as_str())
3804            .collect();
3805        if std::env::var_os("CTB_PAN_DEBUG_PANIC").is_some() {
3806            return Err(anyhow::anyhow!(
3807                "{:#?}",
3808                serde_json::to_string_pretty(&parsed)?
3809            )); // Note to Copilot: don't remove this line. It's useful; I'll move it around as I'm runinng the tests.
3810        }
3811        ensure!(section_names.contains(&"VERSION"));
3812        ensure!(section_names.contains(&"DATA"));
3813        ensure!(section_names.contains(&"FORMS"));
3814
3815        let schema = parsed.schema.context("Expected schema to be parsed")?;
3816        ensure!(schema.fields.len() == 9);
3817        let first_field = schema
3818            .fields
3819            .first()
3820            .context("Expected first schema field")?;
3821        ensure!(first_field.name == "ExampleTextField");
3822        ensure!(first_field.field_type == PanFieldType::Text);
3823        ensure!(first_field.type_label == "Text");
3824        let second_field = schema
3825            .fields
3826            .get(1)
3827            .context("Expected second schema field")?;
3828        ensure!(second_field.field_type == PanFieldType::Integer);
3829        let seventh_field = schema
3830            .fields
3831            .get(6)
3832            .context("Expected seventh schema field")?;
3833        ensure!(seventh_field.field_type == PanFieldType::Date);
3834        let eighth_field = schema
3835            .fields
3836            .get(7)
3837            .context("Expected eighth schema field")?;
3838        ensure!(eighth_field.field_type == PanFieldType::Float);
3839
3840        let data = parsed.data.context("Expected DATA records to be parsed")?;
3841        ensure!(data.sections.len() == 1);
3842        let first_data_section = data
3843            .sections
3844            .first()
3845            .context("Expected first DATA section")?;
3846        ensure!(first_data_section.name == "DATA");
3847        ensure!(data.records.len() == 3);
3848
3849        let first_record =
3850            data.records.first().context("Expected first DATA record")?;
3851        ensure!(matches!(
3852            first_record.fields.first().map(|field| &field.value),
3853            Some(PanDataValue::Text(value)) if value == "Text value"
3854        ));
3855        ensure!(matches!(
3856            first_record.fields.get(1).map(|field| &field.value),
3857            Some(PanDataValue::Integer(value)) if value == "1"
3858        ));
3859        ensure!(matches!(
3860            first_record.fields.get(2).map(|field| &field.value),
3861            Some(PanDataValue::Fixed(value)) if value == "1.1"
3862        ));
3863        ensure!(matches!(
3864            first_record.fields.get(3).map(|field| &field.value),
3865            Some(PanDataValue::Fixed(value)) if value == "1.11"
3866        ));
3867        ensure!(
3868            first_record
3869                .fields
3870                .get(3)
3871                .and_then(|field| field.formatted_value.as_deref())
3872                .is_none()
3873        );
3874        ensure!(matches!(
3875            first_record.fields.get(4).map(|field| &field.value),
3876            Some(PanDataValue::Fixed(value)) if value == "1.111"
3877        ));
3878        ensure!(matches!(
3879            first_record.fields.get(5).map(|field| &field.value),
3880            Some(PanDataValue::Fixed(value)) if value == "1.1111"
3881        ));
3882        ensure!(matches!(
3883            first_record.fields.get(6).map(|field| &field.value),
3884            Some(PanDataValue::Date { raw_serial, pan_date_mdy })
3885                if *raw_serial == crate::date::datevalue(1935, 5, 3)?
3886                    && pan_date_mdy.as_deref() == Some("5/3/35")
3887        ));
3888        ensure!(
3889            first_record
3890                .fields
3891                .get(6)
3892                .and_then(|field| field.formatted_value.as_deref())
3893                .is_none()
3894        );
3895        ensure!(matches!(
3896            first_record.fields.get(7).map(|field| &field.value),
3897            Some(PanDataValue::Float(value)) if value == "1.1111111"
3898        ));
3899        ensure!(matches!(
3900            first_record.fields.get(8).map(|field| &field.value),
3901            Some(PanDataValue::Fixed(value)) if value == "1.11"
3902        ));
3903
3904        let third_record =
3905            data.records.get(2).context("Expected third DATA record")?;
3906        ensure!(matches!(
3907            third_record.fields.first().map(|field| &field.value),
3908            Some(PanDataValue::Text(value)) if value.is_empty()
3909        ));
3910        ensure!(matches!(
3911            third_record.fields.get(1).map(|field| &field.value),
3912            Some(PanDataValue::Integer(value)) if value.is_empty()
3913        ));
3914        ensure!(matches!(
3915            third_record.fields.get(7).map(|field| &field.value),
3916            Some(PanDataValue::Float(value)) if value.is_empty()
3917        ));
3918        ensure!(matches!(
3919            third_record.fields.get(6).map(|field| &field.value),
3920            Some(PanDataValue::Date { pan_date_mdy, .. })
3921                if pan_date_mdy.as_deref() == Some("3/2/26")
3922        ));
3923        ensure!(matches!(
3924            third_record.fields.get(8).map(|field| &field.value),
3925            Some(PanDataValue::Fixed(value)) if value.is_empty()
3926        ));
3927
3928        ensure!(parsed.trailing_bytes.is_empty());
3929        Ok(())
3930    }
3931
3932    #[crate::ctb_test]
3933    fn test_parse_pan_parses_example2_fixture_structure() -> anyhow::Result<()>
3934    {
3935        let pan_file = crate::get_pan_data("fixtures/example2 with lemurs.pan")
3936            .context("Could not load fixtures/example2 with lemurs.pan")?;
3937
3938        let parsed = parse_pan(&pan_file)?;
3939
3940        ensure!(
3941            parsed
3942                .prelude
3943                .entries
3944                .iter()
3945                .map(|entry| entry.name.as_str())
3946                .collect::<Vec<_>>()
3947                == vec!["example2 with lemurs", "DESIGN", "SHEET", "H"]
3948        );
3949
3950        let first_section = parsed
3951            .sections
3952            .first()
3953            .context("Expected at least one section")?;
3954        ensure!(first_section.name == "VERSION");
3955
3956        let section_names: Vec<&str> = parsed
3957            .sections
3958            .iter()
3959            .map(|section| section.name.as_str())
3960            .collect();
3961        ensure!(section_names.contains(&"FORMS"));
3962        ensure!(section_names.contains(&"DATA"));
3963
3964        let schema = parsed.schema.context("Expected schema to be parsed")?;
3965        ensure!(schema.fields.len() == 3);
3966        ensure!(
3967            schema
3968                .fields
3969                .iter()
3970                .map(|field| field.name.as_str())
3971                .collect::<Vec<_>>()
3972                == vec![
3973                    "textfield1",
3974                    "textfield2-with-word-caps",
3975                    "LEMURS ARE TAKING  OVER RHODE ISLAND",
3976                ]
3977        );
3978
3979        let data = parsed
3980            .data
3981            .context("Expected DATA rows in example2 fixture")?;
3982        ensure!(data.sections.len() == 1);
3983        let first_data_section = data
3984            .sections
3985            .first()
3986            .context("Expected first DATA section")?;
3987        ensure!(first_data_section.name.starts_with("DATA"));
3988        ensure!(data.records.len() == 2);
3989
3990        let first_record =
3991            data.records.first().context("Expected first DATA record")?;
3992        ensure!(matches!(
3993            first_record.fields.first().map(|field| &field.value),
3994            Some(PanDataValue::Text(value)) if value == "text field value 1"
3995        ));
3996        ensure!(matches!(
3997            first_record.fields.get(1).map(|field| &field.value),
3998            Some(PanDataValue::Text(value)) if value == "This Field Adds Capitals"
3999        ));
4000        ensure!(matches!(
4001            first_record.fields.get(2).map(|field| &field.value),
4002            Some(PanDataValue::Text(value)) if value.is_empty()
4003        ));
4004
4005        let second_record =
4006            data.records.get(1).context("Expected second DATA record")?;
4007        ensure!(matches!(
4008            second_record.fields.get(2).map(|field| &field.value),
4009            Some(PanDataValue::Text(value)) if value == "LEMUR LEMUR LEMUR"
4010        ));
4011
4012        Ok(())
4013    }
4014
4015    #[crate::ctb_test]
4016    fn test_parse_pan_parses_output_patterns_and_formatted_values()
4017    -> anyhow::Result<()> {
4018        let pan_file = crate::get_pan_data("fixtures/Sample with patterns.pan")
4019            .context("Could not load fixtures/Sample with patterns.pan")?;
4020
4021        let parsed = parse_pan(&pan_file)?;
4022        ensure!(!parsed.sections.is_empty());
4023        ensure!(parsed.sections.iter().any(|section| section.name == "DATA"));
4024        if std::env::var_os("CTB_PAN_DEBUG_PANIC").is_some() {
4025            return Err(anyhow::anyhow!(
4026                "{:#?}",
4027                serde_json::to_string_pretty(&parsed)?
4028            )); // Note to Copilot: don't remove this line. It's useful; I'll move it around as I'm runinng the tests.
4029        }
4030
4031        let schema = parsed.schema.context("Expected schema to be parsed")?;
4032        ensure!(schema.fields.len() == 9);
4033
4034        let fixed2_field = schema
4035            .fields
4036            .get(3)
4037            .context("Expected fixed2 field in schema")?;
4038        ensure!(fixed2_field.name == "ExampleNumericFieldFixed2");
4039        ensure!(fixed2_field.output_pattern.as_deref() == Some("#,.## oz"));
4040
4041        let date_field = schema
4042            .fields
4043            .get(6)
4044            .context("Expected date field in schema")?;
4045        ensure!(date_field.name == "ExampleDateField");
4046        ensure!(date_field.output_pattern.as_deref() == Some("MM-DD-YYYY"));
4047
4048        let data = parsed.data.context("Expected DATA records to be parsed")?;
4049        let first_record =
4050            data.records.first().context("Expected first DATA record")?;
4051
4052        ensure!(matches!(
4053            first_record.fields.get(3).map(|field| &field.value),
4054            Some(PanDataValue::Fixed(value)) if value == "1.11"
4055        ));
4056        ensure!(
4057            first_record
4058                .fields
4059                .get(3)
4060                .and_then(|field| field.formatted_value.as_deref())
4061                == Some("1.11 oz")
4062        );
4063
4064        ensure!(matches!(
4065            first_record.fields.get(6).map(|field| &field.value),
4066            Some(PanDataValue::Date { pan_date_mdy, .. })
4067                if pan_date_mdy.as_deref() == Some("5/3/35")
4068        ));
4069        ensure!(
4070            first_record
4071                .fields
4072                .get(6)
4073                .and_then(|field| field.formatted_value.as_deref())
4074                == Some("05-03-1935")
4075        );
4076
4077        Ok(())
4078    }
4079
4080    #[crate::ctb_test]
4081    fn test_format_data_field_value_cents_and_words_pattern()
4082    -> anyhow::Result<()> {
4083        let field = PanSchemaField {
4084            index: 0,
4085            name: "Amount".to_string(),
4086            width: 20,
4087            type_code: 2,
4088            type_label: "Fixed".to_string(),
4089            field_type: PanFieldType::Fixed2,
4090            output_pattern: Some("§ dollar~ and ¢¢/100".to_string()),
4091            ..Default::default()
4092        };
4093
4094        let val_42 = PanDataValue::Fixed("42.29".to_string());
4095        let formatted_42 = format_data_field_value(&field, &val_42)?;
4096        ensure!(
4097            formatted_42.as_deref() == Some("Forty two dollars and 29/100")
4098        );
4099
4100        let val_1 = PanDataValue::Fixed("1.05".to_string());
4101        let formatted_1 = format_data_field_value(&field, &val_1)?;
4102        ensure!(formatted_1.as_deref() == Some("One dollar and 05/100"));
4103
4104        let val_int = PanDataValue::Integer("100".to_string());
4105        let formatted_int = format_data_field_value(&field, &val_int)?;
4106        ensure!(
4107            formatted_int.as_deref() == Some("One hundred dollars and 00/100")
4108        );
4109
4110        let val_empty = PanDataValue::Fixed(String::new());
4111        let formatted_empty = format_data_field_value(&field, &val_empty)?;
4112        ensure!(formatted_empty.is_none());
4113
4114        Ok(())
4115    }
4116
4117    #[crate::ctb_test]
4118    fn test_parse_data_payload_supports_fe_be16_record_lengths()
4119    -> anyhow::Result<()> {
4120        let schema = PanSchema {
4121            names_section_offset: 0,
4122            widths_section_offset: 0,
4123            types_section_offset: 0,
4124            fields: vec![PanSchemaField {
4125                index: 0,
4126                name: "Token".to_string(),
4127                width: 20,
4128                type_code: 0,
4129                type_label: "Text".to_string(),
4130                field_type: PanFieldType::Text,
4131                output_pattern: None,
4132                ..Default::default()
4133            }],
4134        };
4135
4136        let payload = vec![
4137            0, 0, 0, 0, 0, 0, // DATA section header bytes
4138            0xfe, 0x00, 0x09, 0x00,
4139            0x00, // FE + BE16 record length + 2-byte marker
4140            0x01, // per-record status byte
4141            0x03, b'A', b'B', // single text field, length-prefixed
4142            0, 0, // trailing zeros
4143        ];
4144
4145        let (records, header_bytes, trailing_bytes) =
4146            parse_data_payload(&payload, 0x1000, &schema)?;
4147        ensure!(header_bytes == vec![0, 0, 0, 0, 0, 0]);
4148        ensure!(records.len() == 1);
4149        ensure!(trailing_bytes == vec![0, 0]);
4150
4151        let first = records.first().context("Expected one parsed DATA row")?;
4152        ensure!(first.fields.len() == 1);
4153        ensure!(matches!(
4154            first.fields.first().map(|field| &field.value),
4155            Some(PanDataValue::Text(value)) if value == "AB"
4156        ));
4157
4158        Ok(())
4159    }
4160
4161    #[crate::ctb_test]
4162    fn test_parse_data_payload_supports_be32_prefixed_header()
4163    -> anyhow::Result<()> {
4164        let schema = PanSchema {
4165            names_section_offset: 0,
4166            widths_section_offset: 0,
4167            types_section_offset: 0,
4168            fields: vec![PanSchemaField {
4169                index: 0,
4170                name: "Token".to_string(),
4171                width: 20,
4172                type_code: 0,
4173                type_label: "Text".to_string(),
4174                field_type: PanFieldType::Text,
4175                output_pattern: None,
4176                ..Default::default()
4177            }],
4178        };
4179
4180        let payload = vec![
4181            0x00, 0x00, 0x00, 0x01, 0x00,
4182            0x00, // BE32-prefixed DATA header
4183            0x07, 0x00, 0x00, 0x00, // LE32 record length
4184            0x03, b'A', b'B', // single text field, length-prefixed
4185            0, 0, // trailing zeros
4186        ];
4187
4188        let (records, header_bytes, trailing_bytes) =
4189            parse_data_payload(&payload, 0x1100, &schema)?;
4190        ensure!(header_bytes == vec![0, 0, 0, 1, 0, 0]);
4191        ensure!(records.len() == 1);
4192        ensure!(trailing_bytes == vec![0, 0]);
4193
4194        let first = records.first().context("Expected one parsed DATA row")?;
4195        ensure!(matches!(
4196            first.fields.first().map(|field| &field.value),
4197            Some(PanDataValue::Text(value)) if value == "AB"
4198        ));
4199
4200        Ok(())
4201    }
4202
4203    #[crate::ctb_test]
4204    fn test_parse_data_payload_supports_le24_status_record_lengths()
4205    -> anyhow::Result<()> {
4206        let schema = PanSchema {
4207            names_section_offset: 0,
4208            widths_section_offset: 0,
4209            types_section_offset: 0,
4210            fields: vec![PanSchemaField {
4211                index: 0,
4212                name: "Token".to_string(),
4213                width: 20,
4214                type_code: 0,
4215                type_label: "Text".to_string(),
4216                field_type: PanFieldType::Text,
4217                output_pattern: None,
4218                ..Default::default()
4219            }],
4220        };
4221
4222        let payload = vec![
4223            0, 0, 0, 0, 0, 0, // DATA section header bytes
4224            0x07, 0x00, 0x00, // LE24 record length
4225            0x01, // per-record status byte
4226            0x03, b'A', b'B', // single text field, length-prefixed
4227            0, 0, // trailing zeros
4228        ];
4229
4230        let (records, header_bytes, trailing_bytes) =
4231            parse_data_payload(&payload, 0x3000, &schema)?;
4232        ensure!(header_bytes == vec![0, 0, 0, 0, 0, 0]);
4233        ensure!(records.len() == 1);
4234        ensure!(trailing_bytes == vec![0, 0]);
4235
4236        let first = records.first().context("Expected one parsed DATA row")?;
4237        ensure!(first.fields.len() == 1);
4238        ensure!(matches!(
4239            first.fields.first().map(|field| &field.value),
4240            Some(PanDataValue::Text(value)) if value == "AB"
4241        ));
4242
4243        Ok(())
4244    }
4245
4246    #[crate::ctb_test]
4247    fn test_parse_data_payload_supports_zero_length_field_entries()
4248    -> anyhow::Result<()> {
4249        let schema = PanSchema {
4250            names_section_offset: 0,
4251            widths_section_offset: 0,
4252            types_section_offset: 0,
4253            fields: vec![
4254                PanSchemaField {
4255                    index: 0,
4256                    name: "Token".to_string(),
4257                    width: 20,
4258                    type_code: 0,
4259                    type_label: "Text".to_string(),
4260                    field_type: PanFieldType::Text,
4261                    output_pattern: None,
4262                    ..Default::default()
4263                },
4264                PanSchemaField {
4265                    index: 1,
4266                    name: "Body".to_string(),
4267                    width: 200,
4268                    type_code: 0,
4269                    type_label: "Text".to_string(),
4270                    field_type: PanFieldType::Text,
4271                    output_pattern: None,
4272                    ..Default::default()
4273                },
4274            ],
4275        };
4276
4277        let payload = vec![
4278            0, 0, 0, 0, 0, 0, // DATA section header bytes
4279            0xfe, 0x00, 0x0b, 0x00,
4280            0x00, // FE + BE16 record length + 2-byte marker
4281            0x01, // per-record status byte
4282            0x00, // empty field using zero-length entry
4283            0x04, b'A', b'B', b'C', // non-empty text field
4284            0, 0, // trailing zeros
4285        ];
4286
4287        let (records, _header_bytes, trailing_bytes) =
4288            parse_data_payload(&payload, 0x2000, &schema)?;
4289        ensure!(records.len() == 1);
4290        ensure!(trailing_bytes == vec![0, 0]);
4291
4292        let first = records.first().context("Expected one parsed DATA row")?;
4293        ensure!(matches!(
4294            first.fields.first().map(|field| &field.value),
4295            Some(PanDataValue::Text(value)) if value.is_empty()
4296        ));
4297        ensure!(matches!(
4298            first.fields.get(1).map(|field| &field.value),
4299            Some(PanDataValue::Text(value)) if value == "ABC"
4300        ));
4301
4302        Ok(())
4303    }
4304
4305    #[crate::ctb_test]
4306    fn test_data_section_with_non_ascii_marker_is_skipped() -> anyhow::Result<()>
4307    {
4308        let pan_file = crate::get_pan_data("fixtures/Sample with patterns.pan")
4309            .context("Could not load fixtures/Sample with patterns.pan")?;
4310
4311        let parsed = parse_pan(&pan_file)?;
4312        let data = parsed.data.context("Expected DATA records to be parsed")?;
4313        ensure!(data.records.len() == 3);
4314
4315        let first_record =
4316            data.records.first().context("Expected first DATA record")?;
4317        ensure!(matches!(
4318            first_record.fields.get(3).map(|field| &field.value),
4319            Some(PanDataValue::Fixed(value)) if value == "1.11"
4320        ));
4321
4322        Ok(())
4323    }
4324
4325    #[crate::ctb_test]
4326    fn test_diagnose_missing_data_reports_section_failure_details()
4327    -> anyhow::Result<()> {
4328        let schema = PanSchema {
4329            names_section_offset: 0,
4330            widths_section_offset: 0,
4331            types_section_offset: 0,
4332            fields: vec![PanSchemaField {
4333                index: 0,
4334                name: "Token".to_string(),
4335                width: 20,
4336                type_code: 0,
4337                type_label: "Text".to_string(),
4338                field_type: PanFieldType::Text,
4339                output_pattern: None,
4340                ..Default::default()
4341            }],
4342        };
4343
4344        let pan = PanDocument {
4345            prelude: PanPrelude {
4346                first_u32_le: 0,
4347                entries: Vec::new(),
4348                raw_bytes: Vec::new(),
4349            },
4350            sections: vec![PanSection {
4351                offset: 0x1234,
4352                declared_size: 20,
4353                kind: 0x82,
4354                name_raw: b"DATA".to_vec(),
4355                name: "DATA".to_string(),
4356                payload: vec![0, 0, 0, 0, 0, 0, 0xff, 0, 0, 0],
4357            }],
4358            schema: Some(schema),
4359            data: None,
4360            launch_form: None,
4361            record_count: None,
4362            macros: Vec::new(),
4363            trailing_bytes: Vec::new(),
4364        };
4365
4366        let diagnostic = diagnose_missing_data(&pan);
4367        ensure!(diagnostic.contains("PAN data is missing"));
4368        ensure!(diagnostic.contains("offset=0x1234"));
4369        ensure!(
4370            diagnostic.contains("DATA record has unsupported length encoding")
4371        );
4372
4373        Ok(())
4374    }
4375
4376    #[crate::ctb_test]
4377    fn test_decode_data_field_value_falls_back_for_oversized_varint()
4378    -> anyhow::Result<()> {
4379        let field = PanSchemaField {
4380            index: 0,
4381            name: "NumericField".to_string(),
4382            width: 20,
4383            type_code: 6,
4384            type_label: "Integer".to_string(),
4385            field_type: PanFieldType::Integer,
4386            output_pattern: None,
4387            ..Default::default()
4388        };
4389
4390        let raw_bytes = vec![0xaa; 31];
4391        let value = decode_data_field_value(&field, &raw_bytes)?;
4392        ensure!(matches!(value, PanDataValue::Unknown(_)));
4393
4394        Ok(())
4395    }
4396
4397    #[crate::ctb_test]
4398    fn test_decode_data_field_value_normalizes_cr_to_lf() -> anyhow::Result<()>
4399    {
4400        let field = PanSchemaField {
4401            index: 0,
4402            name: "Body".to_string(),
4403            width: 200,
4404            type_code: 0,
4405            type_label: "Text".to_string(),
4406            field_type: PanFieldType::Text,
4407            output_pattern: None,
4408            ..Default::default()
4409        };
4410
4411        let value = decode_data_field_value(&field, b"line1\rline2\r")?;
4412        ensure!(matches!(
4413            value,
4414            PanDataValue::Text(text) if text == "line1\nline2\n"
4415        ));
4416
4417        Ok(())
4418    }
4419
4420    #[crate::ctb_test]
4421    fn test_parse_section_supports_be_declared_size() -> anyhow::Result<()> {
4422        let section_bytes = vec![
4423            0x00, 0x00, 0x00, 0x12, // BE size = 18 bytes
4424            0x83, 0x07, // kind + name length
4425            b'V', b'E', b'R', b'S', b'I', b'O', b'N', // name
4426            0x00, 0x03, 0x00, 0x00, 0x01, // payload
4427        ];
4428
4429        ensure!(section_header_looks_valid(&section_bytes, 0)?);
4430        let section = parse_section_at(&section_bytes, 0)?;
4431        ensure!(section.name == "VERSION");
4432        ensure!(section.declared_size == 18);
4433        ensure!(section.payload == vec![0x00, 0x03, 0x00, 0x00, 0x01]);
4434
4435        Ok(())
4436    }
4437
4438    #[crate::ctb_test]
4439    fn test_parse_pan_supports_be_section_size_after_prelude()
4440    -> anyhow::Result<()> {
4441        let mut pan_file = Vec::new();
4442        pan_file.extend_from_slice(&0x6613_u32.to_le_bytes());
4443
4444        pan_file.push(0x00);
4445        pan_file.push(4);
4446        pan_file.extend_from_slice(b"Menu");
4447        pan_file.push(0x00);
4448        pan_file.extend_from_slice(&[0x00, 0x00, 0x00, 0x0c]);
4449
4450        pan_file.push(0x01);
4451        pan_file.push(6);
4452        pan_file.extend_from_slice(b"DESIGN");
4453        pan_file.push(0x00);
4454        pan_file.extend_from_slice(&[0x00, 0x00, 0x00, 0x20]);
4455
4456        pan_file.push(0x02);
4457        pan_file.push(1);
4458        pan_file.extend_from_slice(b"H");
4459        pan_file.push(0x00);
4460
4461        pan_file.extend_from_slice(&[
4462            0x00, 0x00, 0x00, 0x12, // BE size = 18
4463            0x83, 0x07, // kind + name length
4464            b'V', b'E', b'R', b'S', b'I', b'O', b'N', 0x00, 0x03, 0x00, 0x00,
4465            0x01,
4466        ]);
4467
4468        let parsed = parse_pan(&pan_file)?;
4469        ensure!(!parsed.sections.is_empty());
4470        ensure!(parsed.sections.first().is_some_and(|s| s.name == "VERSION"));
4471
4472        Ok(())
4473    }
4474
4475    #[crate::ctb_test]
4476    fn test_select_schema_for_data_section_uses_nearest_offset()
4477    -> anyhow::Result<()> {
4478        let schema_a = PanSchema {
4479            names_section_offset: 0x100,
4480            widths_section_offset: 0x110,
4481            types_section_offset: 0x120,
4482            fields: vec![PanSchemaField {
4483                index: 0,
4484                name: "A".to_string(),
4485                width: 10,
4486                type_code: 0,
4487                type_label: "Text".to_string(),
4488                field_type: PanFieldType::Text,
4489                output_pattern: None,
4490                ..Default::default()
4491            }],
4492        };
4493        let schema_b = PanSchema {
4494            names_section_offset: 0x900,
4495            widths_section_offset: 0x910,
4496            types_section_offset: 0x920,
4497            fields: vec![PanSchemaField {
4498                index: 0,
4499                name: "B".to_string(),
4500                width: 10,
4501                type_code: 0,
4502                type_label: "Text".to_string(),
4503                field_type: PanFieldType::Text,
4504                output_pattern: None,
4505                ..Default::default()
4506            }],
4507        };
4508        let schemas = vec![schema_a, schema_b];
4509        let selected = select_schema_for_data_section(&schemas, 0x880)
4510            .context("Expected a selected schema")?;
4511        ensure!(selected.names_section_offset == 0x900);
4512
4513        Ok(())
4514    }
4515
4516    #[crate::ctb_test]
4517    fn test_parse_prelude_terminator_aligns_to_even_word_boundary()
4518    -> anyhow::Result<()> {
4519        let mut pan_file = Vec::new();
4520        pan_file.extend_from_slice(&0x6613_u32.to_le_bytes()); // magic 4 bytes (0x00..0x04)
4521
4522        // Entry 1 at 0x04: kind=1, name="MENU", value=0x1234 (10 bytes: 0x04..0x0e)
4523        pan_file.push(0x01);
4524        pan_file.push(4);
4525        pan_file.extend_from_slice(b"MENU");
4526        pan_file.extend_from_slice(&[0x34, 0x12, 0x00, 0x00]);
4527
4528        // Entry 2 at 0x0e: kind=2, name="H" (name_end = 0x11, odd -> value_cursor = 0x12)
4529        pan_file.push(0x02);
4530        pan_file.push(1);
4531        pan_file.extend_from_slice(b"H");
4532        pan_file.push(0x00); // pad byte at 0x11 aligning to 0x12
4533
4534        // Section at 0x12
4535        pan_file.extend_from_slice(&[
4536            0x00, 0x00, 0x00, 0x12, // BE size = 18
4537            0x83, 0x07, // kind + name length
4538            b'V', b'E', b'R', b'S', b'I', b'O', b'N', // name
4539            0x00, 0x03, 0x00, 0x00, 0x01, // payload
4540        ]);
4541
4542        let (entries, first_section) = parse_prelude_entries(&pan_file, true)?;
4543        ensure!(entries.len() == 2);
4544        ensure!(first_section == 0x12);
4545
4546        Ok(())
4547    }
4548
4549    #[crate::ctb_test]
4550    fn test_parse_framed_schema_payload_headers() -> anyhow::Result<()> {
4551        // NAMES with 0x53 0x00 2-byte tag header
4552        let names_payload = vec![
4553            0x53, 0x00, // framed tag header
4554            0x14, 0x00, 0x00,
4555            0x00, // declared byte count = 20 (6 header + 14 data)
4556            0x07, b'F', b'i', b'e', b'l', b'd',
4557            b'A', // 7 bytes (1 len + 6 chars)
4558            0x07, b'F', b'i', b'e', b'l', b'd',
4559            b'B', // 7 bytes (1 len + 6 chars)
4560        ];
4561        let names = parse_names_payload(&names_payload, 2)?;
4562        ensure!(names == vec!["FieldA", "FieldB"]);
4563
4564        // WIDTHS with "HS" 2-byte tag header
4565        let widths_payload = vec![
4566            0x48, 0x53, // "HS"
4567            0x00, 0x64, // 100 BE
4568            0x00, 0xc8, // 200 BE
4569        ];
4570        let widths = parse_widths_payload(&widths_payload, true)?;
4571        ensure!(widths == vec![100, 200]);
4572
4573        // TYPES with 0x53 0x00 2-byte tag header
4574        let types_payload = vec![
4575            0x53, 0x00, // 0x53 0x00 tag
4576            0x00, // Type: Text
4577            0x06, // Type: Integer
4578        ];
4579        let types = parse_types_payload(&types_payload, 2)?;
4580        ensure!(types == vec![0x00, 0x06]);
4581
4582        // USING with 0x47 0x00 2-byte tag header
4583        let using_payload = vec![
4584            0x47, 0x00, // framed tag header
4585            0x0c, 0x00, 0x00,
4586            0x00, // declared byte count = 12 (6 header + 6 data)
4587            0x06, b'$', b'#', b'.', b'#',
4588            b'#', // 6 bytes (1 len + 5 chars)
4589        ];
4590        let using = parse_using_payload(&using_payload, 1)?;
4591        ensure!(using.len() == 1);
4592        ensure!(using[0].as_deref() == Some("$#.##"));
4593
4594        Ok(())
4595    }
4596
4597    #[crate::ctb_test]
4598    fn test_parse_data_payload_byte8_with_status_4byte_header()
4599    -> anyhow::Result<()> {
4600        let schema = PanSchema {
4601            names_section_offset: 0,
4602            widths_section_offset: 0,
4603            types_section_offset: 0,
4604            fields: vec![
4605                PanSchemaField {
4606                    index: 0,
4607                    name: "Park".to_string(),
4608                    width: 100,
4609                    type_code: 0,
4610                    type_label: "Text".to_string(),
4611                    field_type: PanFieldType::Text,
4612                    output_pattern: None,
4613                    ..Default::default()
4614                },
4615                PanSchemaField {
4616                    index: 1,
4617                    name: "State".to_string(),
4618                    width: 50,
4619                    type_code: 0,
4620                    type_label: "Text".to_string(),
4621                    field_type: PanFieldType::Text,
4622                    output_pattern: None,
4623                    ..Default::default()
4624                },
4625            ],
4626        };
4627
4628        // DATA section payload with 2-byte section header
4629        let mut payload = vec![0x00, 0x00];
4630
4631        // Record 0: sz=16 (0x10), header=[0x10, 0x80, 0x00, 0x01]
4632        // Field 0: len=6 (1 + 5 bytes "Zion ") -> "Zion "
4633        // Field 1: len=3 (1 + 2 bytes "UT") -> "UT"
4634        // Total record bytes = 4 (header) + 6 (f0) + 3 (f1) + 2 (pad) + 1 (trailer 0x10) = 16
4635        payload.extend_from_slice(&[
4636            0x10, 0x80, 0x00,
4637            0x01, // 4-byte header: sz=16, flag=0x80, status=0x00, 0x01
4638            0x06, b'Z', b'i', b'o', b'n', b' ', // Field 0
4639            0x03, b'U', b'T', // Field 1
4640            0x00, 0x00, // padding within declared sz
4641            0x10, // 1-byte trailer matching sz
4642        ]);
4643
4644        // Record 1: sz=17 (0x11), header=[0x11, 0x80, 0x00, 0x07]
4645        // Field 0: len=7 (1 + 6 bytes "Acadia") -> "Acadia"
4646        // Field 1: len=3 (1 + 2 bytes "ME") -> "ME"
4647        // Total record bytes = 4 (header) + 7 (f0) + 3 (f1) + 2 (pad) + 1 (trailer 0x11) = 17
4648        payload.extend_from_slice(&[
4649            0x11, 0x80, 0x00,
4650            0x07, // 4-byte header: sz=17, flag=0x80, status=0x00, 0x07
4651            0x07, b'A', b'c', b'a', b'd', b'i', b'a', // Field 0
4652            0x03, b'M', b'E', // Field 1
4653            0x00, 0x00, // padding within declared sz
4654            0x11, // 1-byte trailer matching sz
4655        ]);
4656
4657        let (records, _, trailing) =
4658            parse_data_payload(&payload, 0x1000, &schema)?;
4659        ensure!(records.len() == 2);
4660        ensure!(trailing.is_empty());
4661
4662        let r0_f0 = records.first().and_then(|r| r.fields.first());
4663        ensure!(
4664            matches!(r0_f0.map(|f| &f.value), Some(PanDataValue::Text(val)) if val == "Zion ")
4665        );
4666
4667        let r1_f0 = records.get(1).and_then(|r| r.fields.first());
4668        ensure!(
4669            matches!(r1_f0.map(|f| &f.value), Some(PanDataValue::Text(val)) if val == "Acadia")
4670        );
4671
4672        Ok(())
4673    }
4674
4675    #[crate::ctb_test]
4676    fn test_parse_data_payload_fe_be16_5byte_header_field_alignment()
4677    -> anyhow::Result<()> {
4678        let schema = PanSchema {
4679            names_section_offset: 0,
4680            widths_section_offset: 0,
4681            types_section_offset: 0,
4682            fields: vec![
4683                PanSchemaField {
4684                    index: 0,
4685                    name: "Token".to_string(),
4686                    width: 100,
4687                    type_code: 0,
4688                    type_label: "Text".to_string(),
4689                    field_type: PanFieldType::Text,
4690                    output_pattern: None,
4691                    ..Default::default()
4692                },
4693                PanSchemaField {
4694                    index: 1,
4695                    name: "Params".to_string(),
4696                    width: 100,
4697                    type_code: 0,
4698                    type_label: "Text".to_string(),
4699                    field_type: PanFieldType::Text,
4700                    output_pattern: None,
4701                    ..Default::default()
4702                },
4703            ],
4704        };
4705
4706        // 6-byte DATA section header
4707        let mut payload = vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
4708
4709        // Record 0: 5-byte header [0xfe, 0x00, 0x12, 0x00, 0x00], status=0x01
4710        // Field 0: len=3 -> "?("
4711        // Field 1: len=9 -> "PARAM1,P2"
4712        // Total = 5 (header) + 1 (status) + 3 (f0) + 9 (f1) = 18 (0x12)
4713        payload.extend_from_slice(&[
4714            0xfe, 0x00, 0x12, 0x00, 0x00, // 5-byte BE16 header
4715            0x01, // status byte
4716            0x03, b'?', b'(', // Field 0 ("Token")
4717            0x09, b'P', b'A', b'R', b'A', b'M', b'1', b',',
4718            b'P', // Field 1 ("Params")
4719        ]);
4720
4721        let (records, _, _) = parse_data_payload(&payload, 0x2000, &schema)?;
4722        ensure!(records.len() == 1);
4723        ensure!(
4724            matches!(&records[0].fields[0].value, PanDataValue::Text(t) if t == "?(")
4725        );
4726        ensure!(
4727            matches!(&records[0].fields[1].value, PanDataValue::Text(t) if t == "PARAM1,P")
4728        );
4729
4730        Ok(())
4731    }
4732
4733    #[crate::ctb_test]
4734    fn test_parse_data_payload_fe_be16_with_nonzero_flags() -> anyhow::Result<()>
4735    {
4736        let schema = PanSchema {
4737            names_section_offset: 0x1000,
4738            types_section_offset: 0x1050,
4739            widths_section_offset: 0x1080,
4740            fields: vec![
4741                PanSchemaField {
4742                    index: 0,
4743                    name: "Title".to_string(),
4744                    width: 10,
4745                    type_code: 0,
4746                    type_label: "Text".to_string(),
4747                    field_type: PanFieldType::Text,
4748                    output_pattern: None,
4749                    ..Default::default()
4750                },
4751                PanSchemaField {
4752                    index: 1,
4753                    name: "Name".to_string(),
4754                    width: 15,
4755                    type_code: 0,
4756                    type_label: "Text".to_string(),
4757                    field_type: PanFieldType::Text,
4758                    output_pattern: None,
4759                    ..Default::default()
4760                },
4761            ],
4762        };
4763
4764        // 6-byte DATA section header
4765        let mut payload = vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
4766
4767        // Record with non-zero flags in bytes 3..4: [0xfe, 0x00, 0x12, 0x06, 0xf8]
4768        // status byte = 0xe0
4769        // Field 0: len=8 -> "Senator" (1 len byte + 7 chars)
4770        // Field 1: len=4 -> "Tim" (1 len byte + 3 chars)
4771        // Total = 5 (header) + 1 (status) + 8 (f0) + 4 (f1) = 18 (0x12)
4772        payload.extend_from_slice(&[
4773            0xfe, 0x00, 0x12, 0x06,
4774            0xf8, // 5-byte BE16 header with non-zero flags
4775            0xe0, // status byte
4776            0x08, b'S', b'e', b'n', b'a', b't', b'o',
4777            b'r', // Field 0 ("Title")
4778            0x04, b'T', b'i', b'm', // Field 1 ("Name")
4779        ]);
4780
4781        let (records, _, _) = parse_data_payload(&payload, 0x1000, &schema)?;
4782        ensure!(records.len() == 1);
4783        ensure!(
4784            matches!(&records[0].fields[0].value, PanDataValue::Text(t) if t == "Senator")
4785        );
4786        ensure!(
4787            matches!(&records[0].fields[1].value, PanDataValue::Text(t) if t == "Tim")
4788        );
4789
4790        Ok(())
4791    }
4792
4793    #[crate::ctb_test]
4794    fn test_parse_data_payload_le24_starting_at_offset_2() -> anyhow::Result<()>
4795    {
4796        let schema = PanSchema {
4797            names_section_offset: 0x1000,
4798            types_section_offset: 0x1050,
4799            widths_section_offset: 0x1080,
4800            fields: vec![
4801                PanSchemaField {
4802                    index: 0,
4803                    name: "Currency".to_string(),
4804                    width: 15,
4805                    type_code: 0,
4806                    type_label: "Text".to_string(),
4807                    field_type: PanFieldType::Text,
4808                    output_pattern: None,
4809                    ..Default::default()
4810                },
4811                PanSchemaField {
4812                    index: 1,
4813                    name: "Symbol".to_string(),
4814                    width: 5,
4815                    type_code: 0,
4816                    type_label: "Text".to_string(),
4817                    field_type: PanFieldType::Text,
4818                    output_pattern: None,
4819                    ..Default::default()
4820                },
4821            ],
4822        };
4823
4824        // 2-byte DATA section header [0x00, 0x00] followed immediately by LE24 record
4825        // Record size: 4 (header+status) + 14 (Field 0) + 2 (Field 1) = 20 (0x14)
4826        let mut payload = vec![0x00, 0x00];
4827        payload.extend_from_slice(&[
4828            0x14, 0x00, 0x00, // 3-byte LE24 size
4829            0x01, // status byte
4830            0x0e, b'B', b'r', b'i', b't', b'i', b's', b'h', b' ', b'P', b'o',
4831            b'u', b'n', b'd', // Field 0
4832            0x02, b'$', // Field 1
4833        ]);
4834
4835        let (records, _, _) = parse_data_payload(&payload, 0x1000, &schema)?;
4836        ensure!(records.len() == 1);
4837        ensure!(
4838            matches!(&records[0].fields[0].value, PanDataValue::Text(t) if t == "British Pound")
4839        );
4840        ensure!(
4841            matches!(&records[0].fields[1].value, PanDataValue::Text(t) if t == "$")
4842        );
4843
4844        Ok(())
4845    }
4846
4847    #[crate::ctb_test]
4848    fn test_parse_data_payload_6byte_be_length_prefix() -> anyhow::Result<()> {
4849        let schema = PanSchema {
4850            names_section_offset: 0x2000,
4851            types_section_offset: 0x2050,
4852            widths_section_offset: 0x2080,
4853            fields: vec![
4854                PanSchemaField {
4855                    index: 0,
4856                    name: "CustomerID".to_string(),
4857                    width: 10,
4858                    type_code: 6,
4859                    type_label: "Integer".to_string(),
4860                    field_type: PanFieldType::Integer,
4861                    output_pattern: None,
4862                    ..Default::default()
4863                },
4864                PanSchemaField {
4865                    index: 1,
4866                    name: "Class".to_string(),
4867                    width: 15,
4868                    type_code: 0,
4869                    type_label: "Text".to_string(),
4870                    field_type: PanFieldType::Text,
4871                    output_pattern: None,
4872                    ..Default::default()
4873                },
4874            ],
4875        };
4876
4877        // 6-byte section header [0x00, 0x00, hi, lo, 0x00, 0x00] followed by LE24 record
4878        // Record size = 4 (header+status) + 3 (Field 0: int 1000 = [232, 3]) + 7 (Field 1: "Dealer") = 14 (0x0e)
4879        let mut payload = vec![0x00, 0x00, 0x00, 0x0e, 0x00, 0x00];
4880        payload.extend_from_slice(&[
4881            0x0e, 0x00, 0x00, // 3-byte LE24 size
4882            0x00, // status byte
4883            0x03, 0xe8, 0x03, // Field 0: Integer 1000
4884            0x07, b'D', b'e', b'a', b'l', b'e',
4885            b'r', // Field 1: Text "Dealer"
4886        ]);
4887
4888        let (records, header_bytes, _) =
4889            parse_data_payload(&payload, 0x2000, &schema)?;
4890        ensure!(header_bytes.len() == 6);
4891        ensure!(records.len() == 1);
4892        ensure!(
4893            matches!(&records[0].fields[0].value, PanDataValue::Integer(i) if i == "1000")
4894        );
4895        ensure!(
4896            matches!(&records[0].fields[1].value, PanDataValue::Text(t) if t == "Dealer")
4897        );
4898
4899        Ok(())
4900    }
4901
4902    #[crate::ctb_test]
4903    fn test_parse_data_payload_6byte_le_length_prefix_fe_be16()
4904    -> anyhow::Result<()> {
4905        let schema = PanSchema {
4906            names_section_offset: 0x3000,
4907            types_section_offset: 0x3050,
4908            widths_section_offset: 0x3080,
4909            fields: vec![
4910                PanSchemaField {
4911                    index: 0,
4912                    name: "TrackingNumber".to_string(),
4913                    width: 20,
4914                    type_code: 0,
4915                    type_label: "Text".to_string(),
4916                    field_type: PanFieldType::Text,
4917                    output_pattern: None,
4918                    ..Default::default()
4919                },
4920                PanSchemaField {
4921                    index: 1,
4922                    name: "Status".to_string(),
4923                    width: 20,
4924                    type_code: 0,
4925                    type_label: "Text".to_string(),
4926                    field_type: PanFieldType::Text,
4927                    output_pattern: None,
4928                    ..Default::default()
4929                },
4930            ],
4931        };
4932
4933        // 6-byte section header [lo, hi, 0x00, 0x00, 0x00, 0x00] followed by FE+BE16 record
4934        // Record size = 6 (header+flags+status) + 13 (Field 0) + 18 (Field 1) = 37 (0x0025)
4935        let mut payload = vec![0x25, 0x00, 0x00, 0x00, 0x00, 0x00];
4936        payload.extend_from_slice(&[
4937            0xfe, 0x00, 0x25, // FE prefix + BE16 size (37)
4938            0x00, 0x00, // flags
4939            0x00, // status byte
4940            0x0d, b'8', b'2', b'9', b'1', b'7', b'7', b'3', b'9', b'3', b'1',
4941            b'3', b'6', // Field 0
4942            0x12, b'D', b'e', b'l', b'i', b'v', b'e', b'r', b'y', b' ', b'C',
4943            b'o', b'm', b'p', b'l', b'e', b't', b'e', // Field 1
4944        ]);
4945
4946        let (records, header_bytes, _) =
4947            parse_data_payload(&payload, 0x3000, &schema)?;
4948        ensure!(header_bytes.len() == 6);
4949        ensure!(records.len() == 1);
4950        ensure!(
4951            matches!(&records[0].fields[0].value, PanDataValue::Text(t) if t == "829177393136")
4952        );
4953        ensure!(
4954            matches!(&records[0].fields[1].value, PanDataValue::Text(t) if t == "Delivery Complete")
4955        );
4956
4957        Ok(())
4958    }
4959
4960    #[crate::ctb_test]
4961    fn test_parse_data_payload_6byte_tag_prefix_sample_structure()
4962    -> anyhow::Result<()> {
4963        let schema = PanSchema {
4964            names_section_offset: 0x4000,
4965            types_section_offset: 0x4050,
4966            widths_section_offset: 0x4080,
4967            fields: vec![
4968                PanSchemaField {
4969                    index: 0,
4970                    name: "Name".to_string(),
4971                    width: 20,
4972                    type_code: 0,
4973                    type_label: "Text".to_string(),
4974                    field_type: PanFieldType::Text,
4975                    output_pattern: None,
4976                    ..Default::default()
4977                },
4978                PanSchemaField {
4979                    index: 1,
4980                    name: "Score".to_string(),
4981                    width: 10,
4982                    type_code: 6,
4983                    type_label: "Integer".to_string(),
4984                    field_type: PanFieldType::Integer,
4985                    output_pattern: None,
4986                    ..Default::default()
4987                },
4988            ],
4989        };
4990
4991        // 6-byte section header [b'S', 0x00, 0x00, 0x00, 0x00, 0x00] followed by LE24 record
4992        // Record size = 4 (header+status) + 6 ("Alice") + 2 (score 42) = 12 (0x0c)
4993        let mut payload = vec![b'S', 0x00, 0x00, 0x00, 0x00, 0x00];
4994        payload.extend_from_slice(&[
4995            0x0c, 0x00, 0x00, // 3-byte LE24 size
4996            0x00, // status byte
4997            0x06, b'A', b'l', b'i', b'c', b'e', // Field 0
4998            0x02, 0x2a, // Field 1: Integer 42
4999        ]);
5000
5001        let (records, header_bytes, _) =
5002            parse_data_payload(&payload, 0x4000, &schema)?;
5003        ensure!(header_bytes.len() == 6);
5004        ensure!(header_bytes[0] == b'S');
5005        ensure!(records.len() == 1);
5006        ensure!(
5007            matches!(&records[0].fields[0].value, PanDataValue::Text(t) if t == "Alice")
5008        );
5009        ensure!(
5010            matches!(&records[0].fields[1].value, PanDataValue::Integer(i) if i == "42")
5011        );
5012
5013        Ok(())
5014    }
5015
5016    #[crate::ctb_test]
5017    fn test_parse_data_payload_6byte_arbitrary_prefix() -> anyhow::Result<()> {
5018        let schema = PanSchema {
5019            names_section_offset: 0x5000,
5020            types_section_offset: 0x5050,
5021            widths_section_offset: 0x5080,
5022            fields: vec![
5023                PanSchemaField {
5024                    index: 0,
5025                    name: "Function".to_string(),
5026                    width: 20,
5027                    type_code: 0,
5028                    type_label: "Text".to_string(),
5029                    field_type: PanFieldType::Text,
5030                    output_pattern: None,
5031                    ..Default::default()
5032                },
5033                PanSchemaField {
5034                    index: 1,
5035                    name: "Body".to_string(),
5036                    width: 30,
5037                    type_code: 0,
5038                    type_label: "Text".to_string(),
5039                    field_type: PanFieldType::Text,
5040                    output_pattern: None,
5041                    ..Default::default()
5042                },
5043            ],
5044        };
5045
5046        // 6-byte arbitrary section header [0x56, 0x11, 0x03, 0x00, 0x00, 0x00]
5047        // Byte8 record: total size = 26 (0x1a)
5048        // 4 header bytes: [0x1a, 0x00, 0x00, 0x01]
5049        // Field 0: 6 bytes [0x06, 'm', 'o', 'n', 'e', 'y']
5050        // Field 1: 15 bytes [0x0f, 'p', 'a', 't', 't', 'e', 'r', 'n', '(', 'n', 'u', 'm', 'b', 'e', 'r']
5051        // Trailer: 1 byte [0x1a] -> total = 4 + 6 + 15 + 1 = 26
5052        let mut payload = vec![0x56, 0x11, 0x03, 0x00, 0x00, 0x00];
5053        payload.extend_from_slice(&[
5054            0x1a, 0x00, 0x00, 0x01, 0x06, b'm', b'o', b'n', b'e', b'y', 0x0f,
5055            b'p', b'a', b't', b't', b'e', b'r', b'n', b'(', b'n', b'u', b'm',
5056            b'b', b'e', b'r', 0x1a,
5057        ]);
5058
5059        let (records, header_bytes, _) =
5060            parse_data_payload(&payload, 0x5000, &schema)?;
5061        ensure!(header_bytes.len() == 6);
5062        ensure!(records.len() == 1);
5063        ensure!(
5064            matches!(&records[0].fields[0].value, PanDataValue::Text(t) if t == "money")
5065        );
5066        ensure!(
5067            matches!(&records[0].fields[1].value, PanDataValue::Text(t) if t == "pattern(number")
5068        );
5069
5070        Ok(())
5071    }
5072
5073    #[crate::ctb_test]
5074    fn test_parse_data_payload_c0_compressed_control_byte() -> anyhow::Result<()>
5075    {
5076        let schema = PanSchema {
5077            names_section_offset: 0x6000,
5078            types_section_offset: 0x6050,
5079            widths_section_offset: 0x6080,
5080            fields: vec![
5081                PanSchemaField {
5082                    index: 0,
5083                    name: "Year".to_string(),
5084                    width: 10,
5085                    type_code: 0,
5086                    type_label: "Text".to_string(),
5087                    field_type: PanFieldType::Text,
5088                    output_pattern: None,
5089                    ..Default::default()
5090                },
5091                PanSchemaField {
5092                    index: 1,
5093                    name: "State".to_string(),
5094                    width: 5,
5095                    type_code: 0,
5096                    type_label: "Text".to_string(),
5097                    field_type: PanFieldType::Text,
5098                    output_pattern: None,
5099                    ..Default::default()
5100                },
5101            ],
5102        };
5103
5104        // 6-byte section header
5105        let mut payload = vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
5106        // Record size = 15 (0x0f)
5107        // 4 header bytes: [0x0f, 0x00, 0x00, 0x01]
5108        // Field 0: 5 bytes [0x05, '1', '9', '7', '6']
5109        // Field 1: control byte 0xc0 followed by [0x04, 'A', 'K'] -> 4 bytes
5110        // Trailer: [0x0f] -> total = 4 + 5 + 4 + 1 = 14 (+ 1 status/pad = 15)
5111        payload.extend_from_slice(&[
5112            0x0f, 0x00, 0x00, 0x01, 0x05, b'1', b'9', b'7', b'6', 0xc0, 0x04,
5113            b'A', b'K', 0x00, 0x0f,
5114        ]);
5115
5116        let (records, _, _) = parse_data_payload(&payload, 0x6000, &schema)?;
5117        ensure!(records.len() == 1);
5118        ensure!(
5119            matches!(&records[0].fields[0].value, PanDataValue::Text(t) if t == "1976")
5120        );
5121        ensure!(
5122            matches!(&records[0].fields[1].value, PanDataValue::Text(t) if t == "AK")
5123        );
5124
5125        Ok(())
5126    }
5127
5128    #[crate::ctb_test]
5129    fn test_parse_types_payload_strips_leading_zero_padding()
5130    -> anyhow::Result<()> {
5131        // Example: Phone Bill.pan with leading 0x00 pad followed by 9 field types
5132        let payload = vec![
5133            0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x08, 0x00, 0x49,
5134        ];
5135        let types = parse_types_payload(&payload, 9)?;
5136        ensure!(types.len() == 9);
5137        ensure!(types[0] == 0x04); // Date
5138        ensure!(types[1] == 0x00); // Text
5139        ensure!(types[5] == 0x06); // Integer
5140        ensure!(types[7] == 0x08); // Fixed(2)
5141        Ok(())
5142    }
5143
5144    #[crate::ctb_test]
5145    fn test_decode_pan_date_field_1byte_signed_offset() -> anyhow::Result<()> {
5146        // 1-byte signed offset from 1984-01-24:
5147        // Offset 5 -> 1984-01-29
5148        let (jdn5, mdy5) = decode_pan_date_field(&[5])?;
5149        ensure!(
5150            mdy5.as_deref() == Some("1/29/84")
5151                || mdy5.as_deref() == Some("01/29/1984")
5152                || jdn5 > 0
5153        );
5154        let datestr5 = crate::date::datestr(jdn5)?;
5155        ensure!(datestr5 == "1/29/84");
5156
5157        // Signed negative offset -7 (249 as u8) -> 1984-01-17
5158        let (jdn_neg, _) = decode_pan_date_field(&[249])?;
5159        let datestr_neg = crate::date::datestr(jdn_neg)?;
5160        ensure!(datestr_neg == "1/17/84");
5161
5162        Ok(())
5163    }
5164
5165    #[crate::ctb_test]
5166    fn test_parse_equations_and_design_attributes() -> anyhow::Result<()> {
5167        let pan_file =
5168            crate::get_pan_data("fixtures/Sample with patterns v2.pan")
5169                .context(
5170                    "Could not load fixtures/Sample with patterns v2.pan",
5171                )?;
5172
5173        let parsed = parse_pan(&pan_file)?;
5174        let schema = parsed.schema.context("Expected schema to be parsed")?;
5175        ensure!(schema.fields.len() == 9);
5176
5177        // Check field defaults and patterns
5178        let date_field = schema
5179            .fields
5180            .iter()
5181            .find(|f| f.name == "ExampleDateField")
5182            .context("ExampleDateField missing")?;
5183        ensure!(date_field.default_value.as_deref() == Some("today"));
5184        ensure!(date_field.output_pattern.as_deref() == Some("MM-DD-YYYY"));
5185
5186        let fixed2_field = schema
5187            .fields
5188            .iter()
5189            .find(|f| f.name == "ExampleNumericFieldFixed2")
5190            .context("ExampleNumericFieldFixed2 missing")?;
5191        ensure!(fixed2_field.output_pattern.as_deref() == Some("#,.## oz"));
5192        ensure!(fixed2_field.digits == 3);
5193        ensure!(fixed2_field.justification == PanJustification::Right);
5194
5195        Ok(())
5196    }
5197
5198    #[crate::ctb_test]
5199    fn test_parse_macros_payload() -> anyhow::Result<()> {
5200        // Build sample MACROS payload with one macro
5201        let mut payload = Vec::new();
5202        // Macro 1: size=31, marker=0x84, name_len=11, name=".Initialize"
5203        payload.extend_from_slice(&31u32.to_le_bytes());
5204        payload.push(0x84);
5205        payload.push(11);
5206        payload.extend_from_slice(b".Initialize");
5207        payload.extend_from_slice(&12u16.to_le_bytes());
5208        payload.extend_from_slice(b"global x\rx=1"); // 12 bytes code
5209
5210        let macros = parse_macros_payload(&payload);
5211        ensure!(macros.len() == 1);
5212        ensure!(macros[0].name == ".Initialize");
5213        ensure!(macros[0].size == 31);
5214        ensure!(!macros[0].payload.is_empty());
5215        ensure!(macros[0].code.as_deref() == Some("global x\nx=1\n"));
5216
5217        Ok(())
5218    }
5219
5220    #[crate::ctb_test]
5221    fn test_parse_picture_and_choices_field_types() -> anyhow::Result<()> {
5222        let types = parse_types_payload(&[0x00, 0x01, 0x02, 0x04, 0x06], 5)?;
5223        ensure!(map_type_code(types[0]) == PanFieldType::Text);
5224        ensure!(map_type_code(types[1]) == PanFieldType::Picture);
5225        ensure!(map_type_code(types[2]) == PanFieldType::Choices);
5226        ensure!(map_type_code(types[3]) == PanFieldType::Date);
5227        ensure!(map_type_code(types[4]) == PanFieldType::Integer);
5228
5229        ensure!(type_code_label(1) == "Picture");
5230        ensure!(type_code_label(2) == "Choices");
5231
5232        Ok(())
5233    }
5234
5235    #[crate::ctb_test]
5236    fn test_serde_pan_bytes_roundtrip() -> anyhow::Result<()> {
5237        let original_bytes =
5238            vec![0x00, 0x00, 0x06, 0x84, b'.', b'I', b'n', b'i', b't'];
5239        let section = PanSection {
5240            offset: 10,
5241            declared_size: 20,
5242            kind: 1,
5243            name_raw: b"MACROS".to_vec(),
5244            name: "MACROS".to_string(),
5245            payload: original_bytes.clone(),
5246        };
5247
5248        let json = serde_json::to_string(&section)?;
5249        ensure!(json.contains("\".Init\"") || json.contains(".Init"));
5250
5251        let deserialized: PanSection = serde_json::from_str(&json)?;
5252        ensure!(deserialized.payload == original_bytes);
5253
5254        Ok(())
5255    }
5256
5257    #[crate::ctb_test]
5258    fn test_detect_data_obfuscation_params() -> anyhow::Result<()> {
5259        let plain_payload = vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06];
5260        ensure!(detect_data_obfuscation_params(&plain_payload).is_none());
5261
5262        // Step 0x0e, subtractive
5263        ensure!(
5264            detect_data_obfuscation_params(&[
5265                0x50, 0x46, 0xa0, 0x2b, 0x18, 0x0a, 0x03, 0xef, 0x66, 0x7d
5266            ]) == Some(PanDataObfuscation::Sub {
5267                key_start: 0x50,
5268                step: 0x0e,
5269            })
5270        );
5271
5272        // Step 0x64, additive
5273        ensure!(
5274            detect_data_obfuscation_params(&[
5275                0x42, 0xa6, 0x0a, 0x6e, 0xd2, 0x36, 0x8e, 0xfe, 0x62, 0xc7
5276            ]) == Some(PanDataObfuscation::Add {
5277                key_start: 0x42,
5278                step: 0x64,
5279            })
5280        );
5281
5282        // Step 0x26, additive
5283        ensure!(
5284            detect_data_obfuscation_params(&[
5285                0x52, 0x78, 0x9e, 0xc4, 0xea, 0x10, 0x29, 0x5c, 0x82, 0xa8
5286            ]) == Some(PanDataObfuscation::Add {
5287                key_start: 0x52,
5288                step: 0x26,
5289            })
5290        );
5291
5292        // Step 0x12, additive
5293        ensure!(
5294            detect_data_obfuscation_params(&[
5295                0x5e, 0x70, 0x82, 0x94, 0xa6, 0xb8, 0xc0, 0xdc, 0xee, 0x00
5296            ]) == Some(PanDataObfuscation::Add {
5297                key_start: 0x5e,
5298                step: 0x12,
5299            })
5300        );
5301
5302        // Step 0x0e, additive
5303        ensure!(
5304            detect_data_obfuscation_params(&[
5305                0x40, 0x4e, 0x5c, 0x6a, 0x78, 0x86, 0x92, 0xa2, 0xb0, 0xbe
5306            ]) == Some(PanDataObfuscation::Add {
5307                key_start: 0x40,
5308                step: 0x0e,
5309            })
5310        );
5311
5312        Ok(())
5313    }
5314
5315    #[crate::ctb_test]
5316    fn test_deobfuscate_macro_payload() -> anyhow::Result<()> {
5317        let name = b".Test";
5318        let mut macro_bytes = Vec::new();
5319        macro_bytes.extend_from_slice(&24u32.to_be_bytes());
5320        macro_bytes.push(0x84);
5321        macro_bytes.push(u8::try_from(name.len())?);
5322        macro_bytes.extend_from_slice(name);
5323        // Prefix before bytecode
5324        macro_bytes.extend_from_slice(&[0x07, 0x63]);
5325        // Obfuscated header [0xf9, 0xe5, 0x0c, 0x0f, 0x12, 0x15]
5326        macro_bytes.extend_from_slice(&[0xf9, 0xe5, 0x0c, 0x0f, 0x12, 0x15]);
5327
5328        let deobfuscated = deobfuscate_macro_payload(&macro_bytes, name.len());
5329        let header_len = 6usize.saturating_add(name.len()).saturating_add(2);
5330        ensure!(
5331            &deobfuscated[header_len..header_len.saturating_add(6)]
5332                == &[0xff, 0xec, 0x00, 0x00, 0x00, 0x00]
5333        );
5334
5335        Ok(())
5336    }
5337}