Skip to main content

c0/
document.rs

1//! Documents: a SYN heading, a body, EOT; and containers of several
2//! documents with an EM tail.
3
4use crate::*;
5use std::borrow::Cow;
6
7/// The heading of a document: keyed units after SYN, in written order.
8/// Lookups take the last value for a duplicate key.
9pub struct Heading<'a> {
10    raw: &'a [u8],
11    pairs: Vec<(&'a [u8], Cow<'a, [u8]>)>,
12    raw_pairs: Vec<(&'a [u8], &'a [u8])>,
13}
14
15impl<'a> Heading<'a> {
16    /// The heading of a document without SYN.
17    pub fn empty() -> Self {
18        Heading {
19            raw: &[],
20            pairs: Vec::new(),
21            raw_pairs: Vec::new(),
22        }
23    }
24
25    /// The heading's bytes (after SYN, before the body).
26    pub fn raw(&self) -> &'a [u8] {
27        self.raw
28    }
29
30    /// (key, value) pairs in written order. A nested-level value is its raw
31    /// `DLE … CAN` bytes; see [`Heading::blob`].
32    pub fn pairs(&self) -> &[(&'a [u8], Cow<'a, [u8]>)] {
33        &self.pairs
34    }
35
36    /// The value for a key (last wins), or `None`.
37    pub fn get(&self, key: &str) -> Option<&[u8]> {
38        let mut found = None;
39        for (k, v) in &self.pairs {
40            if *k == key.as_bytes() {
41                found = Some(v.as_ref());
42            }
43        }
44        found
45    }
46
47    /// Keys in written order.
48    pub fn keys(&self) -> Vec<&'a [u8]> {
49        self.pairs.iter().map(|(k, _)| *k).collect()
50    }
51
52    /// The `shape` key, when present and UTF-8.
53    pub fn shape(&self) -> Option<&str> {
54        self.get("shape").and_then(|v| std::str::from_utf8(v).ok())
55    }
56
57    /// The `version` key as an integer; 1 when absent.
58    pub fn version(&self) -> u32 {
59        self.get("version")
60            .and_then(|v| std::str::from_utf8(v).ok())
61            .and_then(|s| s.parse().ok())
62            .unwrap_or(1)
63    }
64
65    /// Raw unit of the `blob` key (a level), or `None`.
66    pub fn raw_blob(&self) -> Option<&'a [u8]> {
67        let mut found = None;
68        for (k, v) in &self.raw_pairs {
69            if *k == b"blob" {
70                found = Some(*v);
71            }
72        }
73        found
74    }
75
76    /// The blob table, when declared as a nested level.
77    pub fn blob(&self) -> Result<Option<Body<'a>>> {
78        match self.raw_blob() {
79            Some(raw) if is_level(raw) => Body::of_level(raw).map(Some),
80            _ => Ok(None),
81        }
82    }
83
84    pub fn is_empty(&self) -> bool {
85        self.pairs.is_empty()
86    }
87}
88
89/// Parse keyed units after SYN. Returns the heading and the position of
90/// the first body code.
91pub(crate) fn parse_heading(
92    buf: &[u8],
93    mut pos: usize,
94    len: usize,
95) -> Result<(Heading<'_>, usize)> {
96    let hs = pos;
97    let mut pairs = Vec::new();
98    let mut raw_pairs = Vec::new();
99    loop {
100        pos = scan::layout(buf, pos, len);
101        if pos >= len {
102            break;
103        }
104        let b = buf[pos];
105        if b == SOH {
106            let p2 = scan::layout(buf, pos + 1, len);
107            if p2 < len && buf[p2] == RS {
108                break; // a header row begins the body
109            }
110            let ks = p2;
111            let ke = scan::plain(buf, ks, len);
112            if !(ke < len && buf[ke] == US) {
113                return Err(Error::syntax("key without a value (no US)", ke));
114            }
115            let vs = ke + 1;
116            let ve = scan::unit(buf, vs, len)?;
117            let key = trim(&buf[ks..ke]);
118            let rawv = trim(&buf[vs..ve]);
119            if rawv.first() == Some(&ENQ) {
120                return Err(Error::syntax("reference in a heading", vs));
121            }
122            raw_pairs.push((key, rawv));
123            let v = if rawv.first() == Some(&DLE) {
124                Cow::Borrowed(rawv)
125            } else {
126                value(rawv)?
127            };
128            pairs.push((key, v));
129            pos = ve;
130        } else if b == BEL {
131            let p2 = scan::layout(buf, pos + 1, len);
132            if p2 >= len {
133                return Err(Error::end("BEL at end of input", p2));
134            }
135            let b2 = buf[p2];
136            let header_row = b2 == SOH && {
137                let p3 = scan::layout(buf, p2 + 1, len);
138                p3 < len && buf[p3] == RS
139            };
140            if b2 >= 0x20 || b2 == STX || (b2 == SOH && !header_row) {
141                pos = scan::comment(buf, pos, len)?; // a note or a dead key
142            } else {
143                break; // a dead body element begins the body
144            }
145        } else if b >= 0x20 {
146            return Err(Error::syntax("plain text directly after SYN", pos));
147        } else {
148            break;
149        }
150    }
151    Ok((
152        Heading {
153            raw: &buf[hs..pos],
154            pairs,
155            raw_pairs,
156        },
157        pos,
158    ))
159}
160
161// From the start of a body to its end: EOT, SYN, EM or end of input at
162// depth zero, skipping text and levels.
163fn find_body_end(buf: &[u8], mut pos: usize, len: usize) -> Result<usize> {
164    while pos < len {
165        let b = buf[pos];
166        if b >= 0x20 {
167            pos += 1;
168        } else if b == STX {
169            pos = scan::text(buf, pos, len)?;
170        } else if b == DLE {
171            pos = scan::level(buf, pos, len)?;
172        } else if b == EOT || b == SYN || b == EM {
173            return Ok(pos);
174        } else if b == CAN {
175            return Err(Error::syntax("CAN with no open level", pos));
176        } else {
177            pos += 1;
178        }
179    }
180    Ok(pos)
181}
182
183const KNOWN_KEYS: [&[u8]; 3] = [b"shape", b"version", b"blob"];
184const KNOWN_SHAPES: [&str; 5] = ["diff", "stream", "tabular", "document", "key-value"];
185
186/// One C0DATA document: an optional SYN heading, a body, an optional EOT.
187/// [`Document::new`] reads the first document in a buffer; use
188/// [`Container`] for a buffer holding several documents or an EM tail.
189pub struct Document<'a> {
190    buf: &'a [u8],
191    heading: Heading<'a>,
192    body: Body<'a>,
193    start: usize,
194    stop: usize,
195    has_syn: bool,
196    has_eot: bool,
197    warnings: Vec<String>,
198}
199
200impl<'a> Document<'a> {
201    /// Read the document at the start of `buf`.
202    pub fn new(buf: &'a [u8]) -> Result<Self> {
203        Self::at(buf, 0)
204    }
205
206    /// Read the document starting at `start`.
207    pub fn at(buf: &'a [u8], start: usize) -> Result<Self> {
208        let len = buf.len();
209        let mut warnings = Vec::new();
210        let mut pos = scan::layout(buf, start, len);
211        let has_syn = pos < len && buf[pos] == SYN;
212        let heading = if has_syn {
213            let (h, p) = parse_heading(buf, pos + 1, len)?;
214            pos = p;
215            h
216        } else {
217            warnings.push("no SYN at the start of the document".to_string());
218            Heading::empty()
219        };
220        let body_start = pos;
221        let body_end = find_body_end(buf, pos, len)?;
222        let body = Body::slice(buf, body_start, body_end)?;
223        pos = scan::layout(buf, body_end, len);
224        let has_eot = pos < len && buf[pos] == EOT;
225        if has_eot {
226            pos += 1;
227        } else if heading.shape() != Some("stream") {
228            warnings.push("no EOT at the end of the document".to_string());
229        }
230        for k in heading.keys() {
231            if !KNOWN_KEYS.contains(&k) {
232                warnings.push(format!(
233                    "unknown heading key '{}'",
234                    String::from_utf8_lossy(k)
235                ));
236            }
237        }
238        if let Some(shape) = heading.get("shape") {
239            let known = std::str::from_utf8(shape).is_ok_and(|s| KNOWN_SHAPES.contains(&s));
240            if !known {
241                warnings.push(format!(
242                    "unknown shape '{}'",
243                    String::from_utf8_lossy(shape)
244                ));
245            }
246        }
247        Ok(Document {
248            buf,
249            heading,
250            body,
251            start,
252            stop: pos,
253            has_syn,
254            has_eot,
255            warnings,
256        })
257    }
258
259    pub fn heading(&self) -> &Heading<'a> {
260        &self.heading
261    }
262
263    pub fn body(&self) -> &Body<'a> {
264        &self.body
265    }
266
267    /// Offset where the document begins.
268    pub fn start(&self) -> usize {
269        self.start
270    }
271
272    /// Offset just past EOT (or past the body when there is none).
273    pub fn stop(&self) -> usize {
274        self.stop
275    }
276
277    pub fn has_syn(&self) -> bool {
278        self.has_syn
279    }
280
281    pub fn has_eot(&self) -> bool {
282        self.has_eot
283    }
284
285    /// Loud and ordinary warnings met while reading; never an error.
286    pub fn warnings(&self) -> &[String] {
287        &self.warnings
288    }
289
290    /// The document's bytes.
291    pub fn raw(&self) -> &'a [u8] {
292        &self.buf[self.start..self.stop]
293    }
294
295    pub fn shape(&self) -> Option<&str> {
296        self.heading.shape()
297    }
298
299    // Convenience accessors over the body.
300
301    pub fn name(&self) -> &'a [u8] {
302        self.body.name()
303    }
304
305    pub fn files(&self) -> &[FileView<'a>] {
306        self.body.files()
307    }
308
309    pub fn groups(&self) -> impl Iterator<Item = &Group<'a>> + '_ {
310        self.body.groups()
311    }
312
313    pub fn group_count(&self) -> usize {
314        self.body.group_count()
315    }
316
317    pub fn group(&self, i: usize) -> &Group<'a> {
318        self.body.group(i)
319    }
320
321    pub fn group_by_name(&self, name: &str) -> Result<&Group<'a>> {
322        self.body.group_by_name(name)
323    }
324
325    pub fn group_names(&self) -> Vec<&'a [u8]> {
326        self.body.group_names()
327    }
328
329    pub fn records(&self) -> &[Record<'a>] {
330        self.body.records()
331    }
332}
333
334/// A file or message: one or more documents and an optional raw tail
335/// after EM.
336pub struct Container<'a> {
337    documents: Vec<Document<'a>>,
338    tail: &'a [u8],
339    has_em: bool,
340    warnings: Vec<String>,
341}
342
343impl<'a> Container<'a> {
344    pub fn new(buf: &'a [u8]) -> Result<Self> {
345        let len = buf.len();
346        let mut documents: Vec<Document<'a>> = Vec::new();
347        let mut tail: &'a [u8] = &[];
348        let mut has_em = false;
349        let mut warnings = Vec::new();
350        let mut pos = scan::layout(buf, 0, len);
351        while pos < len {
352            if buf[pos] == EM {
353                has_em = true;
354                tail = &buf[pos + 1..];
355                break;
356            }
357            let doc = Document::at(buf, pos)?;
358            pos = scan::layout(buf, doc.stop, len);
359            if !documents.is_empty() && doc.heading.raw_blob().is_some() {
360                warnings.push(format!(
361                    "blob table in heading of document {} ignored",
362                    documents.len() + 1
363                ));
364            }
365            documents.push(doc);
366            if pos < len && buf[pos] != SYN && buf[pos] != EM {
367                return Err(Error::syntax("unexpected byte after EOT", pos));
368            }
369        }
370        if has_em
371            && documents
372                .first()
373                .is_none_or(|d| d.heading.raw_blob().is_none())
374        {
375            warnings.push("EM with no blob table: the region is unaddressable".to_string());
376        }
377        Ok(Container {
378            documents,
379            tail,
380            has_em,
381            warnings,
382        })
383    }
384
385    /// The documents, in order.
386    pub fn documents(&self) -> &[Document<'a>] {
387        &self.documents
388    }
389
390    /// The first document, if the buffer holds one.
391    pub fn first(&self) -> Option<&Document<'a>> {
392        self.documents.first()
393    }
394
395    /// The raw region after EM (empty when there is no EM).
396    pub fn tail(&self) -> &'a [u8] {
397        self.tail
398    }
399
400    pub fn has_em(&self) -> bool {
401        self.has_em
402    }
403
404    /// Container-level loud warnings (a `blob` key in a later heading, EM
405    /// with no blob table).
406    pub fn warnings(&self) -> &[String] {
407        &self.warnings
408    }
409
410    /// The blob table from the first document's heading.
411    pub fn blob(&self) -> Result<Option<Body<'a>>> {
412        match self.documents.first() {
413            Some(d) => d.heading.blob(),
414            None => Ok(None),
415        }
416    }
417
418    /// Bytes of a named blob from the tail, or `None` when the table does
419    /// not declare it (or its row is unusable).
420    pub fn blob_bytes(&self, name: &str) -> Result<Option<&'a [u8]>> {
421        let Some(table) = self.blob()? else {
422            return Ok(None);
423        };
424        let Some(g) = table.groups().next() else {
425            return Ok(None);
426        };
427        let ni = g.column("name").unwrap_or(0);
428        let oi = g.column("offset").unwrap_or(1);
429        let li = g.column("length").unwrap_or(2);
430        let mut found = None;
431        for r in g.records() {
432            if r.value(ni)?.as_ref() != name.as_bytes() {
433                continue;
434            }
435            let off = parse_usize(&r.value(oi)?);
436            let len = parse_usize(&r.value(li)?);
437            if let (Some(off), Some(len)) = (off, len) {
438                found = self.tail.get(off..off + len);
439            }
440        }
441        Ok(found)
442    }
443}
444
445fn parse_usize(v: &[u8]) -> Option<usize> {
446    std::str::from_utf8(v).ok()?.trim().parse().ok()
447}