Skip to main content

c0/
builder.rs

1//! Writer for canonical compact form.
2
3use crate::*;
4
5/// Writes C0DATA in canonical compact form.
6///
7/// ```
8/// let buf = c0::Builder::build(|b| {
9///     b.syn().heading("schema", "ledger");
10///     b.group("users", Some(&["name", "amount"]));
11///     b.record(&["Alice", "1502.30"]);
12///     b.record(&["Bob", "340.00"]);
13///     b.eot();
14/// });
15/// ```
16///
17/// Two layers. The primitives are one method per code (`fs`, `gs`, `rs`,
18/// `us`, `sub`, `soh`, `dle`, `can`, `bel`, `enq`, `syn`, `eot`, `etb`,
19/// `em`); each
20/// writes its code and, when given, what grammatically follows it, so a
21/// chain reads like the bytes. Rust has no optional arguments, so the codes
22/// that may stand bare come in two spellings: the bare code (`rs()`, `us()`,
23/// `gs()`, `soh()`, `bel()`, `etb()`) and the code with what follows it
24/// (`rs_value`, `us_value`, `gs_name`, `soh_key`, `bel_note`,
25/// `etb_payload`). `sub` is always bare: the element after the next
26/// separator is subordinate to the one before it, before GS a subsection
27/// (`␚␝s`), before US a sub-unit (`old␚␟new`). A reference is `enq(name)`
28/// or `enq_level(|b| …)`, a pattern:
29///
30/// ```
31/// let buf = c0::Builder::build(|b| {
32///     b.rs_value("Alice").us_value("1502.30");          // ␞Alice␟1502.30
33///     b.rs().soh_key("host").us_value("localhost");     // ␞␁host␟localhost
34///     b.bel().gs_name("old");                           // ␇␝old: a dead group
35///     b.sub().gs_name("intro");                         // ␚␝intro: a subsection (depth 2)
36///     b.rs_value("old").sub().us_value("new");          // ␞old␚␟new: new is a sub-unit of old
37///     b.rs().enq("tags").us().enq_level(|b| {           // ␞␅tags␟␅␐␝tags␞001␘
38///         b.gs_name("tags").rs_value("001");
39///     });
40/// });
41/// ```
42///
43/// The composed methods (`file`, `group`, `header`, `record`, `field`,
44/// `map`, `key`, `level`, `list`, `reference`, `sub_unit`, `note`, …) are
45/// built on the
46/// primitives and cannot write ill-formed output. The primitives write what
47/// you spell; well-formedness is then yours to keep. Both layers share the
48/// record state, so they mix.
49///
50/// Values are written in their one spelling: plain when they can be, text
51/// (`STX … ETX`, seven codes escaped) otherwise; they accept any
52/// `AsRef<[u8]>` and are byte-transparent. Keyed records ([`map`], [`key`])
53/// keep the order given. Nested levels ([`level`], [`list`], [`key_level`])
54/// open with DLE and close with CAN. Names (file and group labels, keys,
55/// header names, pattern steps, commit payloads) are identifiers: a
56/// name with a byte below 0x20 or edge whitespace panics.
57///
58/// [`map`]: Builder::map
59/// [`key`]: Builder::key
60/// [`level`]: Builder::level
61/// [`list`]: Builder::list
62/// [`key_level`]: Builder::key_level
63#[derive(Default)]
64pub struct Builder {
65    buf: Vec<u8>,
66    in_record: bool,
67    units: usize,
68    stack: Vec<(bool, usize)>,
69}
70
71impl Builder {
72    pub fn new() -> Self {
73        Builder::default()
74    }
75
76    /// Build a buffer by driving a fresh builder, returning its bytes.
77    pub fn build<F: FnOnce(&mut Builder)>(f: F) -> Vec<u8> {
78        let mut b = Builder::new();
79        f(&mut b);
80        b.into_bytes()
81    }
82
83    /// The bytes built so far.
84    #[inline]
85    pub fn as_bytes(&self) -> &[u8] {
86        &self.buf
87    }
88
89    /// Consume the builder, returning the built buffer.
90    #[inline]
91    pub fn into_bytes(self) -> Vec<u8> {
92        self.buf
93    }
94
95    // ---- primitives: one method per code ---------------------------------
96
97    /// FS and a file name. Ends any open record.
98    pub fn fs(&mut self, name: &str) -> &mut Self {
99        self.end_record();
100        self.buf.push(FS);
101        self.name(name);
102        self
103    }
104
105    /// A bare GS: a group with an empty name (`gs().gs_name("b")` is two
106    /// groups, `""` then `b`). Ends any open record.
107    pub fn gs(&mut self) -> &mut Self {
108        self.end_record();
109        self.buf.push(GS);
110        self
111    }
112
113    /// GS and a group name. Ends any open record.
114    pub fn gs_name(&mut self, name: &str) -> &mut Self {
115        self.gs();
116        self.name(name);
117        self
118    }
119
120    /// `depth − 1` SUB, GS and a group name: `gs_name_at("s", 2)` is
121    /// `␚␝s`, a subsection. Ends any open record.
122    pub fn gs_name_at(&mut self, name: &str, depth: usize) -> &mut Self {
123        assert!(depth >= 1, "a group is at depth one or deeper");
124        self.end_record();
125        for _ in 1..depth {
126            self.buf.push(SUB);
127        }
128        self.buf.push(GS);
129        self.name(name);
130        self
131    }
132
133    /// A bare RS: opens a record with no units yet.
134    pub fn rs(&mut self) -> &mut Self {
135        self.buf.push(RS);
136        self.in_record = true;
137        self.units = 0;
138        self
139    }
140
141    /// RS and the record's first value.
142    pub fn rs_value(&mut self, value: impl AsRef<[u8]>) -> &mut Self {
143        self.rs();
144        self.first_value(value.as_ref());
145        self
146    }
147
148    /// A bare US: the next unit of the record is empty, or is what follows
149    /// (a level, a reference).
150    pub fn us(&mut self) -> &mut Self {
151        self.buf.push(US);
152        self.units += 1;
153        self
154    }
155
156    /// US and the value that follows it.
157    pub fn us_value(&mut self, value: impl AsRef<[u8]>) -> &mut Self {
158        self.buf.push(US);
159        write_value(&mut self.buf, value.as_ref());
160        self.units += 1;
161        self
162    }
163
164    /// SUB: the element after the next separator is subordinate to the one
165    /// before it, at that code's grain: before GS a subsection (`␚␝s`, one
166    /// SUB per level), before US a sub-unit (`old␚␟new`). Does not change
167    /// the unit count.
168    pub fn sub(&mut self) -> &mut Self {
169        self.buf.push(SUB);
170        self
171    }
172
173    /// A bare SOH. Before `rs` it opens a header row.
174    pub fn soh(&mut self) -> &mut Self {
175        self.buf.push(SOH);
176        self
177    }
178
179    /// SOH and a key. The key's value follows as `us_value`.
180    pub fn soh_key(&mut self, name: &str) -> &mut Self {
181        self.buf.push(SOH);
182        self.name(name);
183        self
184    }
185
186    /// DLE: open a nested level. Inside, the builder is at the top of a
187    /// fresh body; the record state is restored by [`can`].
188    ///
189    /// [`can`]: Builder::can
190    pub fn dle(&mut self) -> &mut Self {
191        self.stack.push((self.in_record, self.units));
192        self.in_record = false;
193        self.units = 0;
194        self.buf.push(DLE);
195        self
196    }
197
198    /// CAN: close the innermost level. Panics when none is open.
199    pub fn can(&mut self) -> &mut Self {
200        let (in_record, units) = self.stack.pop().expect("CAN with no open level");
201        self.buf.push(CAN);
202        self.in_record = in_record;
203        self.units = units;
204        self
205    }
206
207    /// A bare BEL: marks the element that follows dead.
208    pub fn bel(&mut self) -> &mut Self {
209        self.buf.push(BEL);
210        self
211    }
212
213    /// BEL and a note. A note has content: an empty one panics (a bare BEL
214    /// is a dead marker, written with [`bel`]).
215    ///
216    /// [`bel`]: Builder::bel
217    pub fn bel_note(&mut self, text: impl AsRef<[u8]>) -> &mut Self {
218        let text = text.as_ref();
219        assert!(
220            !text.is_empty(),
221            "a note needs content: bare BEL marks the next element dead"
222        );
223        self.buf.push(BEL);
224        write_value(&mut self.buf, text);
225        self
226    }
227
228    /// ENQ and a group name: a group reference. The name is required.
229    pub fn enq(&mut self, name: &str) -> &mut Self {
230        assert!(!name.is_empty(), "a reference needs a name");
231        self.buf.push(ENQ);
232        self.name(name);
233        self
234    }
235
236    /// ENQ and a pattern: a level built in `f`, the target with its values
237    /// left out (`enq_level(|b| { b.gs_name("tags").rs_value("001").us_value("label"); })`
238    /// writes `␅␐␝tags␞001␟label␘`).
239    pub fn enq_level<F: FnOnce(&mut Builder)>(&mut self, f: F) -> &mut Self {
240        self.buf.push(ENQ);
241        self.dle();
242        f(self);
243        self.can()
244    }
245
246    /// SYN: the start of a document. Heading pairs follow as
247    /// `soh_key(k).us_value(v)` or [`heading`]. Ends any open record.
248    ///
249    /// [`heading`]: Builder::heading
250    pub fn syn(&mut self) -> &mut Self {
251        self.end_record();
252        self.buf.push(SYN);
253        self
254    }
255
256    /// EOT: the end of the document. Ends any open record.
257    pub fn eot(&mut self) -> &mut Self {
258        self.end_record();
259        self.buf.push(EOT);
260        self
261    }
262
263    /// A bare ETB: commit what was appended since the last commit. Ends
264    /// any open record.
265    pub fn etb(&mut self) -> &mut Self {
266        self.end_record();
267        self.buf.push(ETB);
268        self
269    }
270
271    /// ETB and an integrity payload (a name).
272    pub fn etb_payload(&mut self, payload: &str) -> &mut Self {
273        self.etb();
274        self.name(payload);
275        self
276    }
277
278    /// EM and the raw tail. Nothing may follow.
279    pub fn em(&mut self, tail: &[u8]) -> &mut Self {
280        self.end_record();
281        self.buf.push(EM);
282        self.buf.extend_from_slice(tail);
283        self
284    }
285
286    // ---- documents -------------------------------------------------------
287
288    /// A heading key and its value (`SOH key US value`), after [`syn`].
289    ///
290    /// [`syn`]: Builder::syn
291    pub fn heading(&mut self, key: &str, value: impl AsRef<[u8]>) -> &mut Self {
292        self.end_record();
293        self.soh_key(key).us_value(value)
294    }
295
296    /// A heading key whose value is a nested level (e.g. the blob table).
297    pub fn heading_level<F: FnOnce(&mut Builder)>(&mut self, key: &str, f: F) -> &mut Self {
298        self.end_record();
299        self.soh_key(key).us().dle();
300        f(self);
301        self.can()
302    }
303
304    // ---- structure -------------------------------------------------------
305
306    /// FS and a file name.
307    pub fn file(&mut self, name: &str) -> &mut Self {
308        self.fs(name)
309    }
310
311    /// GS, a group name, and a header row when given.
312    pub fn group(&mut self, name: &str, headers: Option<&[&str]>) -> &mut Self {
313        self.group_at(name, headers, 1)
314    }
315
316    /// A group at `depth` (`depth − 1` SUB then GS), a group name, and a
317    /// header row when given.
318    pub fn group_at(&mut self, name: &str, headers: Option<&[&str]>, depth: usize) -> &mut Self {
319        self.gs_name_at(name, depth);
320        if let Some(h) = headers {
321            self.header(h);
322        }
323        self
324    }
325
326    /// A header row: `SOH RS name US name …`. Ends the record it writes.
327    pub fn header(&mut self, names: &[&str]) -> &mut Self {
328        for n in names {
329            assert!(is_name(n.as_bytes()), "not a legal name: {n:?}");
330        }
331        self.end_record();
332        self.soh().rs();
333        for (i, n) in names.iter().enumerate() {
334            if i == 0 {
335                self.first_value(n.as_bytes());
336            } else {
337                self.us_value(n);
338            }
339        }
340        self.end_record();
341        self
342    }
343
344    /// Document mode: a section at `depth` (`depth − 1` SUB, GS and a name).
345    pub fn section(&mut self, name: &str, depth: usize) -> &mut Self {
346        self.group_at(name, None, depth)
347    }
348
349    // ---- records -----------------------------------------------------------
350
351    /// A positional record.
352    pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> &mut Self {
353        self.rs();
354        for f in fields {
355            self.field(f);
356        }
357        self
358    }
359
360    /// Begin a record and leave it open for [`field`], [`level`], [`list`],
361    /// [`reference`] or [`key`] calls.
362    ///
363    /// [`field`]: Builder::field
364    /// [`level`]: Builder::level
365    /// [`list`]: Builder::list
366    /// [`reference`]: Builder::reference
367    /// [`key`]: Builder::key
368    pub fn begin_record(&mut self) -> &mut Self {
369        self.rs()
370    }
371
372    /// Document mode: a paragraph (a record with one unit).
373    pub fn block(&mut self, text: impl AsRef<[u8]>) -> &mut Self {
374        self.rs_value(text)
375    }
376
377    /// Document mode: a list item (a unit of the open block).
378    pub fn item(&mut self, text: impl AsRef<[u8]>) -> &mut Self {
379        self.field(text)
380    }
381
382    /// Append a unit to the open record (opens one if none is open).
383    pub fn field(&mut self, value: impl AsRef<[u8]>) -> &mut Self {
384        if !self.in_record {
385            self.rs_value(value)
386        } else if self.units == 0 {
387            self.first_value(value.as_ref());
388            self
389        } else {
390            self.us_value(value)
391        }
392    }
393
394    /// A keyed record: a map, entries in the order given.
395    pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> &mut Self {
396        self.rs();
397        for (k, v) in pairs {
398            self.key(k, v);
399        }
400        self
401    }
402
403    /// One keyed unit on the open record (opens one if none is open).
404    pub fn key(&mut self, name: &str, value: impl AsRef<[u8]>) -> &mut Self {
405        if !self.in_record {
406            self.rs();
407        }
408        self.soh_key(name).us_value(value)
409    }
410
411    /// One keyed unit whose value is a nested level.
412    pub fn key_level<F: FnOnce(&mut Builder)>(&mut self, name: &str, f: F) -> &mut Self {
413        if !self.in_record {
414            self.rs();
415        }
416        self.soh_key(name).us().dle();
417        f(self);
418        self.can()
419    }
420
421    // ---- values that are not plain -------------------------------------
422
423    /// A nested level as the next unit. Inside `f` the builder is at the
424    /// top of a fresh body.
425    pub fn level<F: FnOnce(&mut Builder)>(&mut self, f: F) -> &mut Self {
426        self.next_unit();
427        self.dle();
428        f(self);
429        self.can()
430    }
431
432    /// A flat list as the next unit: a level holding one record.
433    pub fn list<T: AsRef<[u8]>>(&mut self, items: &[T]) -> &mut Self {
434        self.next_unit();
435        self.dle();
436        if !items.is_empty() {
437            self.rs();
438            for it in items {
439                self.field(it);
440            }
441        }
442        self.can()
443    }
444
445    /// A group reference (`ENQ name`) as the next unit.
446    pub fn reference(&mut self, name: &str) -> &mut Self {
447        self.next_unit();
448        self.enq(name)
449    }
450
451    /// A reference as the next unit, its pattern built in `f` (see
452    /// [`enq_level`]).
453    ///
454    /// [`enq_level`]: Builder::enq_level
455    pub fn reference_level<F: FnOnce(&mut Builder)>(&mut self, f: F) -> &mut Self {
456        self.next_unit();
457        self.enq_level(f)
458    }
459
460    /// A reference to a record, or to a field of it, as the next unit: the
461    /// pattern `␅␐␝group␞record␟field␘`.
462    pub fn reference_to(&mut self, group: &str, record: &str, field: Option<&str>) -> &mut Self {
463        self.next_unit();
464        self.enq_level(|b| {
465            b.gs_name(group).rs_value(record);
466            if let Some(f) = field {
467                b.us_value(f);
468            }
469        })
470    }
471
472    /// A sub-unit of the unit just written: SUB, US and the value
473    /// (`␞a␚␟b`). It is not a unit of the record and does not count as
474    /// one. Opens a record if none is open: `␞␚␟b` is an empty first unit
475    /// holding `b`.
476    pub fn sub_unit(&mut self, value: impl AsRef<[u8]>) -> &mut Self {
477        self.sub_unit_at(value, 1)
478    }
479
480    /// A sub-unit at `depth`: `depth` SUB, US and the value. `depth` 2 is a
481    /// sub-unit of the sub-unit written before (`␞a␚␟b␚␚␟c`).
482    pub fn sub_unit_at(&mut self, value: impl AsRef<[u8]>, depth: usize) -> &mut Self {
483        assert!(depth >= 1, "a sub-unit is at depth one or deeper");
484        if !self.in_record {
485            self.rs();
486        }
487        for _ in 0..depth {
488            self.buf.push(SUB);
489        }
490        self.buf.push(US);
491        write_value(&mut self.buf, value.as_ref());
492        // the unit it hangs off exists, even when empty
493        self.units = self.units.max(1);
494        self
495    }
496
497    // ---- comments ----------------------------------------------------------
498
499    /// A note at the current position (record level, or as an empty unit).
500    /// A note has content: an empty one panics (a bare BEL is a dead
501    /// marker, written with [`bel`]).
502    ///
503    /// [`bel`]: Builder::bel
504    pub fn note(&mut self, text: impl AsRef<[u8]>) -> &mut Self {
505        self.bel_note(text)
506    }
507
508    // ---- internals ---------------------------------------------------------
509
510    fn name(&mut self, name: &str) {
511        if let Err(e) = write_name(&mut self.buf, name.as_bytes()) {
512            panic!("{e}");
513        }
514    }
515
516    fn end_record(&mut self) {
517        self.in_record = false;
518        self.units = 0;
519    }
520
521    /// Position for the next unit of the open record (opening one if
522    /// needed): US between units, nothing before the first.
523    fn next_unit(&mut self) {
524        if !self.in_record {
525            self.rs();
526        } else if self.units > 0 {
527            self.buf.push(US);
528        }
529        self.units += 1;
530    }
531
532    /// The first value of a record, straight after RS.
533    fn first_value(&mut self, value: &[u8]) {
534        write_value(&mut self.buf, value);
535        self.units = 1;
536    }
537}