acadrust 0.3.3

A pure Rust library for reading and writing CAD files in DXF format (ASCII and Binary) and DWG format (Binary).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
//! SAB (ACIS Binary) format converter.
//!
//! Converts between SAT text format (used pre-AC1027) and SAB binary format
//! (used in AC1027 / R2013 and later). The SAB format stores the same ACIS
//! topology/geometry data but uses binary tags instead of text tokens.
//!
//! # SAB Tag Bytes
//!
//! | Tag  | Meaning           | Data               |
//! |------|-------------------|---------------------|
//! | 0x04 | Integer value     | 4 bytes LE i32      |
//! | 0x06 | Double value      | 8 bytes LE f64      |
//! | 0x07 | String literal    | 1-byte len + bytes  |
//! | 0x0A | False / Reversed  | (no data)           |
//! | 0x0B | True / Forward    | (no data)           |
//! | 0x0C | Entity pointer    | 4 bytes LE i32      |
//! | 0x0D | Entity type name  | 1-byte len + bytes  |
//! | 0x0E | Subtype prefix    | 1-byte len + bytes  |
//! | 0x11 | End of record     | (no data)           |
//! | 0x13 | Position (x,y,z)  | 24 bytes (3×f64 LE) |
//! | 0x14 | Direction (x,y,z) | 24 bytes (3×f64 LE) |

use super::types::*;

/// SAB binary tag constants.
pub mod tags {
    /// Integer value (plain int, not entity pointer).
    pub const INTEGER: u8 = 0x04;
    /// Double-precision float.
    pub const DOUBLE: u8 = 0x06;
    /// String literal with length prefix.
    pub const STRING: u8 = 0x07;
    /// Boolean false / reversed / double-sided.
    pub const FALSE: u8 = 0x0A;
    /// Boolean true / forward / single-sided.
    pub const TRUE: u8 = 0x0B;
    /// Entity pointer reference (like `$n` in SAT).
    pub const POINTER: u8 = 0x0C;
    /// Entity type name.
    pub const ENTITY_TYPE: u8 = 0x0D;
    /// Subtype prefix (for compound types like `plane-surface`).
    pub const SUBTYPE: u8 = 0x0E;
    /// End of record marker.
    pub const END_OF_RECORD: u8 = 0x11;
    /// Position (3 doubles: x, y, z).
    pub const POSITION: u8 = 0x13;
    /// Direction (3 doubles: x, y, z).
    pub const DIRECTION: u8 = 0x14;
}

/// SAB header magic string.
const SAB_MAGIC: &[u8] = b"ACIS BinaryFile";

// ============================================================================
// SAT → SAB Writer
// ============================================================================

/// Converts a [`SatDocument`] to SAB binary format.
pub struct SabWriter;

impl SabWriter {
    /// Convert a SAT document to SAB binary data.
    pub fn write(doc: &SatDocument) -> Vec<u8> {
        let mut buf = Vec::with_capacity(8192);

        // Header
        Self::write_header(&mut buf, &doc.header);

        // Entity records
        for record in &doc.records {
            Self::write_record(&mut buf, record);
        }

        // End marker: entity type "End-of-ACIS-data" with no end-of-record tag
        Self::write_entity_type(&mut buf, "End-of-ACIS-data");

        buf
    }

    fn write_header(buf: &mut Vec<u8>, header: &SatHeader) {
        // Magic
        buf.extend_from_slice(SAB_MAGIC);

        // Version number (4 bytes LE)
        let ver = header.version.sat_version_number();
        buf.extend_from_slice(&ver.to_le_bytes());

        // num_records field (4 bytes LE) — always 0 for ACIS 7.0+
        let num_records: u32 = if header.version.has_explicit_indices() {
            0
        } else {
            header.num_records as u32
        };
        buf.extend_from_slice(&num_records.to_le_bytes());

        // num_bodies (4 bytes LE)
        buf.extend_from_slice(&(header.num_bodies as u32).to_le_bytes());

        // has_history (4 bytes LE)
        let history: u32 = if header.has_history { 1 } else { 0 };
        buf.extend_from_slice(&history.to_le_bytes());

        // Product info strings
        Self::write_string(buf, &header.product_id);
        Self::write_string(buf, &header.product_version);
        Self::write_string(buf, &header.date);

        // Tolerances
        Self::write_double(buf, header.spatial_resolution);
        Self::write_double(buf, header.normal_tolerance);
        if let Some(resfit) = header.resfit_tolerance {
            Self::write_double(buf, resfit);
        }
    }

