1use std::rc::Rc;
11
12use rustc_hash::FxHashMap as HashMap;
13
14use super::schema::{self, Count, FieldDef, Kind};
15
16#[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#[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#[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 pub fn field(&self, name: &str) -> Option<&Value> {
66 self.layout.position(name).map(|i| &self.values[i])
67 }
68
69 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 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 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 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 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 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#[derive(Debug)]
165pub struct XtFile {
166 pub modeller_version: String,
168 pub schema: String,
170 pub header: Vec<(String, String)>,
172 pub partition: bool,
175 nodes: Vec<Node>,
176 by_index: HashMap<u32, usize>,
177}
178
179impl XtFile {
180 pub fn root(&self) -> Option<&Node> {
182 self.nodes.first()
183 }
184
185 pub fn nodes(&self) -> &[Node] {
186 &self.nodes
187 }
188
189 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 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
207const NULL_INT: i64 = -32764;
209
210pub 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
234pub fn parse_xt(bytes: &[u8]) -> Result<XtFile, String> {
239 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
281fn parse_data(header: Vec<(String, String)>, mut stream: Stream) -> Result<XtFile, String> {
284 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 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 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 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
368fn 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
379fn read_layout(stream: &mut Stream, node_type: u16) -> Result<NodeLayout, String> {
382 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 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
430fn 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 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
472fn 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
499fn 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
523fn 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#[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 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 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 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 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 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 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 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 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 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 Ok((value != -3.14158e13).then_some(value))
708 }
709
710 fn vector(&mut self) -> Result<Option<[f64; 3]>, String> {
711 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 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 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 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 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 fn field_def(&mut self) -> Result<FieldDef, String> {
845 let name = self.string()?;
846 let pointer_class = self.short()?.unwrap_or(0);
847 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}