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