Skip to main content

brep_kernel/io/parasolid/
reader.rs

1//! The text transmit reader: header, token stream, embedded-schema deltas and
2//! the node graph (Parasolid XT Format Reference, chapters 2 and 3).
3//!
4//! A text part is a bytestream cut into ~80-character records; the record
5//! breaks carry no meaning, so the reader joins the records and walks one
6//! string. Numbers are followed by one space; `c` (char) and `l` (logical)
7//! fields are single characters with no separator, and the unset value of
8//! an integer, real or vector is a lone `?` with no separator either.
9
10use std::rc::Rc;
11
12use rustc_hash::FxHashMap as HashMap;
13
14use super::schema::{self, Count, FieldDef, Kind};
15
16/// The field layout of one node type as this file writes it.
17#[derive(Debug)]
18pub struct NodeLayout {
19    pub node_type: u16,
20    pub name: String,
21    pub fields: Vec<FieldDef>,
22}
23
24impl NodeLayout {
25    fn variable(&self) -> bool {
26        self.fields.last().is_some_and(|f| f.count == Count::Variable)
27    }
28
29    fn position(&self, name: &str) -> Option<usize> {
30        self.fields.iter().position(|f| f.name == name)
31    }
32}
33
34/// One field value. Unset values (`?`) are `None`.
35#[derive(Clone, Debug, PartialEq)]
36pub enum Value {
37    Int(Option<i64>),
38    Real(Option<f64>),
39    Vector(Option<[f64; 3]>),
40    Interval([Option<f64>; 2]),
41    Box([Option<f64>; 6]),
42    Char(u8),
43    Array(Vec<Value>),
44    Text(String),
45}
46
47/// A node: its type, index and field values in its layout's order.
48#[derive(Debug)]
49pub struct Node {
50    pub index: u32,
51    pub layout: Rc<NodeLayout>,
52    pub values: Vec<Value>,
53}
54
55impl Node {
56    pub fn node_type(&self) -> u16 {
57        self.layout.node_type
58    }
59
60    pub fn type_name(&self) -> &str {
61        &self.layout.name
62    }
63
64    /// A field by name; `None` when this file's layout has no such field.
65    pub fn field(&self, name: &str) -> Option<&Value> {
66        self.layout.position(name).map(|i| &self.values[i])
67    }
68
69    /// An integer or pointer field; unset and absent read as `None`.
70    pub fn int(&self, name: &str) -> Option<i64> {
71        match self.field(name) {
72            Some(Value::Int(v)) => *v,
73            _ => None,
74        }
75    }
76
77    /// A pointer field's index; null, unset and absent read as 0.
78    pub fn ptr(&self, name: &str) -> u32 {
79        self.int(name).filter(|&v| v > 0).map_or(0, |v| v as u32)
80    }
81
82    pub fn real(&self, name: &str) -> Option<f64> {
83        match self.field(name) {
84            Some(Value::Real(v)) => *v,
85            _ => None,
86        }
87    }
88
89    pub fn vector(&self, name: &str) -> Option<[f64; 3]> {
90        match self.field(name) {
91            Some(Value::Vector(v)) => *v,
92            _ => None,
93        }
94    }
95
96    pub fn interval(&self, name: &str) -> Option<[Option<f64>; 2]> {
97        match self.field(name) {
98            Some(Value::Interval(v)) => Some(*v),
99            _ => None,
100        }
101    }
102
103    pub fn char(&self, name: &str) -> Option<u8> {
104        match self.field(name) {
105            Some(Value::Char(c)) => Some(*c),
106            _ => None,
107        }
108    }
109
110    /// A logical field; `T` is true.
111    pub fn logical(&self, name: &str) -> Option<bool> {
112        self.char(name).map(|c| c == b'T')
113    }
114
115    pub fn text(&self, name: &str) -> Option<&str> {
116        match self.field(name) {
117            Some(Value::Text(s)) => Some(s),
118            _ => None,
119        }
120    }
121
122    pub fn array(&self, name: &str) -> &[Value] {
123        match self.field(name) {
124            Some(Value::Array(v)) => v,
125            _ => &[],
126        }
127    }
128
129    /// An array of reals (unset entries as NaN).
130    pub fn reals(&self, name: &str) -> Vec<f64> {
131        self.array(name)
132            .iter()
133            .map(|v| match v {
134                Value::Real(Some(x)) => *x,
135                _ => f64::NAN,
136            })
137            .collect()
138    }
139
140    /// An array of integers or pointers (unset entries as 0).
141    pub fn ints(&self, name: &str) -> Vec<i64> {
142        self.array(name)
143            .iter()
144            .map(|v| match v {
145                Value::Int(Some(x)) => *x,
146                _ => 0,
147            })
148            .collect()
149    }
150
151    /// An array of vectors (unset entries as `None`).
152    pub fn vectors(&self, name: &str) -> Vec<Option<[f64; 3]>> {
153        self.array(name)
154            .iter()
155            .map(|v| match v {
156                Value::Vector(x) => *x,
157                _ => None,
158            })
159            .collect()
160    }
161}
162
163/// A parsed text transmit file.
164#[derive(Debug)]
165pub struct XtFile {
166    /// `TRANSMIT FILE created by modeller version …`.
167    pub modeller_version: String,
168    /// `SCH_<version>_<schema>[_<base>]`.
169    pub schema: String,
170    /// The header's `KEY=value` pairs (parts 1 to 3).
171    pub header: Vec<(String, String)>,
172    /// A partition (`TRANSMIT FILE (partition)`): its root is the WORLD,
173    /// whose bodies are the partition's.
174    pub partition: bool,
175    nodes: Vec<Node>,
176    by_index: HashMap<u32, usize>,
177}
178
179impl XtFile {
180    /// The root node: the first node in the file (§2.1).
181    pub fn root(&self) -> Option<&Node> {
182        self.nodes.first()
183    }
184
185    pub fn nodes(&self) -> &[Node] {
186        &self.nodes
187    }
188
189    /// The node an index names; 0 and indices with no node are null (§2.1.4.4).
190    pub fn node(&self, index: u32) -> Option<&Node> {
191        if index == 0 {
192            return None;
193        }
194        self.by_index.get(&index).map(|&i| &self.nodes[i])
195    }
196
197    /// The node a pointer field of `node` names.
198    pub fn follow(&self, node: &Node, field: &str) -> Option<&Node> {
199        self.node(node.ptr(field))
200    }
201
202    pub fn header_value(&self, key: &str) -> Option<&str> {
203        self.header.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
204    }
205}
206
207/// Unset integer and real values as written by binary writers; text writes `?`.
208const NULL_INT: i64 = -32764;
209
210/// Read a text transmit file (`.x_t`, `.xmt_txt`).
211pub fn parse_xt_text(text: &str) -> Result<XtFile, String> {
212    let (header, body_start) = split_header(text);
213    if text.as_bytes()[body_start..].starts_with(b"PS") {
214        return Err("this is a binary Parasolid file (.x_b); read its bytes, not its text".into());
215    }
216    let data = join_records(&text[body_start..]);
217    let mut stream = Stream { data: &data, at: 0, encoding: Encoding::Text };
218    stream.skip_blank();
219    match stream.next_byte() {
220        Some(b'T') => {}
221        Some(b'P' | b'B') => {
222            return Err("this is a binary Parasolid file (.x_b); read its bytes, not its text".into())
223        }
224        other => {
225            return Err(format!(
226                "not a Parasolid text transmit file: the part data starts with {:?}, expected 'T'",
227                other.map(char::from)
228            ))
229        }
230    }
231    parse_data(header, stream)
232}
233
234/// Read a transmit file, text or binary, from its bytes: a text part, a
235/// neutral binary (`PS\0\0`, big-endian) or typed binary (`PS\0\1` and the
236/// writer's machine description) part or partition, with or without the
237/// keyword header (§3.1, §3.3). A SolidWorks body is such a partition.
238pub fn parse_xt(bytes: &[u8]) -> Result<XtFile, String> {
239    // The keyword header is text in every format; the data follows the line
240    // that ends it. Only a file that starts with the header's preamble has
241    // one: a headerless binary file may hold that text in its own data.
242    let has_header = bytes.trim_ascii_start().starts_with(b"**ABCDEFGHIJKLMNOPQRSTUVWXYZ");
243    let body_start = match find(bytes, b"**END_OF_HEADER").filter(|_| has_header) {
244        Some(end) => bytes[end..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |n| end + n + 1),
245        None => 0,
246    };
247    let data = &bytes[body_start..];
248    let flag = data.iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(data.len());
249    if !data[flag..].starts_with(b"PS") && !data[flag..].starts_with(b"B") {
250        return parse_xt_text(&String::from_utf8_lossy(bytes));
251    }
252    let (header, _) = split_header(&String::from_utf8_lossy(&bytes[..body_start]));
253    let data = &data[flag..];
254    let (little, at) = match data {
255        [b'P', b'S', 0, 0, ..] => (false, 4),
256        [b'P', b'S', 0, 1, order, double, character, ..] => {
257            if *double != 0 || *character != 0 {
258                return Err(format!(
259                    "this typed binary Parasolid file was written with {} reals and {} characters; only IEEE reals and \
260                     ASCII characters are read",
261                    if *double == 0 { "IEEE" } else { "VAX D-float" },
262                    if *character == 0 { "ASCII" } else { "EBCDIC" }
263                ));
264            }
265            (*order == 1, 7)
266        }
267        [b'P', b'S', ..] => return Err("this binary Parasolid file has an unknown flag sequence after 'PS'".into()),
268        _ => {
269            return Err("this is a bare binary Parasolid file, written in its machine's own format with no \
270                        description of that machine; only neutral and typed binary are read"
271                .into())
272        }
273    };
274    parse_data(header, Stream::binary(&data[at..], little))
275}
276
277fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
278    haystack.windows(needle.len()).position(|w| w == needle)
279}
280
281/// The part data after its flag sequence: the modeller version, the schema,
282/// the user field size, then the nodes to the terminator (§2.1, §3.2, §3.3).
283fn parse_data(header: Vec<(String, String)>, mut stream: Stream) -> Result<XtFile, String> {
284    // Binary writes the modeller version's length in two bytes and the
285    // schema's in four (§3.3).
286    let modeller_version = stream.header_string(2)?;
287    let partition = modeller_version.contains("(partition)");
288    if modeller_version.contains("(deltas)") {
289        return Err("this is a Parasolid partition's deltas (its rollback history), which holds no bodies".into());
290    }
291    let schema_name = stream.header_string(4)?;
292    // `SCH_1400068_14000_13006`: the base suffix marks embedded schema deltas,
293    // followed by the maximum node type (§2.1.2.2).
294    let embedded = schema_name.split('_').count() >= 4;
295    if embedded {
296        let base = schema_name.rsplit('_').next().unwrap_or_default();
297        if base != schema::BASE_SCHEMA {
298            return Err(format!(
299                "the file's schema {schema_name} is relative to base {base}; only base {} is known",
300                schema::BASE_SCHEMA
301            ));
302        }
303        stream.short()?;
304    }
305    // Without embedded deltas the layouts are the named schema's own: the
306    // base's, or a stored schema's.
307    let stored = if embedded {
308        None
309    } else {
310        schema::STORED_SCHEMAS.into_iter().find(|s| schema_name.ends_with(&format!("_{s}")))
311    };
312    if !embedded && stored.is_none() && !schema_name.ends_with(&format!("_{}", schema::BASE_SCHEMA)) {
313        return Err(format!(
314            "the file's schema {schema_name} carries no description of its layout; only files written with schema {} \
315             or {}, or with embedded schema deltas (Parasolid V14 and later), are read",
316            schema::BASE_SCHEMA,
317            schema::STORED_SCHEMAS.join(", ")
318        ));
319    }
320    let user_field_size = stream.long()?.unwrap_or(0).max(0) as usize;
321    let mut layouts: HashMap<u16, Rc<NodeLayout>> = HashMap::default();
322    let mut nodes = Vec::new();
323    let mut by_index = HashMap::default();
324    loop {
325        let at = stream.at;
326        let node_type = stream.short()?.ok_or("a node type is unset")?;
327        if node_type == 1 {
328            // Terminator: type 1, index 0.
329            if stream.index()? == 0 {
330                break;
331            }
332            return Err(format!("node type 1 at byte {at} is not followed by the terminating 0"));
333        }
334        let node_type = u16::try_from(node_type).map_err(|_| format!("node type {node_type} at byte {at} is out of range"))?;
335        let layout = match layouts.get(&node_type) {
336            Some(layout) => layout.clone(),
337            None => {
338                let layout = Rc::new(if embedded {
339                    read_layout(&mut stream, node_type)?
340                } else if let Some(stored) = stored {
341                    stored_layout(stored, node_type)?
342                } else {
343                    base_layout(node_type)?
344                });
345                layouts.insert(node_type, layout.clone());
346                layout
347            }
348        };
349        let node = read_node(&mut stream, layout, user_field_size)
350            .map_err(|e| format!("node type {node_type} at byte {at}: {e}"))?;
351        if by_index.insert(node.index, nodes.len()).is_some() {
352            return Err(format!("node index {} appears twice", node.index));
353        }
354        nodes.push(node);
355    }
356    if nodes.is_empty() {
357        return Err("the file holds no nodes".into());
358    }
359    Ok(XtFile { modeller_version, schema: schema_name, header, partition, nodes, by_index })
360}
361
362fn base_layout(node_type: u16) -> Result<NodeLayout, String> {
363    let (name, fields) = schema::base(node_type)
364        .ok_or_else(|| format!("node type {node_type} is not in the base schema and the file does not describe it"))?;
365    Ok(NodeLayout { node_type, name: name.to_string(), fields })
366}
367
368/// A node type's layout in a stored schema; a type no file in that schema
369/// has shown is refused by name.
370fn stored_layout(stored: &str, node_type: u16) -> Result<NodeLayout, String> {
371    let delta = schema::stored_delta(stored, node_type).ok_or_else(|| {
372        let name = schema::base(node_type).map_or_else(|| format!("node type {node_type}"), |(n, _)| format!("node type {node_type} ({n})"));
373        format!("{name} has no known layout in schema {stored} and the file does not describe it")
374    })?;
375    read_layout(&mut Stream { data: delta.as_bytes(), at: 0, encoding: Encoding::Text }, node_type)
376        .map_err(|e| format!("the stored schema {stored} layout of node type {node_type}: {e}"))
377}
378
379/// A node type's layout from its first occurrence (§2.1.2.2): 255 for "as the
380/// base", a new type's full description, or an edit script against the base.
381fn read_layout(stream: &mut Stream, node_type: u16) -> Result<NodeLayout, String> {
382    // A field count is a byte (§2.1.2.2); 255 means "as the base".
383    let count = stream.byte_int()?.ok_or("a field count is unset")?;
384    if !(0..=255).contains(&count) {
385        return Err(format!("node type {node_type} declares {count} fields"));
386    }
387    let Some((name, base)) = schema::base(node_type) else {
388        // A type the base schema does not have: its whole description.
389        let name = stream.string()?;
390        let _description = stream.string()?;
391        let mut fields = Vec::with_capacity(count.max(0) as usize);
392        for _ in 0..count {
393            fields.push(stream.field_def()?);
394        }
395        return Ok(NodeLayout { node_type, name, fields });
396    };
397    if count == 255 {
398        return Ok(NodeLayout { node_type, name: name.to_string(), fields: base });
399    }
400    let mut fields = Vec::with_capacity(count.max(0) as usize);
401    let mut base_fields = base.into_iter();
402    loop {
403        match stream.next_byte() {
404            Some(b'C') => fields.push(
405                base_fields
406                    .next()
407                    .ok_or_else(|| format!("{name}'s schema copies past the end of the base layout"))?,
408            ),
409            Some(b'D') => {
410                base_fields
411                    .next()
412                    .ok_or_else(|| format!("{name}'s schema deletes past the end of the base layout"))?;
413            }
414            Some(b'I' | b'A') => fields.push(stream.field_def()?),
415            Some(b'Z') => break,
416            other => {
417                return Err(format!(
418                    "{name}'s schema edit has instruction {:?}, expected C, D, I, A or Z",
419                    other.map(char::from)
420                ))
421            }
422        }
423    }
424    if fields.len() as i64 != count {
425        return Err(format!("{name}'s schema edit gives {} fields, its header says {count}", fields.len()));
426    }
427    Ok(NodeLayout { node_type, name: name.to_string(), fields })
428}
429
430/// Node types visible at the PK interface, which carry the user field (§2.1, §6.1).
431fn carries_user_field(node_type: u16) -> bool {
432    matches!(
433        node_type,
434        10..=19 | 29..=32 | 38 | 50..=54 | 56 | 60 | 67 | 68 | 70 | 80 | 81 | 90 | 100 | 120 | 124 | 130 | 133
435            | 134 | 137 | 200 | 201 | 222
436    )
437}
438
439fn read_node(stream: &mut Stream, layout: Rc<NodeLayout>, user_field_size: usize) -> Result<Node, String> {
440    let length = if layout.variable() {
441        let n = stream.long()?.ok_or("a variable length is unset")?;
442        let n = usize::try_from(n).map_err(|_| format!("variable length {n} is negative"))?;
443        // Every element takes at least one byte of the data.
444        if n > stream.remaining() {
445            return Err(format!("variable length {n} runs past the end of the data"));
446        }
447        n
448    } else {
449        0
450    };
451    let index = stream.index()?;
452    let index = u32::try_from(index).ok().filter(|&i| i > 0).ok_or_else(|| format!("node index {index} is invalid"))?;
453    let mut values = Vec::with_capacity(layout.fields.len());
454    for field in &layout.fields {
455        let value = match field.count {
456            Count::Scalar => stream.value(field),
457            Count::Variable if field.code == b'c' => stream.chars(length).map(Value::Text),
458            Count::Variable => (0..length).map(|_| stream.value(field)).collect::<Result<_, _>>().map(Value::Array),
459            Count::Fixed(n) => (0..n).map(|_| stream.value(field)).collect::<Result<_, _>>().map(Value::Array),
460        }
461        .map_err(|e| format!("{} field {}: {e}", layout.name, field.name))?;
462        values.push(value);
463    }
464    if layout.node_type < 1000 && carries_user_field(layout.node_type) {
465        for _ in 0..user_field_size {
466            stream.long()?;
467        }
468    }
469    Ok(Node { index, layout, values })
470}
471
472/// The header's `KEY=value;` pairs and where the part data starts (§3.1). A
473/// file with no header starts with its part data.
474fn split_header(text: &str) -> (Vec<(String, String)>, usize) {
475    let Some(end) = text.find("**END_OF_HEADER") else {
476        return (Vec::new(), 0);
477    };
478    let body_start = text[end..].find('\n').map_or(text.len(), |n| end + n + 1);
479    let mut joined = String::new();
480    for line in text[..end].lines() {
481        let line = line.trim_end_matches('\r');
482        if line.starts_with("**ABCDEFG") || line.starts_with("**PARASOLID") {
483            continue;
484        }
485        joined.push_str(line);
486    }
487    let mut header = Vec::new();
488    for item in joined.split(';') {
489        let item = item.trim_start_matches(|c| c == '*').trim();
490        let item = item.strip_prefix("PART1").or_else(|| item.strip_prefix("PART2")).or_else(|| item.strip_prefix("PART3")).unwrap_or(item);
491        let item = item.trim_start_matches(|c| c == '*' || c == ';');
492        if let Some((key, value)) = item.split_once('=') {
493            header.push((key.trim().to_string(), unescape_header(value)));
494        }
495    }
496    (header, body_start)
497}
498
499/// §3.1.1 keyword escapes.
500fn unescape_header(value: &str) -> String {
501    let mut out = String::with_capacity(value.len());
502    let mut chars = value.chars();
503    while let Some(c) = chars.next() {
504        if c != '^' {
505            out.push(c);
506            continue;
507        }
508        match chars.next() {
509            Some('n') => out.push('\n'),
510            Some('-') => out.push(' '),
511            Some(';') => out.push(';'),
512            Some('^') => out.push('^'),
513            Some(other) => {
514                out.push('^');
515                out.push(other);
516            }
517            None => out.push('^'),
518        }
519    }
520    out
521}
522
523/// §3.2: record breaks, carriage returns and the trailing spaces a system may
524/// add to a record are not part of the data; leading spaces are.
525fn join_records(text: &str) -> Vec<u8> {
526    let mut data = Vec::with_capacity(text.len());
527    for line in text.split('\n') {
528        data.extend_from_slice(line.trim_end_matches(['\r', ' ']).as_bytes());
529    }
530    data
531}
532
533/// How the part data is encoded: text tokens, or binary (§3.3), neutral
534/// binary big-endian and typed binary in its writer's byte order.
535#[derive(Clone, Copy, Debug, PartialEq, Eq)]
536pub(super) enum Encoding {
537    Text,
538    Binary { little: bool },
539}
540
541pub(super) struct Stream<'a> {
542    data: &'a [u8],
543    at: usize,
544    encoding: Encoding,
545}
546
547impl<'a> Stream<'a> {
548    /// A binary stream from its first byte.
549    pub(super) fn binary(data: &'a [u8], little: bool) -> Self {
550        Stream { data, at: 0, encoding: Encoding::Binary { little } }
551    }
552
553    fn skip_blank(&mut self) {
554        while self.at < self.data.len() && self.data[self.at].is_ascii_whitespace() {
555            self.at += 1;
556        }
557    }
558
559    fn remaining(&self) -> usize {
560        self.data.len().saturating_sub(self.at)
561    }
562
563    fn peek(&self) -> Option<u8> {
564        self.data.get(self.at).copied()
565    }
566
567    fn next_byte(&mut self) -> Option<u8> {
568        let b = self.peek()?;
569        self.at += 1;
570        Some(b)
571    }
572
573    fn take<const N: usize>(&mut self) -> Result<[u8; N], String> {
574        let bytes = self
575            .data
576            .get(self.at..self.at + N)
577            .ok_or("the data ends inside a binary value")?
578            .try_into()
579            .map_err(|_| "a binary value is cut short".to_string())?;
580        self.at += N;
581        Ok(bytes)
582    }
583
584    fn little(&self) -> bool {
585        matches!(self.encoding, Encoding::Binary { little: true })
586    }
587
588    fn raw_i16(&mut self) -> Result<i16, String> {
589        let b = self.take::<2>()?;
590        Ok(if self.little() { i16::from_le_bytes(b) } else { i16::from_be_bytes(b) })
591    }
592
593    fn raw_i32(&mut self) -> Result<i32, String> {
594        let b = self.take::<4>()?;
595        Ok(if self.little() { i32::from_le_bytes(b) } else { i32::from_be_bytes(b) })
596    }
597
598    fn raw_f64(&mut self) -> Result<f64, String> {
599        let b = self.take::<8>()?;
600        Ok(if self.little() { f64::from_le_bytes(b) } else { f64::from_be_bytes(b) })
601    }
602
603    /// A one-byte integer (a field count); text writes it as any integer.
604    fn byte_int(&mut self) -> Result<Option<i64>, String> {
605        match self.encoding {
606            Encoding::Text => self.int(),
607            Encoding::Binary { .. } => Ok(Some(i64::from(self.next_byte().ok_or("the data ends inside a byte")?))),
608        }
609    }
610
611    /// A two-byte integer (a node type, a pointer class); null is -32764.
612    fn short(&mut self) -> Result<Option<i64>, String> {
613        match self.encoding {
614            Encoding::Text => self.int(),
615            Encoding::Binary { .. } => Ok(Some(i64::from(self.raw_i16()?)).filter(|&v| v != NULL_INT)),
616        }
617    }
618
619    /// A four-byte integer (a variable length, the user field size, an
620    /// integer field); null is -32764.
621    fn long(&mut self) -> Result<Option<i64>, String> {
622        match self.encoding {
623            Encoding::Text => self.int(),
624            Encoding::Binary { .. } => Ok(Some(i64::from(self.raw_i32()?)).filter(|&v| v != NULL_INT)),
625        }
626    }
627
628    /// A node index or pointer (§3.3.3): in binary, index + 1 in two bytes
629    /// below 32767; above, the negated remainder + 1 and then the quotient.
630    /// Null is 0.
631    pub(super) fn index(&mut self) -> Result<i64, String> {
632        match self.encoding {
633            Encoding::Text => Ok(self.int()?.unwrap_or(0)),
634            Encoding::Binary { .. } => {
635                let r = i64::from(self.raw_i16()?);
636                match r {
637                    0 => Err(format!("a pointer at byte {} is 0, which no writer emits", self.at - 2)),
638                    r if r > 0 => Ok(r - 1),
639                    r => {
640                        let q = i64::from(self.raw_i16()?);
641                        Ok(q * 32767 - r - 1)
642                    }
643                }
644            }
645        }
646    }
647
648    /// The modeller version and schema strings: in binary, a length of
649    /// `width` bytes then the characters.
650    fn header_string(&mut self, width: usize) -> Result<String, String> {
651        let n = match (self.encoding, width) {
652            (Encoding::Text, _) => return self.string(),
653            (_, 2) => i64::from(self.raw_i16()?),
654            _ => i64::from(self.raw_i32()?),
655        };
656        let n = usize::try_from(n).map_err(|_| format!("a header string length {n} is negative"))?;
657        let bytes = self.data.get(self.at..self.at + n).ok_or("a header string runs past the end of the data")?;
658        self.at += n;
659        Ok(String::from_utf8_lossy(bytes).into_owned())
660    }
661
662    /// A space-terminated token.
663    fn token(&mut self) -> Result<&str, String> {
664        let start = self.at;
665        while self.at < self.data.len() && self.data[self.at] != b' ' {
666            self.at += 1;
667        }
668        let token = &self.data[start..self.at];
669        if self.at < self.data.len() {
670            self.at += 1;
671        }
672        if token.is_empty() {
673            return Err(if start >= self.data.len() {
674                "the data ends before the terminator".into()
675            } else {
676                format!("an empty token at byte {start}")
677            });
678        }
679        std::str::from_utf8(token).map_err(|_| format!("a non-text token at byte {start}"))
680    }
681
682    /// An integer, or `None` for `?`.
683    fn int(&mut self) -> Result<Option<i64>, String> {
684        if self.peek() == Some(b'?') {
685            self.at += 1;
686            return Ok(None);
687        }
688        let at = self.at;
689        let token = self.token()?;
690        let value: i64 = token.parse().map_err(|_| format!("expected an integer at byte {at}, read {token:?}"))?;
691        Ok((value != NULL_INT).then_some(value))
692    }
693
694    /// A real, or `None` for `?`.
695    fn real(&mut self) -> Result<Option<f64>, String> {
696        if self.peek() == Some(b'?') {
697            self.at += 1;
698            return Ok(None);
699        }
700        let at = self.at;
701        let token = self.token()?;
702        let value: f64 = token.parse().map_err(|_| format!("expected a real at byte {at}, read {token:?}"))?;
703        if !value.is_finite() {
704            return Err(format!("a non-finite real at byte {at}"));
705        }
706        // The null real, -3.14158e13, marks an unset value in binary writers.
707        Ok((value != -3.14158e13).then_some(value))
708    }
709
710    fn vector(&mut self) -> Result<Option<[f64; 3]>, String> {
711        // One `?` stands for a whole unset vector (§3.2).
712        if self.peek() == Some(b'?') {
713            self.at += 1;
714            return Ok(None);
715        }
716        let (x, y, z) = (self.real()?, self.real()?, self.real()?);
717        Ok(match (x, y, z) {
718            (Some(x), Some(y), Some(z)) => Some([x, y, z]),
719            _ => None,
720        })
721    }
722
723    fn value(&mut self, field: &FieldDef) -> Result<Value, String> {
724        if let Encoding::Binary { .. } = self.encoding {
725            return self.binary_value(field);
726        }
727        let kind = field.kind;
728        Ok(match kind {
729            Kind::Int => Value::Int(self.int()?),
730            Kind::Real => Value::Real(self.real()?),
731            Kind::Vector => Value::Vector(self.vector()?),
732            // Like a vector, an unset interval or box is one `?`.
733            Kind::Interval | Kind::Box if self.peek() == Some(b'?') => {
734                self.at += 1;
735                match kind {
736                    Kind::Interval => Value::Interval([None; 2]),
737                    _ => Value::Box([None; 6]),
738                }
739            }
740            Kind::Interval => Value::Interval([self.real()?, self.real()?]),
741            Kind::Box => {
742                let mut out = [None; 6];
743                for v in &mut out {
744                    *v = self.real()?;
745                }
746                Value::Box(out)
747            }
748            Kind::Char => Value::Char(self.next_byte().ok_or("the data ends inside a character field")?),
749            Kind::Unknown => {
750                return Err("the base schema layout of this field is not known (it is deleted in every schema seen)".into())
751            }
752        })
753    }
754
755    /// A field in binary (§3.3): by its type code's width. A logical is 0 or
756    /// 1 in its byte and is read as text writes it, `F` or `T`.
757    fn binary_value(&mut self, field: &FieldDef) -> Result<Value, String> {
758        let real = |stream: &mut Self| -> Result<Option<f64>, String> {
759            let value = stream.raw_f64()?;
760            if !value.is_finite() {
761                return Err(format!("a non-finite real at byte {}", stream.at - 8));
762            }
763            Ok((value != -3.14158e13).then_some(value))
764        };
765        Ok(match field.code {
766            b'p' => Value::Int(Some(self.index()?)),
767            b'u' => Value::Int(Some(i64::from(self.next_byte().ok_or("the data ends inside a byte field")?))),
768            b'n' | b'w' => Value::Int(self.short()?),
769            b'd' | b't' => Value::Int(self.long()?),
770            b'f' => Value::Real(real(self)?),
771            b'v' | b'h' => {
772                let (x, y, z) = (real(self)?, real(self)?, real(self)?);
773                Value::Vector(match (x, y, z) {
774                    (Some(x), Some(y), Some(z)) => Some([x, y, z]),
775                    _ => None,
776                })
777            }
778            b'i' => Value::Interval([real(self)?, real(self)?]),
779            b'b' => {
780                let mut out = [None; 6];
781                for v in &mut out {
782                    *v = real(self)?;
783                }
784                Value::Box(out)
785            }
786            b'l' => Value::Char(match self.next_byte().ok_or("the data ends inside a logical field")? {
787                0 => b'F',
788                1 => b'T',
789                other => return Err(format!("a logical byte {other}, expected 0 or 1")),
790            }),
791            b'c' => Value::Char(self.next_byte().ok_or("the data ends inside a character field")?),
792            _ => {
793                return Err("the base schema layout of this field is not known (it is deleted in every schema seen)".into())
794            }
795        })
796    }
797
798    /// A short string: its length, a space, then the characters (§2.1.2.1);
799    /// in binary a one-byte length, then the characters.
800    fn string(&mut self) -> Result<String, String> {
801        let n = self.byte_int()?.ok_or("a string length is unset")?;
802        let n = usize::try_from(n).map_err(|_| format!("string length {n} is negative"))?;
803        if n > self.remaining() {
804            return Err(format!("string length {n} runs past the end of the data"));
805        }
806        self.chars(n)
807    }
808
809    /// `n` characters of a char field, with the §3.2 and §2.1.3 escapes
810    /// (`\0`, `\n`, `\r`, `\\`, and `\<d>` for d spaces) each counting as the
811    /// characters they stand for.
812    fn chars(&mut self, n: usize) -> Result<String, String> {
813        if let Encoding::Binary { .. } = self.encoding {
814            let bytes = self.data.get(self.at..self.at + n).ok_or("the data ends inside a string")?;
815            self.at += n;
816            return Ok(String::from_utf8_lossy(bytes).into_owned());
817        }
818        let mut out = Vec::with_capacity(n);
819        while out.len() < n {
820            let b = self.next_byte().ok_or("the data ends inside a string")?;
821            if b != b'\\' {
822                out.push(b);
823                continue;
824            }
825            match self.next_byte() {
826                Some(b'0') => out.push(0),
827                Some(b'n') => out.push(b'\n'),
828                Some(b'r') => out.push(b'\r'),
829                Some(b'\\') => out.push(b'\\'),
830                Some(d @ b'1'..=b'9') => out.extend(std::iter::repeat(b' ').take(usize::from(d - b'0'))),
831                Some(other) => {
832                    out.push(b'\\');
833                    out.push(other);
834                }
835                None => return Err("the data ends inside a string escape".into()),
836            }
837        }
838        out.truncate(n);
839        Ok(String::from_utf8_lossy(&out).into_owned())
840    }
841
842    /// A field description in a schema delta (§2.1.2.2): name, pointer class,
843    /// element count, type (when not a pointer), transmit flag (when variable).
844    fn field_def(&mut self) -> Result<FieldDef, String> {
845        let name = self.string()?;
846        let pointer_class = self.short()?.unwrap_or(0);
847        // Binary writes the element count as it writes an index (+1, two
848        // bytes): every SolidWorks partition's deltas read to their end so.
849        let elements = match self.encoding {
850            Encoding::Text => self.int()?.ok_or("a field's element count is unset")?,
851            Encoding::Binary { .. } => self.index()?,
852        };
853        let (kind, code) = if pointer_class != 0 {
854            (Kind::Int, b'p')
855        } else {
856            let code = self.string()?;
857            let code = code.bytes().next().ok_or_else(|| format!("field {name} has an empty type"))?;
858            (schema::kind_of(code).ok_or_else(|| format!("field {name} has unknown type {:?}", char::from(code)))?, code)
859        };
860        if elements == 1 {
861            self.next_byte().ok_or("the data ends inside a field description")?;
862        }
863        let count = match elements {
864            0 => Count::Scalar,
865            1 => Count::Variable,
866            n if n > 1 && (n as u64) <= self.remaining() as u64 => Count::Fixed(n as usize),
867            n => return Err(format!("field {name} has element count {n}")),
868        };
869        Ok(FieldDef { name, kind, count, code })
870    }
871}