    fn write_record(buf: &mut Vec<u8>, record: &SatRecord) {
        // Entity type — may be compound with multiple hyphens.
        // In SAB, each level of the class hierarchy is a separate tag:
        //   "plane-surface"               → 0x0E("plane") + 0x0D("surface")
        //   "fmesh-eye-attrib"            → 0x0E("fmesh") + 0x0E("eye") + 0x0D("attrib")
        //   "persubent-acadSolidHistory-attrib" → 0x0E("persubent") + 0x0E("acadSolidHistory") + 0x0D("attrib")
        // The last segment is always the base type (0x0D ENTITY_TYPE);
        // all preceding segments are subtype prefixes (0x0E SUBTYPE).
        if record.entity_type.contains('-') {
            let parts: Vec<&str> = record.entity_type.split('-').collect();
            // All parts except the last are subtypes
            for &part in &parts[..parts.len() - 1] {
                Self::write_subtype(buf, part);
            }
            // Last part is the base entity type
            Self::write_entity_type(buf, parts[parts.len() - 1]);
        } else {
            Self::write_entity_type(buf, &record.entity_type);
        }

        // Attribute pointer
        Self::write_pointer(buf, record.attribute.0);

        // Subtype ID (plain integer, not pointer)
        Self::write_integer(buf, record.subtype_id);

        // Remaining tokens — with entity-type-aware coordinate grouping.
        // In SAT text, coordinates are individual Float tokens, but SAB uses
        // composite position(0x13)/direction(0x14) tags for coordinate triplets.
        let layout = CoordLayout::for_entity(&record.entity_type);
        let ints_as_doubles = Self::integers_are_doubles(&record.entity_type);
        Self::write_tokens_with_coord_grouping(buf, &record.tokens, &layout, ints_as_doubles);

        // End of record
        buf.push(tags::END_OF_RECORD);
    }

    /// Write tokens with coordinate grouping based on entity type layout.
    ///
    /// For geometric entities (surfaces, curves, points), consecutive Float
    /// tokens that represent coordinates are grouped into Position/Direction
    /// composite tags. The layout describes the exact sequence of triplets
    /// and scalars for each entity type.
    fn write_tokens_with_coord_grouping(
        buf: &mut Vec<u8>,
        tokens: &[SatToken],
        layout: &CoordLayout,
        ints_as_doubles: bool,
    ) {
        let mut i = 0;
        let mut step_index = 0; // tracks position in layout.steps

        // Skip the first Pointer token (v700 unknown/$-1) to count geometry tokens
        let geom_start = tokens.iter().position(|t| Self::is_numeric(t));

        while i < tokens.len() {
            // Are we in the geometry section of the token stream?
            let in_geom = geom_start.map(|gs| i >= gs).unwrap_or(false);

            if in_geom && step_index < layout.steps.len() {
                match layout.steps[step_index] {
                    Some(tag) => {
                        // This step expects a coordinate triplet (3 floats → Position/Direction)
                        if i + 2 < tokens.len()
                            && Self::is_numeric(&tokens[i])
                            && Self::is_numeric(&tokens[i + 1])
                            && Self::is_numeric(&tokens[i + 2])
                        {
                            let x = Self::numeric_value(&tokens[i]);
                            let y = Self::numeric_value(&tokens[i + 1]);
                            let z = Self::numeric_value(&tokens[i + 2]);

                            buf.push(tag);
                            buf.extend_from_slice(&x.to_le_bytes());
                            buf.extend_from_slice(&y.to_le_bytes());
                            buf.extend_from_slice(&z.to_le_bytes());

                            i += 3;
                            step_index += 1;
                        } else {
                            // Not enough numeric tokens for a triplet — write individually
                            Self::write_token(buf, &tokens[i], ints_as_doubles);
                            i += 1;
                        }
                    }
                    None => {
                        // This step expects a scalar double (single float value)
                        Self::write_token(buf, &tokens[i], ints_as_doubles);
                        i += 1;
                        step_index += 1;
                    }
                }
            } else {
                Self::write_token(buf, &tokens[i], ints_as_doubles);
                i += 1;
            }
        }
    }

