Skip to main content

c0/
body.rs

1//! Zero-copy index of a document body: files, groups, header rows and
2//! records, each a slice into the original buffer.
3
4use crate::*;
5use std::borrow::Cow;
6use std::fmt;
7
8/// A document body: the bytes between a heading and EOT, or the inside of
9/// a nested level. Indexes files, groups, header rows and records once;
10/// everything it returns borrows the original buffer.
11///
12/// Records before the first GS of a file form an unnamed group; records
13/// and groups before the first FS form an unnamed file.
14pub struct Body<'a> {
15    buf: &'a [u8],
16    start: usize,
17    stop: usize,
18    files: Vec<FileView<'a>>,
19}
20
21impl<'a> Body<'a> {
22    /// Index a whole buffer as a body (no SYN, no EOT).
23    pub fn new(buf: &'a [u8]) -> Result<Self> {
24        Self::slice(buf, 0, buf.len())
25    }
26
27    /// Index `buf[start..stop]` as a body.
28    pub fn slice(buf: &'a [u8], start: usize, stop: usize) -> Result<Self> {
29        let mut body = Body {
30            buf,
31            start,
32            stop,
33            files: Vec::new(),
34        };
35        body.index()?;
36        Ok(body)
37    }
38
39    /// The contents of a nested level: `raw` is a unit holding `DLE … CAN`
40    /// (layout at its edges allowed).
41    pub fn of_level(raw: &'a [u8]) -> Result<Self> {
42        let t = trim(raw);
43        if t.first() != Some(&DLE) {
44            return Err(Error::other("unit is not a nested level"));
45        }
46        let stop = scan::level(t, 0, t.len())?;
47        Self::slice(t, 1, stop - 1)
48    }
49
50    /// The buffer the body indexes.
51    pub fn buf(&self) -> &'a [u8] {
52        self.buf
53    }
54
55    /// Offset of the body's first byte in the buffer.
56    pub fn start(&self) -> usize {
57        self.start
58    }
59
60    /// Offset just past the body in the buffer.
61    pub fn stop(&self) -> usize {
62        self.stop
63    }
64
65    /// The body's bytes.
66    pub fn raw(&self) -> &'a [u8] {
67        &self.buf[self.start..self.stop]
68    }
69
70    /// The files of the body, in order. There is always at least one (the
71    /// unnamed file, when the body has no FS).
72    pub fn files(&self) -> &[FileView<'a>] {
73        &self.files
74    }
75
76    /// All groups of all files, in order.
77    pub fn groups(&self) -> impl Iterator<Item = &Group<'a>> + '_ {
78        self.files.iter().flat_map(|f| f.groups.iter())
79    }
80
81    /// Groups of the first file.
82    pub fn group_count(&self) -> usize {
83        self.first_file().groups.len()
84    }
85
86    /// Group `i` of the first file.
87    pub fn group(&self, i: usize) -> &Group<'a> {
88        &self.first_file().groups[i]
89    }
90
91    /// The first file's group named `name`.
92    pub fn group_by_name(&self, name: &str) -> Result<&Group<'a>> {
93        self.first_file().group(name)
94    }
95
96    /// Names of the first file's groups.
97    pub fn group_names(&self) -> Vec<&'a [u8]> {
98        self.first_file().groups.iter().map(|g| g.name()).collect()
99    }
100
101    /// Name of the first file (empty when the body has no FS).
102    pub fn name(&self) -> &'a [u8] {
103        self.first_file().name()
104    }
105
106    /// Records of the body when it is a bare record stream (no FS, no
107    /// GS): the unnamed group's records.
108    pub fn records(&self) -> &[Record<'a>] {
109        match self.first_file().groups.first() {
110            Some(g) => &g.records,
111            None => &[],
112        }
113    }
114
115    pub fn record_count(&self) -> usize {
116        self.records().len()
117    }
118
119    pub fn record(&self, i: usize) -> Record<'a> {
120        self.records()[i]
121    }
122
123    /// Whether the body is just records: one unnamed file, at most one
124    /// unnamed group.
125    pub fn bare(&self) -> bool {
126        self.files.len() == 1
127            && self.files[0].name().is_empty()
128            && self.files[0].groups.len() <= 1
129            && self.files[0].groups.first().is_none_or(|g| g.depth == 0)
130    }
131
132    fn first_file(&self) -> &FileView<'a> {
133        &self.files[0]
134    }
135
136    // ------------------------------------------------------------------
137
138    fn index(&mut self) -> Result<()> {
139        let buf = self.buf;
140        let stop = self.stop;
141        let mut pos = scan::layout(buf, self.start, stop);
142        // leading unnamed file
143        let mut file = FileView::new(buf, 0, 0);
144        pos = index_part(buf, pos, stop, &mut file, false)?;
145        let fs_follows = pos < stop && (buf[pos] == FS || dead_fs(buf, pos, stop));
146        let mut unnamed = Some(file);
147        if !(unnamed.as_ref().is_some_and(|f| f.groups.is_empty()) && fs_follows) {
148            self.files.extend(unnamed.take());
149        }
150        while pos < stop {
151            let mut b = buf[pos];
152            let mut dead = false;
153            if b == BEL && dead_fs(buf, pos, stop) {
154                dead = true;
155                pos = scan::layout(buf, pos + 1, stop);
156                b = FS;
157            }
158            if b != FS {
159                break;
160            }
161            pos = scan::layout(buf, pos + 1, stop);
162            let ns = pos;
163            pos = scan::plain(buf, pos, stop);
164            if dead {
165                // a dead file line is read as if absent: what follows belongs
166                // to the file before it, its leading items to that file's
167                // last group
168                if self.files.is_empty() {
169                    self.files.extend(unnamed.take());
170                }
171                let i = self.files.len() - 1;
172                pos = index_part(buf, pos, stop, &mut self.files[i], true)?;
173            } else {
174                let mut f = FileView::new(buf, ns, pos);
175                pos = index_part(buf, pos, stop, &mut f, false)?;
176                self.files.push(f);
177            }
178        }
179        if self.files.is_empty() {
180            self.files.push(FileView::new(buf, 0, 0));
181        }
182        Ok(())
183    }
184}
185
186fn dead_fs(buf: &[u8], pos: usize, stop: usize) -> bool {
187    if !(pos < stop && buf[pos] == BEL) {
188        return false;
189    }
190    let p2 = scan::layout(buf, pos + 1, stop);
191    p2 < stop && buf[p2] == FS
192}
193
194fn has_content(g: &Group<'_>) -> bool {
195    g.header.is_some() || !g.records.is_empty()
196}
197
198// Index one part: leading items (the unnamed group, or the file's last
199// group when continuing after a dead file line), then groups. Returns the
200// position of the next FS (or dead FS), or stop.
201fn index_part<'a>(
202    buf: &'a [u8],
203    mut pos: usize,
204    stop: usize,
205    file: &mut FileView<'a>,
206    cont: bool,
207) -> Result<usize> {
208    // the group a dead group line's contents attach to: an index into
209    // file.groups, or the still-pending unnamed group
210    let mut current: Option<usize> = None;
211    let mut pending: Option<Group<'a>> = None;
212    if cont && !file.groups.is_empty() {
213        let i = file.groups.len() - 1;
214        pos = index_group_contents(buf, pos, stop, &mut file.groups[i])?;
215        current = Some(i);
216    } else {
217        let mut g = Group::new(buf, 0, 0, 0);
218        pos = index_group_contents(buf, pos, stop, &mut g)?;
219        if has_content(&g) {
220            file.groups.push(g);
221            current = Some(file.groups.len() - 1);
222        } else {
223            pending = Some(g);
224        }
225    }
226    while pos < stop {
227        let mut b = buf[pos];
228        let mut dead = false;
229        if b == BEL {
230            let p2 = scan::layout(buf, pos + 1, stop);
231            if p2 < stop && buf[p2] == GS {
232                dead = true;
233                pos = p2;
234                b = GS;
235            } else {
236                break;
237            }
238        }
239        if b != GS {
240            break;
241        }
242        let mut depth = 0;
243        while pos < stop && (buf[pos] == GS || is_layout(buf[pos])) {
244            if buf[pos] == GS {
245                depth += 1;
246            }
247            pos += 1;
248        }
249        let ns = pos;
250        pos = scan::plain(buf, pos, stop);
251        let ne = pos;
252        if dead {
253            // a dead group line: what follows still belongs to the group before
254            match current {
255                Some(i) => pos = index_group_contents(buf, pos, stop, &mut file.groups[i])?,
256                None => {
257                    if let Some(mut g) = pending.take() {
258                        pos = index_group_contents(buf, pos, stop, &mut g)?;
259                        if has_content(&g) {
260                            file.groups.push(g);
261                            current = Some(file.groups.len() - 1);
262                        } else {
263                            pending = Some(g);
264                        }
265                    }
266                }
267            }
268        } else {
269            let mut grp = Group::new(buf, depth, ns, ne);
270            pos = index_group_contents(buf, pos, stop, &mut grp)?;
271            file.groups.push(grp);
272            current = Some(file.groups.len() - 1);
273        }
274    }
275    Ok(pos)
276}
277
278// After a group label (or at the start of a part): notes, header row,
279// items. Returns the position of the next GS/FS/dead GS/FS or stop.
280fn index_group_contents<'a>(
281    buf: &'a [u8],
282    mut pos: usize,
283    stop: usize,
284    grp: &mut Group<'a>,
285) -> Result<usize> {
286    let mut first_item = true;
287    loop {
288        pos = scan::layout(buf, pos, stop);
289        if pos >= stop {
290            break;
291        }
292        let b = buf[pos];
293        if b == RS {
294            first_item = false;
295            let rs = pos + 1;
296            pos = scan::record_end(buf, rs, stop)?;
297            grp.records
298                .push(Record::new(buf, rs, trim_end(buf, rs, pos)));
299        } else if b == SOH {
300            let p2 = scan::layout(buf, pos + 1, stop);
301            if !(p2 < stop && buf[p2] == RS) {
302                return Err(Error::syntax("keyed unit outside a record", pos));
303            }
304            if !first_item {
305                return Err(Error::syntax(
306                    "header row not at the start of its group",
307                    pos,
308                ));
309            }
310            first_item = false;
311            let hs = p2 + 1;
312            pos = scan::record_end(buf, hs, stop)?;
313            grp.header = Some(Record::new(buf, hs, trim_end(buf, hs, pos)));
314        } else if b == ETB {
315            pos = scan::plain(buf, scan::layout(buf, pos + 1, stop), stop);
316        } else if b == BEL {
317            let p2 = scan::layout(buf, pos + 1, stop);
318            if p2 >= stop || buf[p2] >= 0x20 || buf[p2] == STX {
319                pos = scan::comment(buf, pos, stop)?; // a note
320            } else if buf[p2] == RS || buf[p2] == SOH {
321                pos = scan::comment(buf, pos, stop)?; // dead record / header row
322                if buf[p2] == RS {
323                    first_item = false;
324                }
325            } else {
326                break; // dead GS or FS: the caller's business
327            }
328        } else {
329            break;
330        }
331    }
332    Ok(pos)
333}
334
335#[inline]
336fn trim_end(buf: &[u8], start: usize, mut stop: usize) -> usize {
337    while stop > start && is_layout(buf[stop - 1]) {
338        stop -= 1;
339    }
340    stop
341}
342
343/// A file within a body: its name and groups.
344pub struct FileView<'a> {
345    buf: &'a [u8],
346    name_start: usize,
347    name_end: usize,
348    groups: Vec<Group<'a>>,
349}
350
351impl<'a> FileView<'a> {
352    fn new(buf: &'a [u8], name_start: usize, name_end: usize) -> Self {
353        FileView {
354            buf,
355            name_start,
356            name_end,
357            groups: Vec::new(),
358        }
359    }
360
361    /// The file's name (empty for the unnamed file).
362    pub fn name(&self) -> &'a [u8] {
363        trim(&self.buf[self.name_start..self.name_end])
364    }
365
366    /// The file's groups, in order.
367    pub fn groups(&self) -> &[Group<'a>] {
368        &self.groups
369    }
370
371    /// The group named `name`.
372    pub fn group(&self, name: &str) -> Result<&Group<'a>> {
373        self.groups
374            .iter()
375            .find(|g| g.name() == name.as_bytes())
376            .ok_or_else(|| Error::Key(format!("No group named '{name}'")))
377    }
378}
379
380/// A group: its depth (GS count; 0 for the unnamed leading group), name,
381/// optional header row and records.
382pub struct Group<'a> {
383    buf: &'a [u8],
384    depth: usize,
385    name_start: usize,
386    name_end: usize,
387    header: Option<Record<'a>>,
388    records: Vec<Record<'a>>,
389}
390
391/// A group read as a table is itself.
392pub type Table<'a> = Group<'a>;
393
394impl<'a> Group<'a> {
395    fn new(buf: &'a [u8], depth: usize, name_start: usize, name_end: usize) -> Self {
396        Group {
397            buf,
398            depth,
399            name_start,
400            name_end,
401            header: None,
402            records: Vec::new(),
403        }
404    }
405
406    /// The group's name (empty for the unnamed leading group).
407    pub fn name(&self) -> &'a [u8] {
408        trim(&self.buf[self.name_start..self.name_end])
409    }
410
411    /// GS repetitions: 1 for `␝g`, 2 for `␝␝g`; 0 for the unnamed group.
412    pub fn depth(&self) -> usize {
413        self.depth
414    }
415
416    /// Whether the group has a header row.
417    pub fn has_header(&self) -> bool {
418        self.header.is_some()
419    }
420
421    /// The header row as a record, if any.
422    pub fn header_row(&self) -> Option<Record<'a>> {
423        self.header
424    }
425
426    /// Header names, or an empty vector.
427    pub fn headers(&self) -> Vec<&'a [u8]> {
428        match &self.header {
429            Some(h) => h.fields().into_iter().map(trim).collect(),
430            None => Vec::new(),
431        }
432    }
433
434    pub fn header_count(&self) -> usize {
435        self.header.map_or(0, |h| h.field_count())
436    }
437
438    pub fn header(&self, i: usize) -> &'a [u8] {
439        self.headers()[i]
440    }
441
442    pub fn record_count(&self) -> usize {
443        self.records.len()
444    }
445
446    pub fn record(&self, i: usize) -> Record<'a> {
447        self.records[i]
448    }
449
450    /// The records, in order.
451    pub fn records(&self) -> &[Record<'a>] {
452        &self.records
453    }
454
455    /// Index of a header name, or `None`.
456    pub fn column(&self, name: &str) -> Option<usize> {
457        self.headers().iter().position(|h| *h == name.as_bytes())
458    }
459}
460
461/// A key and its logical value, from a keyed record.
462pub type Pair<'a> = (&'a [u8], Cow<'a, [u8]>);
463
464/// A record: positional or keyed. Copyable, zero-copy accessors.
465#[derive(Clone, Copy, PartialEq, Eq)]
466pub struct Record<'a> {
467    buf: &'a [u8],
468    start: usize,
469    end: usize,
470}
471
472impl fmt::Debug for Record<'_> {
473    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474        f.debug_struct("Record")
475            .field("raw", &String::from_utf8_lossy(self.raw()))
476            .finish()
477    }
478}
479
480impl<'a> Record<'a> {
481    pub(crate) fn new(buf: &'a [u8], start: usize, end: usize) -> Self {
482        Record { buf, start, end }
483    }
484
485    /// Raw bytes of the record (after its RS).
486    #[inline]
487    pub fn raw(&self) -> &'a [u8] {
488        &self.buf[self.start..self.end]
489    }
490
491    /// Whether the record is keyed (its first live or dead unit is an SOH).
492    pub fn keyed(&self) -> bool {
493        let buf = self.buf;
494        let end = self.end;
495        let mut p = scan::layout(buf, self.start, end);
496        while p < end && buf[p] == BEL {
497            let p2 = scan::layout(buf, p + 1, end);
498            if p2 < end && buf[p2] == SOH {
499                return true;
500            }
501            if p2 < end && buf[p2] < 0x20 && buf[p2] != STX && buf[p2] != DLE {
502                break;
503            }
504            match scan::comment(buf, p, end) {
505                Ok(n) => p = scan::layout(buf, n, end),
506                Err(_) => return false,
507            }
508        }
509        p < end && buf[p] == SOH
510    }
511
512    // ---- positional -----------------------------------------------------
513
514    /// Raw slice of unit `n` (layout at its edges included); empty when
515    /// there is no such unit.
516    pub fn field(&self, n: usize) -> &'a [u8] {
517        self.unit_ranges()
518            .get(n)
519            .map_or(&[][..], |&(s, e)| &self.buf[s..e])
520    }
521
522    /// Number of positional units (0 for a keyed record).
523    pub fn field_count(&self) -> usize {
524        self.unit_ranges().len()
525    }
526
527    /// Raw slices of every unit.
528    pub fn fields(&self) -> Vec<&'a [u8]> {
529        self.unit_ranges()
530            .into_iter()
531            .map(|(s, e)| &self.buf[s..e])
532            .collect()
533    }
534
535    /// Logical value of unit `n`: text decoded, layout trimmed.
536    pub fn value(&self, n: usize) -> Result<Cow<'a, [u8]>> {
537        value(self.field(n))
538    }
539
540    /// Logical values of every unit.
541    pub fn values(&self) -> Result<Vec<Cow<'a, [u8]>>> {
542        self.fields().into_iter().map(value).collect()
543    }
544
545    /// Unit `n` as a nested level.
546    pub fn level(&self, n: usize) -> Result<Body<'a>> {
547        Body::of_level(self.field(n))
548    }
549
550    /// Unit `n` as a flat list: a level holding exactly one positional
551    /// record (an empty level is the empty list).
552    pub fn list(&self, n: usize) -> Result<Vec<Cow<'a, [u8]>>> {
553        let body = self.level(n)?;
554        let recs = body.records();
555        if recs.is_empty() && body.bare() {
556            return Ok(Vec::new());
557        }
558        if !(recs.len() == 1 && body.bare()) {
559            return Err(Error::other(format!(
560                "level is not a list ({} records)",
561                recs.len()
562            )));
563        }
564        if body.group_count() > 0 && body.group(0).has_header() {
565            return Err(Error::other("level is not a list (header row)"));
566        }
567        if recs[0].keyed() {
568            return Err(Error::other("level is not a list (keyed record)"));
569        }
570        recs[0].values()
571    }
572
573    /// Unit `n` as a reference.
574    pub fn reference(&self, n: usize) -> Result<Reference<'a>> {
575        Reference::parse(self.field(n))
576    }
577
578    // ---- keyed ---------------------------------------------------------
579
580    /// Keys in written order (duplicates included).
581    pub fn keys(&self) -> Vec<&'a [u8]> {
582        self.keyed_ranges()
583            .unwrap_or_default()
584            .into_iter()
585            .map(|(k, _, _)| k)
586            .collect()
587    }
588
589    /// (key, logical value) pairs in written order.
590    pub fn pairs(&self) -> Result<Vec<Pair<'a>>> {
591        self.keyed_ranges()?
592            .into_iter()
593            .map(|(k, vs, ve)| Ok((k, value(&self.buf[vs..ve])?)))
594            .collect()
595    }
596
597    /// Raw unit for a key (last wins), or `None`.
598    pub fn get_raw(&self, key: &str) -> Option<&'a [u8]> {
599        let mut found = None;
600        for (k, vs, ve) in self.keyed_ranges().unwrap_or_default() {
601            if k == key.as_bytes() {
602                found = Some(&self.buf[vs..ve]);
603            }
604        }
605        found
606    }
607
608    /// Logical value for a key (last wins), or `None`.
609    pub fn get(&self, key: &str) -> Result<Option<Cow<'a, [u8]>>> {
610        self.get_raw(key).map(value).transpose()
611    }
612
613    /// The value for a key as a nested level, or `None`.
614    pub fn get_level(&self, key: &str) -> Result<Option<Body<'a>>> {
615        self.get_raw(key).map(Body::of_level).transpose()
616    }
617
618    pub fn has_key(&self, key: &str) -> bool {
619        self.get_raw(key).is_some()
620    }
621
622    // ---- internals ------------------------------------------------------
623
624    // (start, end) of each positional unit. A record comes from an indexed
625    // body, whose text and levels were already scanned, so the unit scan
626    // cannot fail; should it, the unit runs to the record's end.
627    fn unit_ranges(&self) -> Vec<(usize, usize)> {
628        let buf = self.buf;
629        let end = self.end;
630        let mut out = Vec::new();
631        if self.keyed() {
632            return out;
633        }
634        let mut pos = scan::layout(buf, self.start, end);
635        let mut unit_start = self.start;
636        loop {
637            pos = scan::unit(buf, pos, end).unwrap_or(end);
638            out.push((unit_start, pos));
639            if !(pos < end && buf[pos] == US) {
640                break;
641            }
642            pos += 1;
643            unit_start = pos;
644        }
645        out
646    }
647
648    // (key, value start, value end) per live keyed unit.
649    fn keyed_ranges(&self) -> Result<Vec<(&'a [u8], usize, usize)>> {
650        let buf = self.buf;
651        let end = self.end;
652        let mut out = Vec::new();
653        let mut pos = scan::layout(buf, self.start, end);
654        while pos < end {
655            let b = buf[pos];
656            if b == SOH {
657                let ks = scan::layout(buf, pos + 1, end);
658                let ke = scan::plain(buf, ks, end);
659                if !(ke < end && buf[ke] == US) {
660                    return Err(Error::syntax("key without a value (no US)", ke));
661                }
662                let vs = ke + 1;
663                let ve = scan::unit(buf, vs, end)?;
664                out.push((trim(&buf[ks..ke]), vs, ve));
665                pos = ve;
666            } else if b == BEL {
667                pos = scan::comment(buf, pos, end)?;
668            } else if is_layout(b) {
669                pos += 1;
670            } else {
671                break;
672            }
673        }
674        Ok(out)
675    }
676}
677
678/// A reference: a group name, or a path of two or three segments
679/// (group, record id, field name).
680#[derive(Debug, Clone, PartialEq, Eq)]
681pub struct Reference<'a> {
682    path: Vec<Cow<'a, [u8]>>,
683}
684
685impl<'a> Reference<'a> {
686    /// Parse a raw unit holding `ENQ name` or `ENQ STX a US b [US c] ETX`.
687    pub fn parse(raw: &'a [u8]) -> Result<Self> {
688        let t = trim(raw);
689        if t.first() != Some(&ENQ) {
690            return Err(Error::other("unit is not a reference"));
691        }
692        let p = scan::layout(t, 1, t.len());
693        if p < t.len() && t[p] == STX {
694            let stop = scan::text(t, p, t.len())?;
695            let inside = decode_text(&t[p + 1..stop - 1]);
696            let segs: Vec<Cow<'a, [u8]>> = match inside {
697                Cow::Borrowed(s) => s.split(|&b| b == US).map(Cow::Borrowed).collect(),
698                Cow::Owned(v) => v
699                    .split(|&b| b == US)
700                    .map(|s| Cow::Owned(s.to_vec()))
701                    .collect(),
702            };
703            if segs.len() > 3 {
704                return Err(Error::syntax(
705                    "reference path with more than three segments",
706                    p,
707                ));
708            }
709            if segs.iter().any(|s| s.is_empty()) {
710                return Err(Error::syntax("reference path with an empty segment", p));
711            }
712            if segs.iter().any(|s| !is_name(s)) {
713                return Err(Error::syntax("reference path segment is not a name", p));
714            }
715            Ok(Reference { path: segs })
716        } else {
717            let name = trim(&t[p..]);
718            if name.is_empty() {
719                return Err(Error::syntax("reference without a name", p));
720            }
721            Ok(Reference {
722                path: vec![Cow::Borrowed(name)],
723            })
724        }
725    }
726
727    /// The segments: group, then record id and field name when present.
728    pub fn path(&self) -> &[Cow<'a, [u8]>] {
729        &self.path
730    }
731
732    pub fn group(&self) -> &[u8] {
733        &self.path[0]
734    }
735
736    pub fn record(&self) -> Option<&[u8]> {
737        self.path.get(1).map(|s| s.as_ref())
738    }
739
740    pub fn field(&self) -> Option<&[u8]> {
741        self.path.get(2).map(|s| s.as_ref())
742    }
743
744    /// Whether the reference names a whole group.
745    pub fn is_group(&self) -> bool {
746        self.path.len() == 1
747    }
748}