Skip to main content

brep_kernel/io/parasolid/
writer.rs

1//! The text transmit writer: the reader's inverse (Parasolid XT Format
2//! Reference §2.1, §3.2).
3//!
4//! The part data is one token stream, cut into records of at most 80
5//! characters. Numbers end with a space; `c` and `l` fields, `?` (unset)
6//! and the characters of a string do not. A record never ends with a space
7//! (a reader drops trailing spaces), so a cut that would leave one there
8//! moves back to the last character that is not a space and the spaces
9//! start the next record. Reals are written in the shorter of their
10//! decimal form (no leading zero) and an integer mantissa with an exponent
11//! (`4826e-8`), the decimal on a tie when the exponent would be negative;
12//! with the fewest digits that read back to the same double. All 2000 files
13//! of the ABC sample written by Parasolid 30.1 cut and format exactly so.
14
15use super::reader::{Node, NodeLayout, Value, XtFile};
16use super::schema::{Count, Kind};
17
18/// `text` with every character a text transmit file cannot hold (beyond
19/// 7-bit ASCII) as `?`.
20pub(super) fn ascii(text: &str) -> std::borrow::Cow<'_, str> {
21    if text.is_ascii() {
22        std::borrow::Cow::Borrowed(text)
23    } else {
24        std::borrow::Cow::Owned(text.chars().map(|c| if c.is_ascii() { c } else { '?' }).collect())
25    }
26}
27
28/// The record length of a text transmit file.
29const RECORD: usize = 80;
30
31/// A real as Parasolid writes it in a text file.
32pub(super) fn format_real(x: f64) -> String {
33    if x == 0.0 {
34        return "0".into();
35    }
36    // The fewest significant digits that read back to `x`.
37    let mut digits = String::new();
38    let mut exponent = 0i32;
39    for precision in 1..=17usize {
40        let s = format!("{:.*e}", precision - 1, x.abs());
41        if s.parse::<f64>().ok() == Some(x.abs()) {
42            let (mantissa, e) = s.split_once('e').unwrap_or((&s, "0"));
43            digits = mantissa.replace('.', "");
44            exponent = e.parse().unwrap_or(0);
45            break;
46        }
47    }
48    let digits = digits.trim_end_matches('0');
49    let digits = if digits.is_empty() { "0" } else { digits };
50    let n = digits.len() as i32;
51    // x = 0.d1 d2 ... × 10^(exponent + 1) = D × 10^(exponent - n + 1).
52    let integer_exponent = exponent - n + 1;
53    let scientific = format!("{digits}e{integer_exponent}");
54    let point = exponent + 1;
55    let fixed = if point <= 0 {
56        format!(".{}{digits}", "0".repeat((-point) as usize))
57    } else if point >= n {
58        format!("{digits}{}", "0".repeat((point - n) as usize))
59    } else {
60        format!("{}.{}", &digits[..point as usize], &digits[point as usize..])
61    };
62    let chosen = if fixed.len() < scientific.len() || (fixed.len() == scientific.len() && integer_exponent < 0) {
63        fixed
64    } else {
65        scientific
66    };
67    if x < 0.0 {
68        format!("-{chosen}")
69    } else {
70        chosen
71    }
72}
73
74/// Cut the token stream into records.
75pub(super) fn records(data: &str) -> String {
76    // The token stream is ASCII ([`ascii`]), so every byte is a character.
77    debug_assert!(data.is_ascii());
78    let bytes = data.as_bytes();
79    let mut out = String::with_capacity(data.len() + data.len() / RECORD + 1);
80    let mut at = 0;
81    while at < bytes.len() {
82        let mut end = (at + RECORD).min(bytes.len());
83        if end - at == RECORD {
84            while end > at + 1 && bytes[end - 1] == b' ' {
85                end -= 1;
86            }
87        }
88        out.push_str(&data[at..end]);
89        out.push('\n');
90        at = end;
91    }
92    out
93}
94
95/// The token stream of a part's data.
96#[derive(Default)]
97pub(super) struct Tokens {
98    pub(super) data: String,
99}
100
101impl Tokens {
102    pub(super) fn int(&mut self, value: Option<i64>) {
103        match value {
104            Some(v) => {
105                self.data.push_str(&v.to_string());
106                self.data.push(' ');
107            }
108            None => self.data.push('?'),
109        }
110    }
111
112    pub(super) fn real(&mut self, value: Option<f64>) {
113        match value {
114            Some(v) => {
115                self.data.push_str(&format_real(v));
116                self.data.push(' ');
117            }
118            None => self.data.push('?'),
119        }
120    }
121
122    /// The characters of a string, escaped (§3.2): null, carriage return,
123    /// line feed and backslash. A text file holds 7-bit characters: any
124    /// other is written `?` (so the length counts characters written).
125    pub(super) fn chars(&mut self, text: &str) {
126        for c in ascii(text).bytes() {
127            match c {
128                0 => self.data.push_str("\\0"),
129                b'\n' => self.data.push_str("\\n"),
130                b'\r' => self.data.push_str("\\r"),
131                b'\\' => self.data.push_str("\\\\"),
132                c => self.data.push(char::from(c)),
133            }
134        }
135    }
136
137    /// A short string: its length, a space, its characters.
138    pub(super) fn string(&mut self, text: &str) {
139        self.int(Some(ascii(text).len() as i64));
140        self.chars(text);
141    }
142
143    fn value(&mut self, kind: Kind, value: &Value) -> Result<(), String> {
144        match (kind, value) {
145            (Kind::Int, Value::Int(v)) => self.int(*v),
146            (Kind::Real, Value::Real(v)) => self.real(*v),
147            (Kind::Vector, Value::Vector(None)) => self.data.push('?'),
148            (Kind::Vector, Value::Vector(Some(v))) => v.iter().for_each(|x| self.real(Some(*x))),
149            (Kind::Interval, Value::Interval(v)) if v.iter().all(Option::is_none) => self.data.push('?'),
150            (Kind::Interval, Value::Interval(v)) => v.iter().for_each(|x| self.real(*x)),
151            (Kind::Box, Value::Box(v)) if v.iter().all(Option::is_none) => self.data.push('?'),
152            (Kind::Box, Value::Box(v)) => v.iter().for_each(|x| self.real(*x)),
153            (Kind::Char, Value::Char(c)) => self.data.push(char::from(*c)),
154            (kind, value) => return Err(format!("a {kind:?} field holds {value:?}")),
155        }
156        Ok(())
157    }
158
159    /// One node: its type, its layout's description at the type's first
160    /// node, its variable length, its index and its fields.
161    pub(super) fn node(&mut self, node: &Node, describe: bool, user_field_size: usize) -> Result<(), String> {
162        let layout: &NodeLayout = &node.layout;
163        self.int(Some(i64::from(layout.node_type)));
164        if describe {
165            let delta = layout.delta.as_deref().ok_or_else(|| format!("{} has no layout description to write", layout.name))?;
166            self.data.push_str(delta);
167        }
168        let variable = layout.fields.last().filter(|f| f.count == Count::Variable);
169        if let Some(field) = variable {
170            let length = match node.values.last() {
171                Some(Value::Text(text)) => ascii(text).len(),
172                Some(Value::Array(items)) => items.len(),
173                other => return Err(format!("{}'s variable field {} holds {other:?}", layout.name, field.name)),
174            };
175            self.int(Some(length as i64));
176        }
177        self.int(Some(i64::from(node.index)));
178        for (field, value) in layout.fields.iter().zip(&node.values) {
179            match (field.count, value) {
180                (Count::Scalar, value) => self.value(field.kind, value)?,
181                (Count::Variable, Value::Text(text)) => self.chars(text),
182                (_, Value::Array(items)) => {
183                    for item in items {
184                        self.value(field.kind, item)?;
185                    }
186                }
187                (_, value) => return Err(format!("{} field {} holds {value:?}", layout.name, field.name)),
188            }
189        }
190        if layout.node_type < 1000 && super::reader::carries_user_field(layout.node_type) {
191            for _ in 0..user_field_size {
192                self.int(Some(0));
193            }
194        }
195        Ok(())
196    }
197}
198
199/// A parsed file's part data written again: the banner, the schema, each
200/// node with its layout described at its type's first node, the terminator
201/// — cut into records. What [`super::parse_xt_text`] read from a text file
202/// with embedded deltas is written back as that file had it.
203pub fn write_xt_part_data(file: &XtFile) -> Result<String, String> {
204    if file.user_field_size > 0 {
205        return Err("the file carries user fields, which the reader does not keep: it is not written back".into());
206    }
207    let mut tokens = Tokens::default();
208    tokens.data.push('T');
209    tokens.string(&file.modeller_version);
210    tokens.string(&file.schema);
211    if file.max_node_type.is_some() {
212        tokens.int(file.max_node_type);
213    }
214    tokens.int(Some(file.user_field_size as i64));
215    let mut described = rustc_hash::FxHashSet::default();
216    for node in file.nodes() {
217        let first = described.insert(node.node_type());
218        tokens.node(node, first && file.max_node_type.is_some(), file.user_field_size)?;
219    }
220    tokens.int(Some(1));
221    tokens.int(Some(0));
222    Ok(records(&tokens.data))
223}
224
225/// The neutral binary token stream (§3.3.3): big-endian; node types and
226/// short integers in two bytes, integers and lengths in four, reals in
227/// eight; pointers as index + 1 in two bytes (the negated remainder + 1 and
228/// the quotient past 32766); nulls as -32764 and -3.14158e13; logicals as 0
229/// and 1; short strings with a one-byte length.
230#[derive(Default)]
231pub(super) struct BinaryTokens {
232    pub(super) data: Vec<u8>,
233}
234
235const NULL_INT: i64 = -32764;
236const NULL_REAL: f64 = -3.14158e13;
237
238impl BinaryTokens {
239    fn u8(&mut self, v: u8) {
240        self.data.push(v);
241    }
242
243    fn i16(&mut self, v: i64) -> Result<(), String> {
244        let v = i16::try_from(v).map_err(|_| format!("{v} does not fit two bytes"))?;
245        self.data.extend_from_slice(&v.to_be_bytes());
246        Ok(())
247    }
248
249    fn i32(&mut self, v: i64) -> Result<(), String> {
250        let v = i32::try_from(v).map_err(|_| format!("{v} does not fit four bytes"))?;
251        self.data.extend_from_slice(&v.to_be_bytes());
252        Ok(())
253    }
254
255    fn f64(&mut self, v: f64) {
256        self.data.extend_from_slice(&v.to_be_bytes());
257    }
258
259    /// A node index or pointer.
260    pub(super) fn index(&mut self, index: i64) -> Result<(), String> {
261        if !(0..=i64::from(i16::MAX) * 32767).contains(&index) {
262            return Err(format!("index {index} cannot be written"));
263        }
264        if index < 32767 {
265            self.i16(index + 1)
266        } else {
267            self.i16(-(index % 32767 + 1))?;
268            self.i16(index / 32767)
269        }
270    }
271
272    fn short_string(&mut self, text: &[u8]) -> Result<(), String> {
273        let n = u8::try_from(text.len()).map_err(|_| "a short string is longer than 255 bytes".to_string())?;
274        self.u8(n);
275        self.data.extend_from_slice(text);
276        Ok(())
277    }
278
279    fn value(&mut self, code: u8, value: &Value) -> Result<(), String> {
280        let real = |s: &mut Self, x: &Option<f64>| s.f64(x.unwrap_or(NULL_REAL));
281        match (code, value) {
282            (b'p', Value::Int(v)) => self.index(v.unwrap_or(0))?,
283            (b'u', Value::Int(v)) => self.u8(u8::try_from(v.unwrap_or(0)).map_err(|_| format!("byte field holds {v:?}"))?),
284            (b'n' | b'w', Value::Int(v)) => self.i16(v.unwrap_or(NULL_INT))?,
285            (b'd' | b't', Value::Int(v)) => self.i32(v.unwrap_or(NULL_INT))?,
286            (b'f', Value::Real(v)) => real(self, v),
287            (b'v' | b'h', Value::Vector(v)) => match v {
288                Some(p) => p.iter().for_each(|x| self.f64(*x)),
289                None => (0..3).for_each(|_| self.f64(NULL_REAL)),
290            },
291            (b'i', Value::Interval(v)) => v.iter().for_each(|x| real(self, x)),
292            (b'b', Value::Box(v)) => v.iter().for_each(|x| real(self, x)),
293            (b'l', Value::Char(c)) => self.u8(u8::from(*c == b'T')),
294            (b'c', Value::Char(c)) => self.u8(*c),
295            (code, value) => return Err(format!("a `{}` field holds {value:?}", char::from(code))),
296        }
297        Ok(())
298    }
299
300    /// One node, its layout described at its type's first node: the raw
301    /// binary description a binary file carried, or a text description
302    /// converted.
303    pub(super) fn node(&mut self, node: &Node, describe: bool, user_field_size: usize) -> Result<(), String> {
304        let layout: &NodeLayout = &node.layout;
305        self.i16(i64::from(layout.node_type))?;
306        if describe {
307            match (&layout.delta_binary, &layout.delta) {
308                (Some(raw), _) => self.data.extend_from_slice(raw),
309                (None, Some(text)) => self.data.extend(delta_to_binary(layout.node_type, text)?),
310                (None, None) => return Err(format!("{} has no layout description to write", layout.name)),
311            }
312        }
313        if let Some(field) = layout.fields.last().filter(|f| f.count == Count::Variable) {
314            let length = match node.values.last() {
315                Some(Value::Text(text)) => text.len(),
316                Some(Value::Array(items)) => items.len(),
317                other => return Err(format!("{}'s variable field {} holds {other:?}", layout.name, field.name)),
318            };
319            self.i32(length as i64)?;
320        }
321        self.index(i64::from(node.index))?;
322        for (field, value) in layout.fields.iter().zip(&node.values) {
323            match (field.count, value) {
324                (Count::Scalar, value) => self.value(field.code, value)?,
325                (Count::Variable, Value::Text(text)) => self.data.extend_from_slice(text.as_bytes()),
326                (_, Value::Array(items)) => {
327                    for item in items {
328                        self.value(field.code, item)?;
329                    }
330                }
331                (_, value) => return Err(format!("{} field {} holds {value:?}", layout.name, field.name)),
332            }
333        }
334        if layout.node_type < 1000 && super::reader::carries_user_field(layout.node_type) {
335            for _ in 0..user_field_size {
336                self.i32(0)?;
337            }
338        }
339        Ok(())
340    }
341
342    /// The flag sequence and prologue (§3.3): `PS\0\0`, the modeller version
343    /// (two-byte length), the schema (four-byte length), the largest node
344    /// type when the layouts are described, the user field size.
345    pub(super) fn prologue(&mut self, modeller: &str, schema: &str, max_node_type: Option<i64>, user_field_size: usize) -> Result<(), String> {
346        self.data.extend_from_slice(b"PS\0\0");
347        self.i16(modeller.len() as i64)?;
348        self.data.extend_from_slice(modeller.as_bytes());
349        self.i32(schema.len() as i64)?;
350        self.data.extend_from_slice(schema.as_bytes());
351        if let Some(max) = max_node_type {
352            self.i16(max)?;
353        }
354        self.i32(user_field_size as i64)
355    }
356
357    pub(super) fn terminator(&mut self) -> Result<(), String> {
358        self.i16(1)?;
359        self.index(0)
360    }
361}
362
363/// A layout description as a text file writes it, in binary: the field
364/// count as a byte; for a type the base has, the edit letters, each new
365/// field as its name (one-byte length), pointer class (two bytes), element
366/// count (as an index), type code (when not a pointer) and transmit flag
367/// (when variable); for a new type, its name, description and fields.
368pub(super) fn delta_to_binary(node_type: u16, text: &str) -> Result<Vec<u8>, String> {
369    let bytes = text.as_bytes();
370    let mut at = 0usize;
371    let token = |at: &mut usize| -> Result<i64, String> {
372        let start = *at;
373        while *at < bytes.len() && bytes[*at] != b' ' {
374            *at += 1;
375        }
376        let t = std::str::from_utf8(&bytes[start..*at]).map_err(|e| e.to_string())?;
377        *at += 1;
378        t.parse::<i64>().map_err(|_| format!("a delta for node type {node_type} has {t:?} where an integer belongs"))
379    };
380    let string = |at: &mut usize| -> Result<Vec<u8>, String> {
381        let n = token(at)? as usize;
382        let s = bytes.get(*at..*at + n).ok_or("a delta string runs past its end")?.to_vec();
383        *at += n;
384        Ok(s)
385    };
386    let mut out = BinaryTokens::default();
387    let field = |at: &mut usize, out: &mut BinaryTokens| -> Result<(), String> {
388        let name = string(at)?;
389        let class = token(at)?;
390        let elements = token(at)?;
391        out.short_string(&name)?;
392        out.i16(class)?;
393        out.index(elements)?;
394        if class == 0 {
395            let code = string(at)?;
396            out.short_string(&code)?;
397        }
398        if elements == 1 {
399            let flag = *bytes.get(*at).ok_or("a delta ends inside a field")?;
400            *at += 1;
401            out.u8(flag);
402        }
403        Ok(())
404    };
405    let count = token(&mut at)?;
406    out.u8(u8::try_from(count).map_err(|_| format!("a field count of {count}"))?);
407    if count == 255 {
408        return Ok(out.data);
409    }
410    if super::schema::base(node_type).is_none() {
411        let name = string(&mut at)?;
412        let description = string(&mut at)?;
413        out.short_string(&name)?;
414        out.short_string(&description)?;
415        for _ in 0..count {
416            field(&mut at, &mut out)?;
417        }
418        return Ok(out.data);
419    }
420    loop {
421        let letter = *bytes.get(at).ok_or("a delta ends before Z")?;
422        at += 1;
423        out.u8(letter);
424        match letter {
425            b'C' | b'D' => {}
426            b'I' | b'A' => field(&mut at, &mut out)?,
427            b'Z' => break,
428            other => return Err(format!("a delta has edit letter {:?}", char::from(other))),
429        }
430    }
431    Ok(out.data)
432}
433
434/// A parsed file's part data written again in neutral binary: what
435/// [`super::parse_xt`] read from a neutral binary file comes back as that
436/// file had it.
437pub fn write_xt_binary_part_data(file: &XtFile) -> Result<Vec<u8>, String> {
438    if file.user_field_size > 0 {
439        return Err("the file carries user fields, which the reader does not keep: it is not written back".into());
440    }
441    let mut tokens = BinaryTokens::default();
442    tokens.prologue(&file.modeller_version, &file.schema, file.max_node_type, file.user_field_size)?;
443    let mut described = rustc_hash::FxHashSet::default();
444    for node in file.nodes() {
445        let first = described.insert(node.node_type());
446        tokens.node(node, first && file.max_node_type.is_some(), file.user_field_size)?;
447    }
448    tokens.terminator()?;
449    Ok(tokens.data)
450}