    /// Check if a token is a numeric value (Float or Integer).
    fn is_numeric(token: &SatToken) -> bool {
        matches!(token, SatToken::Float(_) | SatToken::Integer(_) | SatToken::Position(_, _, _))
    }

    /// Extract numeric value from a Float or Integer token.
    fn numeric_value(token: &SatToken) -> f64 {
        match token {
            SatToken::Float(v) => *v,
            SatToken::Integer(v) => *v as f64,
            _ => 0.0,
        }
    }

    fn write_token(buf: &mut Vec<u8>, token: &SatToken, ints_as_doubles: bool) {
        match token {
            SatToken::Pointer(p) => Self::write_pointer(buf, p.0),
            // For geometric entities (edge, surface, curve, point), integer-looking
            // values in SAT are actually doubles (e.g., edge start/end parameters,
            // cone ratio). For attribute entities (eye_refinement, vertex_template,
            // *-attrib), integer values are real integers.
            SatToken::Integer(v) => {
                if ints_as_doubles {
                    Self::write_double(buf, *v as f64);
                } else {
                    Self::write_integer(buf, *v as i32);
                }
            }
            SatToken::Float(v) => Self::write_double(buf, *v),
            // String tokens from @-counted SAT format may be boolean keywords
            // (e.g., @9 reverse_v, @9 forward_v). Map them to TRUE/FALSE tags.
            SatToken::String(s) => {
                if let Some(val) = Self::string_to_boolean(s) {
                    buf.push(if val { tags::TRUE } else { tags::FALSE });
                } else {
                    Self::write_string(buf, s);
                }
            }
            SatToken::Position(x, y, z) => Self::write_position(buf, *x, *y, *z),
            SatToken::True => buf.push(tags::TRUE),
            SatToken::False => buf.push(tags::FALSE),
            SatToken::Terminator => buf.push(tags::END_OF_RECORD),
            SatToken::Ident(s) => Self::write_ident_token(buf, s),
            SatToken::Enum(s) => Self::write_enum_token(buf, s),
        }
    }

    /// Check if a string value is a known ACIS boolean keyword.
    /// Returns `Some(true)` for forward/positive, `Some(false)` for reversed/negative.
    fn string_to_boolean(s: &str) -> Option<bool> {
        match s {
            "forward_v" | "I" | "forward" | "single" | "in" => Some(true),
            "reverse_v" | "reversed_v" | "reversed" | "double" | "out" | "F" => Some(false),
            _ => None,
        }
    }

    fn write_ident_token(buf: &mut Vec<u8>, ident: &str) {
        // Map known boolean identifiers to True/False tags
        if let Some(val) = Self::string_to_boolean(ident) {
            buf.push(if val { tags::TRUE } else { tags::FALSE });
        } else {
            Self::write_string(buf, ident);
        }
    }

    fn write_enum_token(buf: &mut Vec<u8>, name: &str) {
        match name {
            "forward" | "single" | "in" => buf.push(tags::TRUE),
            "reversed" | "double" | "out" => buf.push(tags::FALSE),
            // "unknown" and other enum values → string
            _ => Self::write_string(buf, name),
        }
    }

    fn write_entity_type(buf: &mut Vec<u8>, name: &str) {
        buf.push(tags::ENTITY_TYPE);
        buf.push(name.len() as u8);
        buf.extend_from_slice(name.as_bytes());
    }

