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