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("shape", "tabular");
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/// `sub()`, `gs()`, `soh()`, `bel()`, `etb()`) and the code with what follows
24/// it (`rs_value`, `us_value`, `sub_value`, `gs_name`, `soh_key`, `bel_note`,
25/// `etb_payload`). `sub` is C0-DIFF only:
26///
27/// ```
28/// let buf = c0::Builder::build(|b| {
29/// b.rs_value("Alice").us_value("1502.30"); // ␞Alice␟1502.30
30/// b.rs().soh_key("host").us_value("localhost"); // ␞␁host␟localhost
31/// b.bel().gs_name("old"); // ␇␝old: a dead group
32/// });
33/// ```
34///
35/// The composed methods (`file`, `group`, `header`, `record`, `field`,
36/// `map`, `key`, `level`, `list`, `reference`, `note`, …) are built on the
37/// primitives and cannot write ill-formed output. The primitives write what
38/// you spell; well-formedness is then yours to keep. Both layers share the
39/// record state, so they mix.
40///
41/// Values are written in their one spelling: plain when they can be, text
42/// (`STX … ETX`, seven codes escaped) otherwise; they accept any
43/// `AsRef<[u8]>` and are byte-transparent. Keyed records ([`map`], [`key`])
44/// keep the order given. Nested levels ([`level`], [`list`], [`key_level`])
45/// open with DLE and close with CAN. Names (file and group labels, keys,
46/// header names, reference segments, commit payloads) are identifiers: a
47/// name with a byte below 0x20 or edge whitespace panics.
48///
49/// [`map`]: Builder::map
50/// [`key`]: Builder::key
51/// [`level`]: Builder::level
52/// [`list`]: Builder::list
53/// [`key_level`]: Builder::key_level
54#[derive(Default)]
55pub struct Builder {
56 buf: Vec<u8>,
57 in_record: bool,
58 units: usize,
59 stack: Vec<(bool, usize)>,
60}
61
62impl Builder {
63 pub fn new() -> Self {
64 Builder::default()
65 }
66
67 /// Build a buffer by driving a fresh builder, returning its bytes.
68 pub fn build<F: FnOnce(&mut Builder)>(f: F) -> Vec<u8> {
69 let mut b = Builder::new();
70 f(&mut b);
71 b.into_bytes()
72 }
73
74 /// The bytes built so far.
75 #[inline]
76 pub fn as_bytes(&self) -> &[u8] {
77 &self.buf
78 }
79
80 /// Consume the builder, returning the built buffer.
81 #[inline]
82 pub fn into_bytes(self) -> Vec<u8> {
83 self.buf
84 }
85
86 // ---- primitives: one method per code ---------------------------------
87
88 /// FS and a file name. Ends any open record.
89 pub fn fs(&mut self, name: &str) -> &mut Self {
90 self.end_record();
91 self.buf.push(FS);
92 self.name(name);
93 self
94 }
95
96 /// A bare GS. `gs().gs_name("sub")` is a group at depth 2. Ends any
97 /// open record.
98 pub fn gs(&mut self) -> &mut Self {
99 self.end_record();
100 self.buf.push(GS);
101 self
102 }
103
104 /// GS and a group name. Ends any open record.
105 pub fn gs_name(&mut self, name: &str) -> &mut Self {
106 self.gs();
107 self.name(name);
108 self
109 }
110
111 /// A bare RS: opens a record with no units yet.
112 pub fn rs(&mut self) -> &mut Self {
113 self.buf.push(RS);
114 self.in_record = true;
115 self.units = 0;
116 self
117 }
118
119 /// RS and the record's first value.
120 pub fn rs_value(&mut self, value: impl AsRef<[u8]>) -> &mut Self {
121 self.rs();
122 self.first_value(value.as_ref());
123 self
124 }
125
126 /// A bare US: the next unit of the record is empty, or is what follows
127 /// (a level, a reference).
128 pub fn us(&mut self) -> &mut Self {
129 self.buf.push(US);
130 self.units += 1;
131 self
132 }
133
134 /// US and the value that follows it.
135 pub fn us_value(&mut self, value: impl AsRef<[u8]>) -> &mut Self {
136 self.buf.push(US);
137 write_value(&mut self.buf, value.as_ref());
138 self.units += 1;
139 self
140 }
141
142 /// A bare SUB: a substitution whose new side is empty. C0-DIFF only;
143 /// in a data body SUB is an error. Does not change the unit count.
144 pub fn sub(&mut self) -> &mut Self {
145 self.buf.push(SUB);
146 self
147 }
148
149 /// SUB and the new side of a substitution. C0-DIFF only:
150 /// `rs_value("old").sub_value("new")` is a replace-all,
151 /// `us_value("10").sub_value("20")` a pattern unit with one substitution.
152 pub fn sub_value(&mut self, value: impl AsRef<[u8]>) -> &mut Self {
153 self.buf.push(SUB);
154 write_value(&mut self.buf, value.as_ref());
155 self
156 }
157
158 /// A bare SOH. Before `rs` it opens a header row.
159 pub fn soh(&mut self) -> &mut Self {
160 self.buf.push(SOH);
161 self
162 }
163
164 /// SOH and a key. The key's value follows as `us_value`.
165 pub fn soh_key(&mut self, name: &str) -> &mut Self {
166 self.buf.push(SOH);
167 self.name(name);
168 self
169 }
170
171 /// DLE: open a nested level. Inside, the builder is at the top of a
172 /// fresh body; the record state is restored by [`can`].
173 ///
174 /// [`can`]: Builder::can
175 pub fn dle(&mut self) -> &mut Self {
176 self.stack.push((self.in_record, self.units));
177 self.in_record = false;
178 self.units = 0;
179 self.buf.push(DLE);
180 self
181 }
182
183 /// CAN: close the innermost level. Panics when none is open.
184 pub fn can(&mut self) -> &mut Self {
185 let (in_record, units) = self.stack.pop().expect("CAN with no open level");
186 self.buf.push(CAN);
187 self.in_record = in_record;
188 self.units = units;
189 self
190 }
191
192 /// A bare BEL: marks the element that follows dead.
193 pub fn bel(&mut self) -> &mut Self {
194 self.buf.push(BEL);
195 self
196 }
197
198 /// BEL and a note. A note has content: an empty one panics (a bare BEL
199 /// is a dead marker, written with [`bel`]).
200 ///
201 /// [`bel`]: Builder::bel
202 pub fn bel_note(&mut self, text: impl AsRef<[u8]>) -> &mut Self {
203 let text = text.as_ref();
204 assert!(
205 !text.is_empty(),
206 "a note needs content: bare BEL marks the next element dead"
207 );
208 self.buf.push(BEL);
209 write_value(&mut self.buf, text);
210 self
211 }
212
213 /// ENQ and a group reference (a name).
214 pub fn enq(&mut self, name: &str) -> &mut Self {
215 self.buf.push(ENQ);
216 self.name(name);
217 self
218 }
219
220 /// ENQ and a reference by path: one segment is a group reference, two
221 /// or three are a path written as text.
222 pub fn enq_path(&mut self, segments: &[&str]) -> &mut Self {
223 assert!(
224 (1..=3).contains(&segments.len()),
225 "a reference path has one to three segments"
226 );
227 if segments.len() == 1 {
228 return self.enq(segments[0]);
229 }
230 self.buf.push(ENQ);
231 self.buf.push(STX);
232 for (i, seg) in segments.iter().enumerate() {
233 if i > 0 {
234 self.buf.push(US);
235 }
236 assert!(
237 !seg.is_empty() && is_name(seg.as_bytes()),
238 "reference segment is not a name: {seg:?}"
239 );
240 self.buf.extend_from_slice(seg.as_bytes());
241 }
242 self.buf.push(ETX);
243 self
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 /// GS×`depth`, a group name, and a header row when given.
317 pub fn group_at(&mut self, name: &str, headers: Option<&[&str]>, depth: usize) -> &mut Self {
318 for _ in 1..depth {
319 self.gs();
320 }
321 self.gs_name(name);
322 if let Some(h) = headers {
323 self.header(h);
324 }
325 self
326 }
327
328 /// A header row: `SOH RS name US name …`. Ends the record it writes.
329 pub fn header(&mut self, names: &[&str]) -> &mut Self {
330 for n in names {
331 assert!(is_name(n.as_bytes()), "not a legal name: {n:?}");
332 }
333 self.end_record();
334 self.soh().rs();
335 for (i, n) in names.iter().enumerate() {
336 if i == 0 {
337 self.first_value(n.as_bytes());
338 } else {
339 self.us_value(n);
340 }
341 }
342 self.end_record();
343 self
344 }
345
346 /// Document mode: a section at `depth` (GS×depth and a name).
347 pub fn section(&mut self, name: &str, depth: usize) -> &mut Self {
348 self.group_at(name, None, depth)
349 }
350
351 // ---- records -----------------------------------------------------------
352
353 /// A positional record.
354 pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> &mut Self {
355 self.rs();
356 for f in fields {
357 self.field(f);
358 }
359 self
360 }
361
362 /// Begin a record and leave it open for [`field`], [`level`], [`list`],
363 /// [`reference`] or [`key`] calls.
364 ///
365 /// [`field`]: Builder::field
366 /// [`level`]: Builder::level
367 /// [`list`]: Builder::list
368 /// [`reference`]: Builder::reference
369 /// [`key`]: Builder::key
370 pub fn begin_record(&mut self) -> &mut Self {
371 self.rs()
372 }
373
374 /// Document mode: a paragraph (a record with one unit).
375 pub fn block(&mut self, text: impl AsRef<[u8]>) -> &mut Self {
376 self.rs_value(text)
377 }
378
379 /// Document mode: a list item (a unit of the open block).
380 pub fn item(&mut self, text: impl AsRef<[u8]>) -> &mut Self {
381 self.field(text)
382 }
383
384 /// Append a unit to the open record (opens one if none is open).
385 pub fn field(&mut self, value: impl AsRef<[u8]>) -> &mut Self {
386 if !self.in_record {
387 self.rs_value(value)
388 } else if self.units == 0 {
389 self.first_value(value.as_ref());
390 self
391 } else {
392 self.us_value(value)
393 }
394 }
395
396 /// A keyed record: a map, entries in the order given.
397 pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> &mut Self {
398 self.rs();
399 for (k, v) in pairs {
400 self.key(k, v);
401 }
402 self
403 }
404
405 /// One keyed unit on the open record (opens one if none is open).
406 pub fn key(&mut self, name: &str, value: impl AsRef<[u8]>) -> &mut Self {
407 if !self.in_record {
408 self.rs();
409 }
410 self.soh_key(name).us_value(value)
411 }
412
413 /// One keyed unit whose value is a nested level.
414 pub fn key_level<F: FnOnce(&mut Builder)>(&mut self, name: &str, f: F) -> &mut Self {
415 if !self.in_record {
416 self.rs();
417 }
418 self.soh_key(name).us().dle();
419 f(self);
420 self.can()
421 }
422
423 // ---- values that are not plain -------------------------------------
424
425 /// A nested level as the next unit. Inside `f` the builder is at the
426 /// top of a fresh body.
427 pub fn level<F: FnOnce(&mut Builder)>(&mut self, f: F) -> &mut Self {
428 self.next_unit();
429 self.dle();
430 f(self);
431 self.can()
432 }
433
434 /// A flat list as the next unit: a level holding one record.
435 pub fn list<T: AsRef<[u8]>>(&mut self, items: &[T]) -> &mut Self {
436 self.next_unit();
437 self.dle();
438 if !items.is_empty() {
439 self.rs();
440 for it in items {
441 self.field(it);
442 }
443 }
444 self.can()
445 }
446
447 /// A group reference (`ENQ name`) as the next unit.
448 pub fn reference(&mut self, name: &str) -> &mut Self {
449 self.next_unit();
450 self.enq(name)
451 }
452
453 /// A reference by path as the next unit: one segment is a group
454 /// reference, two or three are a path written as text.
455 pub fn reference_path(&mut self, segments: &[&str]) -> &mut Self {
456 self.next_unit();
457 self.enq_path(segments)
458 }
459
460 // ---- comments ----------------------------------------------------------
461
462 /// A note at the current position (record level, or as an empty unit).
463 /// A note has content: an empty one panics (a bare BEL is a dead
464 /// marker, written with [`bel`]).
465 ///
466 /// [`bel`]: Builder::bel
467 pub fn note(&mut self, text: impl AsRef<[u8]>) -> &mut Self {
468 self.bel_note(text)
469 }
470
471 // ---- internals ---------------------------------------------------------
472
473 fn name(&mut self, name: &str) {
474 if let Err(e) = write_name(&mut self.buf, name.as_bytes()) {
475 panic!("{e}");
476 }
477 }
478
479 fn end_record(&mut self) {
480 self.in_record = false;
481 self.units = 0;
482 }
483
484 /// Position for the next unit of the open record (opening one if
485 /// needed): US between units, nothing before the first.
486 fn next_unit(&mut self) {
487 if !self.in_record {
488 self.rs();
489 } else if self.units > 0 {
490 self.buf.push(US);
491 }
492 self.units += 1;
493 }
494
495 /// The first value of a record, straight after RS.
496 fn first_value(&mut self, value: &[u8]) {
497 write_value(&mut self.buf, value);
498 self.units = 1;
499 }
500}