    /// Determine whether integer body tokens should be written as doubles.
    ///
    /// Geometric entities (surfaces, curves, edges, points) have numeric
    /// parameters that appear as integers in SAT text (e.g., `1`, `0`) but
    /// are actually double-precision values in SAB. Attribute and utility
    /// entities have true integer fields that must stay as INTEGER tags.
    fn integers_are_doubles(entity_type: &str) -> bool {
        let base = if let Some(pos) = entity_type.rfind('-') {
            &entity_type[pos + 1..]
        } else {
            entity_type
        };
        matches!(base, "surface" | "curve" | "edge" | "pcurve" | "point")
    }

    fn write_subtype(buf: &mut Vec<u8>, name: &str) {
        buf.push(tags::SUBTYPE);
        buf.push(name.len() as u8);
        buf.extend_from_slice(name.as_bytes());
    }

    fn write_pointer(buf: &mut Vec<u8>, value: i32) {
        buf.push(tags::POINTER);
        buf.extend_from_slice(&value.to_le_bytes());
    }

    fn write_integer(buf: &mut Vec<u8>, value: i32) {
        buf.push(tags::INTEGER);
        buf.extend_from_slice(&value.to_le_bytes());
    }

    fn write_double(buf: &mut Vec<u8>, value: f64) {
        buf.push(tags::DOUBLE);
        buf.extend_from_slice(&value.to_le_bytes());
    }

    fn write_string(buf: &mut Vec<u8>, s: &str) {
        buf.push(tags::STRING);
        buf.push(s.len() as u8);
        buf.extend_from_slice(s.as_bytes());
    }

    fn write_position(buf: &mut Vec<u8>, x: f64, y: f64, z: f64) {
        buf.push(tags::POSITION);
        buf.extend_from_slice(&x.to_le_bytes());
        buf.extend_from_slice(&y.to_le_bytes());
        buf.extend_from_slice(&z.to_le_bytes());
    }

    #[allow(dead_code)]
    fn write_direction(buf: &mut Vec<u8>, x: f64, y: f64, z: f64) {
        buf.push(tags::DIRECTION);
        buf.extend_from_slice(&x.to_le_bytes());
        buf.extend_from_slice(&y.to_le_bytes());
        buf.extend_from_slice(&z.to_le_bytes());
    }
}

// ============================================================================
// Coordinate layout for entity-type-aware SAB encoding
// ============================================================================

/// Describes the layout of coordinate triplets and scalars in a geometry record.
///
/// In SAT text, positions and directions are both written as three individual floats.
/// In SAB binary, positions use tag `0x13` and directions use tag `0x14`, each
/// encoding three f64 values as a single composite token.
///
/// Some entities (like `sphere-surface` and `torus-surface`) have scalar float
/// values interleaved between coordinate triplets. The layout must describe
/// the exact sequence to group correctly.
struct CoordLayout {
    /// Sequence of geometry tokens after the initial v700 $-1 pointer.
    ///
    /// - `Some(tag)` = group next 3 floats as a composite Position/Direction.
    /// - `None` = write next float as an individual DOUBLE scalar.
    steps: &'static [Option<u8>],
}

impl CoordLayout {
    const EMPTY: Self = Self { steps: &[] };

    /// Position only (e.g., `point`)
    const POS: Self = Self {
        steps: &[Some(tags::POSITION)],
    };

    /// Position + direction (e.g., `straight-curve`)
    const POS_DIR: Self = Self {
        steps: &[Some(tags::POSITION), Some(tags::DIRECTION)],
    };

    /// Position + direction + direction (e.g., `plane-surface`)
    const POS_DIR_DIR: Self = Self {
        steps: &[Some(tags::POSITION), Some(tags::DIRECTION), Some(tags::DIRECTION)],
    };

    /// Position + direction + position (e.g., future entity types where
    /// the 3rd triplet's magnitude carries meaning).
    #[allow(dead_code)]
    const POS_DIR_POS: Self = Self {
        steps: &[Some(tags::POSITION), Some(tags::DIRECTION), Some(tags::POSITION)],
    };

    /// Position + scalar + direction + direction (e.g., `sphere-surface`)
    ///
    /// sphere-surface: center(pos) radius(scalar) u_dir(dir) pole(dir)
    const POS_S_DIR_DIR: Self = Self {
        steps: &[
            Some(tags::POSITION),
            None, // radius (scalar double)
            Some(tags::DIRECTION),
            Some(tags::DIRECTION),
        ],
    };

