Skip to main content

rust_motion_affinity/
stream.rs

1//! The tagged object stream inside `doc.dat`: a self-describing tree of objects whose fields carry
2//! a type code and a four-character tag. Parsing needs no schema; unknown fields are kept, so the
3//! document mapping can name what it could not import.
4
5use crate::container::Cursor;
6use crate::Error;
7
8/// A four-character tag in its readable order (`Desc`, `Chld`).
9#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
10pub struct Tag(pub u32);
11
12impl Tag {
13    pub const fn of(s: &[u8; 4]) -> Self {
14        Self(u32::from_be_bytes(*s))
15    }
16}
17
18impl std::fmt::Debug for Tag {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        write!(f, "{}", String::from_utf8_lossy(&self.0.to_be_bytes()))
21    }
22}
23
24impl std::fmt::Display for Tag {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        std::fmt::Debug::fmt(self, f)
27    }
28}
29
30/// Index of an object in [`Stream::objects`].
31pub type ObjId = usize;
32
33#[derive(Debug, Clone, PartialEq)]
34pub enum Value {
35    Int(i64),
36    UInt(u64),
37    Float(f64),
38    Bool(bool),
39    Enum {
40        id: u16,
41        version: u16,
42    },
43    Str(String),
44    /// Fixed-length vectors of i32/f32/f64 (points, rectangles, transforms).
45    Ints(Vec<i64>),
46    Floats(Vec<f64>),
47    /// Fixed-size record (curve nodes, ids) or fixed-size struct (colour components).
48    Bytes(Vec<u8>),
49    Blob(Vec<u8>),
50    /// Name of another archive entry (raster tiles, embedded files).
51    Entry(String),
52    Flags(u64),
53    /// `None` is a null object.
54    Obj(Option<ObjId>),
55    Array(Vec<Value>),
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum Kind {
60    Root,
61    /// Defined once and referenced by id elsewhere.
62    Shared,
63    Inline,
64    /// Untagged fields identified by position (curve data).
65    Positional,
66}
67
68#[derive(Debug, Clone, PartialEq)]
69pub struct Object {
70    pub class: Tag,
71    pub kind: Kind,
72    /// Class chain, most derived first (`ShpN`, `VNod`, `Node`).
73    pub chain: Vec<Tag>,
74    /// Fields in stream order; positional fields have tag 0.
75    pub fields: Vec<(Tag, Value)>,
76}
77
78impl Object {
79    pub fn get(&self, tag: Tag) -> Option<&Value> {
80        self.fields.iter().find(|(t, _)| *t == tag).map(|(_, v)| v)
81    }
82}
83
84#[derive(Debug)]
85pub struct Stream {
86    pub root: ObjId,
87    pub objects: Vec<Object>,
88}
89
90/// Deepest object nesting accepted; real documents stay well below (each layer level adds three).
91pub const MAX_DEPTH: usize = 128;
92
93const MAX_OBJECTS: usize = 8_000_000;
94
95/// Most values (fields and array elements) one stream may decode. A value takes about 40 bytes
96/// in memory however few it took in the file (a bool array packs eight in a byte), so the size
97/// of the input alone doesn't bound what parsing allocates: a small compressed entry could
98/// otherwise ask for tens of gigabytes. Real documents stay far below.
99pub const MAX_VALUES: usize = 1 << 24;
100
101struct Parser<'a> {
102    c: Cursor<'a>,
103    objects: Vec<Object>,
104    /// Shared ids, defined at first use and referenced backwards.
105    shared: std::collections::HashMap<u32, ObjId>,
106    depth: usize,
107    /// Values decoded so far, against [`MAX_VALUES`].
108    values: usize,
109}
110
111/// Parse a stream (`00 FF 4B 53` header). Bytes after the root's terminator are ignored.
112pub fn parse(bytes: &[u8]) -> Result<Stream, Error> {
113    let mut c = Cursor::new(bytes, 0);
114    if c.take(4)? != b"\x00\xffKS" {
115        return Err(Error::Malformed("document stream signature"));
116    }
117    let version = c.u16()?;
118    if version > 2 {
119        return Err(Error::Unsupported("document stream version"));
120    }
121    let class = Tag(c.u32()?);
122    c.u16()?;
123    if version == 2 {
124        c.u32()?;
125    }
126    let mut p = Parser {
127        c,
128        objects: Vec::new(),
129        shared: std::collections::HashMap::new(),
130        depth: 0,
131        values: 0,
132    };
133    let root = p.push(Object {
134        class,
135        kind: Kind::Root,
136        chain: vec![class],
137        fields: Vec::new(),
138    })?;
139    let fields = p.fields(true, class)?;
140    if let Some(o) = p.objects.get_mut(root) {
141        o.fields = fields;
142    }
143    Ok(Stream {
144        root,
145        objects: p.objects,
146    })
147}
148
149impl Parser<'_> {
150    fn push(&mut self, o: Object) -> Result<ObjId, Error> {
151        if self.objects.len() >= MAX_OBJECTS {
152            return Err(Error::Limit("too many objects"));
153        }
154        self.objects.push(o);
155        Ok(self.objects.len() - 1)
156    }
157
158    /// Counts `n` more values against [`MAX_VALUES`], before anything is allocated for them.
159    fn spend(&mut self, n: usize) -> Result<(), Error> {
160        self.values = self
161            .values
162            .checked_add(n)
163            .filter(|&v| v <= MAX_VALUES)
164            .ok_or(Error::Limit("too many values in the document stream"))?;
165        Ok(())
166    }
167
168    /// An empty array with room for `n` values, paid for first; an allocation that still fails
169    /// is an error, not an abort.
170    fn vec<T>(&mut self, n: usize) -> Result<Vec<T>, Error> {
171        self.spend(n)?;
172        let mut v = Vec::new();
173        v.try_reserve_exact(n)
174            .map_err(|_| Error::Limit("not enough memory for the document stream"))?;
175        Ok(v)
176    }
177
178    /// Element count of an array: each element takes at least `min` bytes, so a count the
179    /// remaining input cannot hold is rejected before anything is allocated.
180    fn count(&mut self, min: usize) -> Result<usize, Error> {
181        let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?;
182        if n.checked_mul(min.max(1))
183            .is_none_or(|bytes| bytes > self.c.remaining())
184        {
185            return Err(Error::Malformed("array longer than its data"));
186        }
187        Ok(n)
188    }
189
190    fn fields(&mut self, tagged: bool, class: Tag) -> Result<Vec<(Tag, Value)>, Error> {
191        self.depth += 1;
192        if self.depth > MAX_DEPTH {
193            return Err(Error::Limit("objects nested too deeply"));
194        }
195        let mut out = Vec::new();
196        loop {
197            let t = self.c.u8()?;
198            let code = t & 0x7F;
199            if code == 0 {
200                break;
201            }
202            self.spend(1)?;
203            let tag = if tagged { Tag(self.c.u32()?) } else { Tag(0) };
204            let v = if t & 0x80 != 0 {
205                self.array(code, class)?
206            } else {
207                self.scalar(code, tagged, class)?
208            };
209            out.push((tag, v));
210        }
211        self.depth -= 1;
212        Ok(out)
213    }
214
215    fn string(&mut self) -> Result<String, Error> {
216        let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("string length"))?;
217        Ok(String::from_utf8_lossy(self.c.take(n)?).into_owned())
218    }
219
220    fn floats(&mut self, n: usize, wide: bool) -> Result<Value, Error> {
221        let mut v = Vec::with_capacity(n);
222        for _ in 0..n {
223            v.push(if wide {
224                f64::from_le_bytes(self.c.array()?)
225            } else {
226                f64::from(f32::from_le_bytes(self.c.array()?))
227            });
228        }
229        Ok(Value::Floats(v))
230    }
231
232    fn scalar(&mut self, code: u8, tagged: bool, class: Tag) -> Result<Value, Error> {
233        let c = &mut self.c;
234        Ok(match code {
235            0x01 => Value::UInt(c.u8()?.into()),
236            0x02 => Value::UInt(c.u16()?.into()),
237            0x03 | 0x2f | 0x34 => Value::UInt(c.u32()?.into()),
238            0x04 => Value::UInt(c.u64()?),
239            0x05 => Value::Int(i8::from_le_bytes(c.array()?).into()),
240            0x06 => Value::Int(i16::from_le_bytes(c.array()?).into()),
241            0x07 => Value::Int(i32::from_le_bytes(c.array()?).into()),
242            0x08 => Value::Int(i64::from_le_bytes(c.array()?)),
243            0x09 => Value::Float(f32::from_le_bytes(c.array()?).into()),
244            0x0a => Value::Float(f64::from_le_bytes(c.array()?)),
245            0x15..=0x19 => {
246                let n = usize::from(code - 0x13);
247                let mut v = Vec::with_capacity(n);
248                for _ in 0..n {
249                    v.push(i32::from_le_bytes(c.array()?).into());
250                }
251                Value::Ints(v)
252            }
253            0x1f..=0x23 => return self.floats(usize::from(code - 0x1d), false),
254            0x24..=0x28 => return self.floats(usize::from(code - 0x22), true),
255            0x29 => Value::Bool(c.u8()? != 0),
256            0x2a => Value::Enum {
257                id: c.u16()?,
258                version: c.u16()?,
259            },
260            0x2b | 0x2e => Value::Str(self.string()?),
261            0x2c => {
262                let n = usize::from(c.u16()?);
263                Value::Bytes(c.take(n)?.to_vec())
264            }
265            0x35..=0x74 => Value::Bytes(c.take(usize::from(code - 0x34))?.to_vec()),
266            0x2d => {
267                let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("blob length"))?;
268                Value::Blob(c.take(n)?.to_vec())
269            }
270            0x33 => {
271                c.u32()?;
272                let n =
273                    usize::try_from(c.u32()?).map_err(|_| Error::Malformed("entry name length"))?;
274                Value::Entry(String::from_utf8_lossy(c.take(n)?).into_owned())
275            }
276            0x75 => {
277                c.u16()?;
278                let n = usize::from(c.u8()?);
279                if n > 8 {
280                    return Err(Error::Malformed("flags wider than 64 bits"));
281                }
282                let mut b = [0u8; 8];
283                b.get_mut(..n)
284                    .ok_or(Error::Malformed("flags"))?
285                    .copy_from_slice(c.take(n)?);
286                Value::Flags(u64::from_le_bytes(b))
287            }
288            0x30 => {
289                let fields = self.fields(false, class)?;
290                let id = self.push(Object {
291                    class,
292                    kind: Kind::Positional,
293                    chain: Vec::new(),
294                    fields,
295                })?;
296                Value::Obj(Some(id))
297            }
298            0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")),
299            0x31 => self.shared()?,
300            0x32 => self.inline(None)?,
301            _ => return Err(Error::Unsupported("unknown field type in document stream")),
302        })
303    }
304
305    fn array(&mut self, code: u8, class: Tag) -> Result<Value, Error> {
306        let min = match code {
307            0x01 | 0x05 | 0x29 => 1,
308            0x02 | 0x06 => 2,
309            0x03 | 0x07 | 0x09 | 0x2f | 0x34 => 4,
310            0x04 | 0x08 | 0x0a => 8,
311            0x15..=0x19 => 4 * usize::from(code - 0x13),
312            0x1f..=0x23 => 4 * usize::from(code - 0x1d),
313            0x24..=0x28 => 8 * usize::from(code - 0x22),
314            0x35..=0x74 => usize::from(code - 0x34),
315            _ => 1,
316        };
317        match code {
318            0x29 => {
319                let n =
320                    usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?;
321                let bits = self.c.take(n.div_ceil(8))?;
322                let mut v = self.vec(n)?;
323                v.extend(
324                    (0..n).map(|i| {
325                        Value::Bool(bits.get(i / 8).is_some_and(|b| b >> (i % 8) & 1 != 0))
326                    }),
327                );
328                Ok(Value::Array(v))
329            }
330            0x2a => {
331                let n = self.count(2)?;
332                let version = self.c.u16()?;
333                let mut v = self.vec(n)?;
334                for _ in 0..n {
335                    v.push(Value::Enum {
336                        id: self.c.u16()?,
337                        version,
338                    });
339                }
340                Ok(Value::Array(v))
341            }
342            0x2b | 0x2e => {
343                self.c.u32()?;
344                let n = self.count(4)?;
345                let mut v = self.vec(n)?;
346                for _ in 0..n {
347                    v.push(Value::Str(self.string()?));
348                }
349                Ok(Value::Array(v))
350            }
351            0x2c => {
352                let n =
353                    usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?;
354                let size = usize::from(self.c.u16()?);
355                if n.checked_mul(size).is_none_or(|b| b > self.c.remaining()) {
356                    return Err(Error::Malformed("array longer than its data"));
357                }
358                let mut v = self.vec(n)?;
359                for _ in 0..n {
360                    v.push(Value::Bytes(self.c.take(size)?.to_vec()));
361                }
362                Ok(Value::Array(v))
363            }
364            0x32 => {
365                let n = self.count(1)?;
366                let class = Tag(self.c.u32()?);
367                self.c.u16()?;
368                let mut v = self.vec(n)?;
369                for _ in 0..n {
370                    v.push(self.inline(Some(class))?);
371                }
372                Ok(Value::Array(v))
373            }
374            0x2d | 0x33 | 0x75 => Err(Error::Malformed("array of an unarrayable type")),
375            _ => {
376                let n = self.count(min)?;
377                let mut v = self.vec(n)?;
378                for _ in 0..n {
379                    v.push(self.scalar(code, true, class)?);
380                }
381                Ok(Value::Array(v))
382            }
383        }
384    }
385
386    /// Inline object; `class` is given once for a whole array of them.
387    fn inline(&mut self, class: Option<Tag>) -> Result<Value, Error> {
388        match self.c.u8()? {
389            0 => return Ok(Value::Obj(None)),
390            1 => {}
391            _ => return Err(Error::Malformed("object marker")),
392        }
393        let class = match class {
394            Some(c) => c,
395            None => {
396                let c = Tag(self.c.u32()?);
397                self.c.u16()?;
398                c
399            }
400        };
401        let fields = self.fields(true, class)?;
402        let id = self.push(Object {
403            class,
404            kind: Kind::Inline,
405            chain: vec![class],
406            fields,
407        })?;
408        Ok(Value::Obj(Some(id)))
409    }
410
411    fn shared(&mut self) -> Result<Value, Error> {
412        let flag = self.c.u8()?;
413        if flag == 0 {
414            return Ok(Value::Obj(None));
415        }
416        let key = self.c.u32()?;
417        match flag {
418            2 => {
419                return self
420                    .shared
421                    .get(&key)
422                    .map(|id| Value::Obj(Some(*id)))
423                    .ok_or(Error::Malformed("reference to an undefined object"))
424            }
425            1 => {}
426            _ => return Err(Error::Malformed("object marker")),
427        }
428        if self.shared.contains_key(&key) {
429            return Err(Error::Malformed("object defined twice"));
430        }
431        // Register before the fields: an object's own fields may refer back to it.
432        let id = self.push(Object {
433            class: Tag(0),
434            kind: Kind::Shared,
435            chain: Vec::new(),
436            fields: Vec::new(),
437        })?;
438        self.shared.insert(key, id);
439        let mut chain = Vec::new();
440        let mut fields = Vec::new();
441        loop {
442            match self.c.u8()? {
443                0 => {
444                    let tag = Tag(self.c.u32()?);
445                    self.c.u16()?;
446                    chain.push(tag);
447                    fields.extend(self.fields(true, tag)?);
448                }
449                1 => {
450                    chain.push(Tag(self.c.u32()?));
451                    break;
452                }
453                2 => break,
454                _ => return Err(Error::Malformed("object class chain")),
455            }
456            if chain.len() > 64 {
457                return Err(Error::Limit("object class chain too long"));
458            }
459        }
460        let class = chain.first().copied().unwrap_or(Tag(0));
461        fields.extend(self.fields(true, class)?);
462        if let Some(o) = self.objects.get_mut(id) {
463            *o = Object {
464                class,
465                kind: Kind::Shared,
466                chain,
467                fields,
468            };
469        }
470        Ok(Value::Obj(Some(id)))
471    }
472}