    /// Position + direction + scalar + scalar + direction (e.g., `torus-surface`)
    ///
    /// torus-surface: center(pos) normal(dir) major_r(scalar) minor_r(scalar) u_dir(dir)
    const POS_DIR_SS_DIR: Self = Self {
        steps: &[
            Some(tags::POSITION),
            Some(tags::DIRECTION),
            None, // major_radius (scalar)
            None, // minor_radius (scalar)
            Some(tags::DIRECTION),
        ],
    };

    /// Determine the coordinate layout for a given entity type.
    fn for_entity(entity_type: &str) -> Self {
        match entity_type {
            "point" => Self::POS,
            "straight-curve" => Self::POS_DIR,
            "plane-surface" => Self::POS_DIR_DIR,
            "cone-surface" => Self::POS_DIR_DIR,
            "sphere-surface" => Self::POS_S_DIR_DIR,
            "torus-surface" => Self::POS_DIR_SS_DIR,
            "ellipse-curve" => Self::POS_DIR_DIR,
            "intcurve-curve" | "spline-surface" => Self::POS_DIR_DIR,
            _ => Self::EMPTY,
        }
    }
}

// ============================================================================
// SAB → SAT Reader
// ============================================================================

/// Error type for SAB parsing.
#[derive(Debug)]
pub enum SabError {
    /// Unexpected end of data.
    UnexpectedEof,
    /// Invalid magic header.
    InvalidMagic,
    /// Unknown tag byte.
    UnknownTag(u8, usize),
    /// Invalid string encoding.
    InvalidString,
}

impl std::fmt::Display for SabError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SabError::UnexpectedEof => write!(f, "Unexpected end of SAB data"),
            SabError::InvalidMagic => write!(f, "Invalid SAB magic header"),
            SabError::UnknownTag(tag, pos) => {
                write!(f, "Unknown SAB tag 0x{:02X} at position {}", tag, pos)
            }
            SabError::InvalidString => write!(f, "Invalid UTF-8 string in SAB data"),
        }
    }
}

impl std::error::Error for SabError {}

/// Reads SAB binary data and produces a [`SatDocument`].
pub struct SabReader;

impl SabReader {
    /// Parse SAB binary data into a SAT document.
    pub fn read(data: &[u8]) -> Result<SatDocument, SabError> {
        if data.len() < SAB_MAGIC.len() {
            return Err(SabError::InvalidMagic);
        }
        if &data[..SAB_MAGIC.len()] != SAB_MAGIC {
            return Err(SabError::InvalidMagic);
        }

        let mut pos = SAB_MAGIC.len();

        // Header ints (4 × u32 LE)
        let version_num = read_u32(data, &mut pos)?;
        let num_records = read_u32(data, &mut pos)? as usize;
        let num_bodies = read_u32(data, &mut pos)? as usize;
        let has_history = read_u32(data, &mut pos)? != 0;

        let version = SatVersion::from_sat_number(version_num);

        // Header strings (3 tagged strings)
        let product_id = read_tagged_string(data, &mut pos)?;
        let product_version = read_tagged_string(data, &mut pos)?;
        let date = read_tagged_string(data, &mut pos)?;

        // Tolerances (2 or 3 tagged doubles)
        let spatial_resolution = read_tagged_double(data, &mut pos)?;
        let normal_tolerance = read_tagged_double(data, &mut pos)?;

        // Third tolerance only for ACIS 7.0+
        let resfit_tolerance = if version.major >= 7 {
            Some(read_tagged_double(data, &mut pos)?)
        } else {
            None
        };

        let header = SatHeader {
            version,
            num_records,
            num_bodies,
            has_history,
            product_id,
            product_version,
            date,
            spatial_resolution,
            normal_tolerance,
            resfit_tolerance,
        };

        // Parse entity records
        let mut records = Vec::new();
        let mut record_index: i32 = 0;

        while pos < data.len() {
            let tag = data[pos];
            if tag == tags::ENTITY_TYPE || tag == tags::SUBTYPE {
                let (record, new_pos) = Self::read_record(data, pos, record_index)?;

                // Check for End-of-ACIS-data marker
                if record.entity_type == "End-of-ACIS-data" {
                    break;
                }

                pos = new_pos;
                records.push(record);
                record_index += 1;
            } else {
                return Err(SabError::UnknownTag(tag, pos));
            }
        }

        Ok(SatDocument {
            header,
            records,
        })
    }

    fn read_record(
        data: &[u8],
        mut pos: usize,
        index: i32,
    ) -> Result<(SatRecord, usize), SabError> {
        // Read entity type — may have multiple subtype prefixes.
        // In SAB, compound types like "fmesh-eye-attrib" are encoded as:
        //   0x0E("fmesh") + 0x0E("eye") + 0x0D("attrib")
        // We collect all 0x0E subtypes, then read the final 0x0D base type,
        // and join them with hyphens to reconstruct the SAT entity type name.
        let mut subtype_parts: Vec<String> = Vec::new();
        let entity_type;

        // Collect all subtype prefixes (0x0E)
        while pos < data.len() && data[pos] == tags::SUBTYPE {
            pos += 1;
            let (sub, new_pos) = read_length_string(data, pos)?;
            subtype_parts.push(sub);
            pos = new_pos;
        }

        // Read the base entity type (0x0D)
        if pos >= data.len() || data[pos] != tags::ENTITY_TYPE {
            return Err(SabError::UnknownTag(
                if pos < data.len() { data[pos] } else { 0 },
                pos,
            ));
        }
        pos += 1;
        let (base_type, new_pos) = read_length_string(data, pos)?;
        pos = new_pos;

        // Reconstruct compound name: subtypes joined with hyphens + base type
        if subtype_parts.is_empty() {
            entity_type = base_type;
        } else {
            subtype_parts.push(base_type);
            entity_type = subtype_parts.join("-");
        }

        let subtype_name = if entity_type.contains('-') {
            Some(entity_type.split('-').next().unwrap().to_string())
        } else {
            None
        };

        // Check for End-of-ACIS-data (no record body)
        if entity_type == "End-of-ACIS-data" {
            return Ok((
                SatRecord {
                    index,
                    entity_type,
                    sub_type: subtype_name,
                    attribute: SatPointer::NULL,
                    subtype_id: -1,
                    tokens: Vec::new(),
                    raw_text: None,
                },
                pos,
            ));
        }

        // Attribute pointer
        let attribute = if pos < data.len() && data[pos] == tags::POINTER {
            pos += 1;
            let val = read_i32(data, &mut pos)?;
            SatPointer::new(val)
        } else {
            SatPointer::NULL
        };

        // Subtype ID (plain integer)
        let subtype_id = if pos < data.len() && data[pos] == tags::INTEGER {
            pos += 1;
            read_i32(data, &mut pos)?
        } else {
            -1
        };

        // Remaining tokens until END_OF_RECORD
        let mut tokens = Vec::new();
        while pos < data.len() {
            let tag = data[pos];
            if tag == tags::END_OF_RECORD {
                pos += 1;
                break;
            }
            let (token, new_pos) = Self::read_token(data, pos)?;
            tokens.push(token);
            pos = new_pos;
        }

        Ok((
            SatRecord {
                index,
                entity_type,
                sub_type: subtype_name,
                attribute,
                subtype_id,
                tokens,
                raw_text: None,
            },
            pos,
        ))
    }

    fn read_token(data: &[u8], pos: usize) -> Result<(SatToken, usize), SabError> {
        if pos >= data.len() {
            return Err(SabError::UnexpectedEof);
        }

        let tag = data[pos];
        let mut pos = pos + 1;

        match tag {
            tags::POINTER => {
                let val = read_i32(data, &mut pos)?;
                Ok((SatToken::Pointer(SatPointer::new(val)), pos))
            }
            tags::INTEGER => {
                let val = read_i32(data, &mut pos)?;
                Ok((SatToken::Integer(val as i64), pos))
            }
            tags::DOUBLE => {
                let val = read_f64(data, &mut pos)?;
                Ok((SatToken::Float(val), pos))
            }
            tags::STRING => {
                let (s, new_pos) = read_length_string(data, pos)?;
                Ok((SatToken::String(s), new_pos))
            }
            tags::TRUE => Ok((SatToken::True, pos)),
            tags::FALSE => Ok((SatToken::False, pos)),
            tags::POSITION => {
                let x = read_f64(data, &mut pos)?;
                let y = read_f64(data, &mut pos)?;
                let z = read_f64(data, &mut pos)?;
                Ok((SatToken::Position(x, y, z), pos))
            }
            tags::DIRECTION => {
                // Direction is treated the same as position in our SatToken model;
                // the semantic distinction is determined by position in the record.
                let x = read_f64(data, &mut pos)?;
                let y = read_f64(data, &mut pos)?;
                let z = read_f64(data, &mut pos)?;
                Ok((SatToken::Position(x, y, z), pos))
            }
            tags::END_OF_RECORD => Ok((SatToken::Terminator, pos)),
            _ => Err(SabError::UnknownTag(tag, pos - 1)),
        }
    }
}

// ============================================================================
// Binary reading helpers
// ============================================================================

fn read_u32(data: &[u8], pos: &mut usize) -> Result<u32, SabError> {
    if *pos + 4 > data.len() {
        return Err(SabError::UnexpectedEof);
    }
    let val = u32::from_le_bytes([data[*pos], data[*pos + 1], data[*pos + 2], data[*pos + 3]]);
    *pos += 4;
    Ok(val)
}

fn read_i32(data: &[u8], pos: &mut usize) -> Result<i32, SabError> {
    if *pos + 4 > data.len() {
        return Err(SabError::UnexpectedEof);
    }
    let val = i32::from_le_bytes([data[*pos], data[*pos + 1], data[*pos + 2], data[*pos + 3]]);
    *pos += 4;
    Ok(val)
}

fn read_f64(data: &[u8], pos: &mut usize) -> Result<f64, SabError> {
    if *pos + 8 > data.len() {
        return Err(SabError::UnexpectedEof);
    }
    let val = f64::from_le_bytes([
        data[*pos],
        data[*pos + 1],
        data[*pos + 2],
        data[*pos + 3],
        data[*pos + 4],
        data[*pos + 5],
        data[*pos + 6],
        data[*pos + 7],
    ]);
    *pos += 8;
    Ok(val)
}

fn read_length_string(data: &[u8], pos: usize) -> Result<(String, usize), SabError> {
    if pos >= data.len() {
        return Err(SabError::UnexpectedEof);
    }
    let len = data[pos] as usize;
    let start = pos + 1;
    if start + len > data.len() {
        return Err(SabError::UnexpectedEof);
    }
    let s = std::str::from_utf8(&data[start..start + len])
        .map_err(|_| SabError::InvalidString)?
        .to_string();
    Ok((s, start + len))
}

fn read_tagged_string(data: &[u8], pos: &mut usize) -> Result<String, SabError> {
    if *pos >= data.len() || data[*pos] != tags::STRING {
        return Err(SabError::UnknownTag(
            if *pos < data.len() { data[*pos] } else { 0 },
            *pos,
        ));
    }
    *pos += 1;
    let (s, new_pos) = read_length_string(data, *pos)?;
    *pos = new_pos;
    Ok(s)
}

fn read_tagged_double(data: &[u8], pos: &mut usize) -> Result<f64, SabError> {
    if *pos >= data.len() || data[*pos] != tags::DOUBLE {
        return Err(SabError::UnknownTag(
            if *pos < data.len() { data[*pos] } else { 0 },
            *pos,
        ));
    }
    *pos += 1;
    read_f64(data, pos)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sat_to_sab_header() {
        let mut doc = SatDocument::new();
        doc.header.product_id = "TestApp".to_string();
        doc.header.product_version = "ACIS 7.0".to_string();
        doc.header.date = "Thu Jan 01 00:00:00 2023".to_string();
        doc.header.spatial_resolution = 10.0;
        doc.header.normal_tolerance = 1e-06;
        doc.header.resfit_tolerance = Some(1e-10);

        let sab = SabWriter::write(&doc);

        // Check magic
        assert_eq!(&sab[..15], b"ACIS BinaryFile");
        // Check version
        let ver = u32::from_le_bytes([sab[15], sab[16], sab[17], sab[18]]);
        assert_eq!(ver, 700);
        // Check End-of-ACIS-data is present
        let end_str = b"End-of-ACIS-data";
        assert!(sab.windows(end_str.len()).any(|w| w == end_str));
    }

    #[test]
    fn test_sat_to_sab_roundtrip() {
        let sat_text = "700 0 1 0\n\
            @8 acadrust @8 ACIS 7.0 @24 Thu Jan 01 00:00:00 2023\n\
            10 9.9999999999999995e-007 1e-010\n\
            body $-1 -1 $-1 $1 $-1 $-1 #\n\
            lump $-1 -1 $-1 $-1 $2 $0 #\n\
            shell $-1 -1 $-1 $-1 $-1 $3 $-1 $1 #\n\
            face $-1 -1 $-1 $-1 $-1 $2 $-1 $4 forward single #\n\
            plane-surface $-1 -1 $-1 0 0 5 0 0 1 1 0 0 forward_v I I I I #\n\
            End-of-ACIS-data\n";

        let doc = SatDocument::parse(sat_text).unwrap();
        let sab = SabWriter::write(&doc);
        let roundtrip = SabReader::read(&sab).unwrap();

        assert_eq!(roundtrip.header.version, doc.header.version);
        assert_eq!(roundtrip.records.len(), doc.records.len());
        assert_eq!(roundtrip.records[0].entity_type, "body");
        assert_eq!(roundtrip.records[3].entity_type, "face");
        assert_eq!(roundtrip.records[4].entity_type, "plane-surface");
    }

    #[test]
    fn test_compound_entity_types() {
        let sat_text = "700 0 1 0\n\
            @8 acadrust @8 ACIS 7.0 @24 Thu Jan 01 00:00:00 2023\n\
            10 9.9999999999999995e-007 1e-010\n\
            plane-surface $-1 -1 $-1 0 0 5 0 0 1 1 0 0 forward_v I I I I #\n\
            straight-curve $-1 -1 $-1 0 0 0 1 0 0 I I #\n\
            End-of-ACIS-data\n";

        let doc = SatDocument::parse(sat_text).unwrap();
        let sab = SabWriter::write(&doc);

        // Verify subtype tags are present
        assert!(sab.contains(&tags::SUBTYPE));

        // Roundtrip
        let roundtrip = SabReader::read(&sab).unwrap();
        assert_eq!(roundtrip.records[0].entity_type, "plane-surface");
        assert_eq!(roundtrip.records[1].entity_type, "straight-curve");
    }

    #[test]
    fn test_sab_boolean_mapping() {
        let sat_text = "700 0 1 0\n\
            @8 acadrust @8 ACIS 7.0 @24 Thu Jan 01 00:00:00 2023\n\
            10 9.9999999999999995e-007 1e-010\n\
            face $-1 -1 $-1 $-1 $-1 $-1 $-1 $-1 forward single #\n\
            face $-1 -1 $-1 $-1 $-1 $-1 $-1 $-1 reversed double #\n\
            End-of-ACIS-data\n";

        let doc = SatDocument::parse(sat_text).unwrap();
        let sab = SabWriter::write(&doc);
        let roundtrip = SabReader::read(&sab).unwrap();

        // forward/single → True, True
        let face1 = &roundtrip.records[0];
        let last_two: Vec<_> = face1.tokens.iter().rev().take(2).collect();
        assert!(matches!(last_two[0], SatToken::True));
        assert!(matches!(last_two[1], SatToken::True));

        // reversed/double → False, False
        let face2 = &roundtrip.records[1];
        let last_two: Vec<_> = face2.tokens.iter().rev().take(2).collect();
        assert!(matches!(last_two[0], SatToken::False));
        assert!(matches!(last_two[1], SatToken::False));
    }
}