c0
C0DATA — structured data using ASCII C0 control codes (C)
Loading...
Searching...
No Matches
c0.h
Go to the documentation of this file.
1/*
2 * c0.h — C0DATA 1.0: structured data using ASCII C0 control codes.
3 *
4 * Single-header library. In exactly one translation unit:
5 *
6 * #define C0_IMPLEMENTATION
7 * #include "c0.h"
8 *
9 * Elsewhere just #include "c0.h" for the declarations.
10 *
11 * The read path is zero-copy and allocation-free: views and cursors walk a
12 * caller-owned buffer and hand back (pointer, length) slices into it. The
13 * hot loop outside text is a single comparison, `byte < 0x20`.
14 *
15 * Parse is validate: `c0_document_read`, `c0_documents` / `c0_next_document`
16 * and `c0_body_read` apply the whole grammar (GRAMMAR.md) to every unit and
17 * level and fail on malformed input; `c0_validate` is the same check on a
18 * whole buffer, `c0_canonical` adds the canonical constraints. The cursors
19 * (files, groups, records, units) then assume well-formed input and report
20 * the result model: a dead element (BEL before it) is parsed but not in the
21 * tree; a sub-unit (`␞a␟b␚␟c`: SUB before US makes `c` a child of `b`) is
22 * not a unit of its record and is reached through `c0_record_unit` and
23 * `c0_unit_subs`. Writing is `c0_builder`, which owns a growable buffer and
24 * spells every value in its one canonical form.
25 *
26 * Spec: https://github.com/c0data/c0-spec (DESIGN.md, GRAMMAR.md, DIFF.md).
27 * License: MIT.
28 */
29#ifndef C0_H
30#define C0_H
31
32#include <stddef.h>
33#include <stdint.h>
34
35#ifdef __cplusplus
36extern "C" {
37#endif
38
39#define C0_VERSION "0.2.0"
40
41/* ---- Assigned control codes (DESIGN.md "Assigned Control Codes") ------ */
42#define C0_SOH 0x01
43#define C0_STX 0x02
44#define C0_ETX 0x03
45#define C0_EOT 0x04
46#define C0_ENQ 0x05
47#define C0_BEL 0x07
48#define C0_DLE 0x10
49#define C0_SYN 0x16
50#define C0_ETB 0x17
51#define C0_CAN 0x18
52#define C0_EM 0x19
53#define C0_SUB 0x1a
54#define C0_FS 0x1c
55#define C0_GS 0x1d
56#define C0_RS 0x1e
57#define C0_US 0x1f
58
59/* Layout codes outside text. */
60#define C0_HT 0x09
61#define C0_LF 0x0a
62#define C0_CR 0x0d
63#define C0_SP 0x20
64
66typedef struct {
67 const uint8_t *ptr;
68 size_t len;
69} c0_bytes;
70
88
91typedef struct {
93 size_t pos;
94 const char *msg;
95} c0_error;
96
98#define C0_WARN_NO_SYN 0x01u
99#define C0_WARN_NO_EOT 0x02u
100#define C0_WARN_UNKNOWN_KEY 0x04u
101#define C0_WARN_DUPLICATE_KEY 0x08u
102#define C0_WARN_UNKNOWN_SHAPE 0x10u
103#define C0_WARN_UNKNOWN_VERSION 0x20u
104
105/* ---- Bytewise helpers -------------------------------------------------- */
106
108int c0_is_assigned(uint8_t byte);
110int c0_is_layout(uint8_t byte);
113int c0_is_text_escaped(uint8_t byte);
115int c0_is_plain(const uint8_t *p, size_t len);
117int c0_is_name(const uint8_t *p, size_t len);
119c0_bytes c0_bytes_of(const uint8_t *ptr, size_t len);
122
126size_t c0_decode_text(const uint8_t *inside, size_t len, uint8_t *out);
127
128/* ---- Scanning primitives (c0.cr `Scan`) --------------------------------
129 * Each takes a buffer and a position and returns the position after the
130 * construct; on malformed input it records the error (when err is given)
131 * and returns `stop`. Converters and bindings build on these. */
132
134size_t c0_scan_layout(const uint8_t *buf, size_t pos, size_t stop);
136size_t c0_scan_plain(const uint8_t *buf, size_t pos, size_t stop);
138size_t c0_scan_text(const uint8_t *buf, size_t pos, size_t stop, c0_error *err);
140size_t c0_scan_level(const uint8_t *buf, size_t pos, size_t stop, c0_error *err);
143size_t c0_scan_unit(const uint8_t *buf, size_t pos, size_t stop, c0_error *err);
145size_t c0_scan_comment(const uint8_t *buf, size_t pos, size_t stop, c0_error *err);
148size_t c0_scan_record_end(const uint8_t *buf, size_t pos, size_t stop, c0_error *err);
149
150/* ---- Validation -------------------------------------------------------- */
151
154c0_status c0_validate(const uint8_t *buf, size_t len, c0_error *err);
155
160int c0_canonical(const uint8_t *buf, size_t len);
161
162/* ---- Units and values -------------------------------------------------- */
163
171
173
184c0_status c0_value(c0_bytes raw, uint8_t *scratch, c0_bytes *out);
185
188typedef struct {
189 const uint8_t *buf;
190 size_t start;
191 size_t stop;
192} c0_body;
193
196c0_body c0_body_view(const uint8_t *buf, size_t len);
197
200c0_status c0_body_read(const uint8_t *buf, size_t len, c0_body *out, c0_error *err);
201
204
213
217
222size_t c0_ref_path(const c0_ref *r, c0_bytes *steps, size_t max);
223
226int c0_ref_group(const c0_ref *r, c0_bytes *name);
227
228/* ---- Records ------------------------------------------------------------ */
229
232typedef struct {
233 const uint8_t *buf;
234 size_t start;
235 size_t stop;
236} c0_record;
237
240
242typedef struct {
243 const uint8_t *buf;
244 size_t pos;
245 size_t stop;
246 int done;
249
256
262typedef struct {
264 const uint8_t *buf;
265 size_t subs_start;
266 size_t subs_end;
267 size_t depth;
268} c0_unit;
269
274
277typedef struct {
278 const uint8_t *buf;
279 size_t pos;
280 size_t stop;
281 size_t depth;
284
289
294
296typedef struct {
297 const uint8_t *buf;
298 size_t pos;
299 size_t stop;
302
309
311c0_status c0_record_get(c0_record r, const uint8_t *key, size_t klen, c0_bytes *raw);
314c0_status c0_record_unit_get(c0_record r, const uint8_t *key, size_t klen, c0_unit *out);
316
321
322/* ---- Bodies: files, groups, records ------------------------------------ */
323
326typedef struct {
327 const uint8_t *buf;
329 size_t name_end;
330 size_t start;
331 size_t stop;
333} c0_file;
334
339typedef struct {
340 const uint8_t *buf;
341 size_t depth;
343 size_t name_end;
344 size_t start;
345 size_t stop;
346} c0_group;
347
350
355typedef struct {
356 const uint8_t *buf;
357 size_t pos;
358 size_t stop;
359 int first;
360 int done;
363
366
371typedef struct {
372 const uint8_t *buf;
373 size_t pos;
374 size_t stop;
375 int first;
376 int done;
379
385
387c0_status c0_body_find_group(c0_body b, const uint8_t *name, size_t nlen, c0_group *out);
389
393
397
400typedef struct {
401 const uint8_t *buf;
402 size_t pos;
403 size_t stop;
404 int done;
407
412
414c0_status c0_group_column(c0_group g, const uint8_t *name, size_t nlen, size_t *index);
415
416/* ---- Documents and containers ------------------------------------------ */
417
419typedef struct {
420 const uint8_t *buf;
421 size_t start;
422 size_t stop;
426 size_t heading_end;
428 unsigned warnings;
431
434c0_status c0_document_read(const uint8_t *buf, size_t len, size_t start, c0_document *out, c0_error *err);
435
439c0_status c0_heading_get(const c0_document *d, const uint8_t *key, size_t klen, c0_bytes *raw);
440c0_status c0_heading_get_str(const c0_document *d, const char *key, c0_bytes *raw);
447
450typedef struct {
451 const uint8_t *buf;
452 size_t len;
453 size_t pos;
455 size_t em_pos;
456 int done;
459
460c0_doc_iter c0_documents(const uint8_t *buf, size_t len);
464
467c0_status c0_container_tail(const uint8_t *buf, size_t len, c0_bytes *tail, int *has_em, c0_error *err);
468
472c0_status c0_blob(const uint8_t *buf, size_t len, const uint8_t *name, size_t nlen, c0_bytes *out, c0_error *err);
473c0_status c0_blob_str(const uint8_t *buf, size_t len, const char *name, c0_bytes *out, c0_error *err);
474
475/* ---- Builder (writer) --------------------------------------------------- */
476
508typedef struct {
509 uint8_t *data;
510 size_t len;
511 size_t cap;
513 int state;
514 size_t units;
515 int *stack;
516 size_t depth;
517 size_t stack_cap;
518} c0_builder;
519
524
525/* primitives: one function per code. The bare form writes the code alone;
526 * the `_name` / `_value` / `_text` / `_payload` form writes the code and what
527 * follows it; `_str` is that form on a NUL-terminated string. Values take
528 * their one spelling (plain or text); names must be plain. */
529void c0_builder_fs(c0_builder *b, const uint8_t *name, size_t nlen);
531void c0_builder_gs_name(c0_builder *b, const uint8_t *name, size_t nlen);
533void c0_builder_rs_value(c0_builder *b, const uint8_t *value, size_t vlen);
535void c0_builder_us_value(c0_builder *b, const uint8_t *value, size_t vlen);
538void c0_builder_soh_name(c0_builder *b, const uint8_t *name, size_t nlen);
542void c0_builder_bel_text(c0_builder *b, const uint8_t *text, size_t tlen);
543void c0_builder_enq(c0_builder *b, const uint8_t *name, size_t nlen);
548void c0_builder_etb_payload(c0_builder *b, const uint8_t *payload, size_t plen);
549void c0_builder_em(c0_builder *b, const uint8_t *tail, size_t tlen);
550
551void c0_builder_fs_str(c0_builder *b, const char *name);
552void c0_builder_gs_str(c0_builder *b, const char *name);
553void c0_builder_rs_str(c0_builder *b, const char *value);
554void c0_builder_us_str(c0_builder *b, const char *value);
555void c0_builder_soh_str(c0_builder *b, const char *name);
556void c0_builder_bel_str(c0_builder *b, const char *text);
557void c0_builder_enq_str(c0_builder *b, const char *name);
558void c0_builder_etb_str(c0_builder *b, const char *payload);
559void c0_builder_em_str(c0_builder *b, const char *tail);
560
561/* composed: cannot write ill-formed output */
562
563/* documents */
566void c0_build_etb(c0_builder *b, const uint8_t *payload, size_t plen);
567void c0_build_em(c0_builder *b, const uint8_t *tail, size_t tlen);
568
569/* structure */
570void c0_build_file(c0_builder *b, const uint8_t *name, size_t nlen);
571void c0_build_group(c0_builder *b, const uint8_t *name, size_t nlen);
572void c0_build_section(c0_builder *b, const uint8_t *name, size_t nlen, size_t depth);
573void c0_build_header(c0_builder *b, const c0_bytes *names, size_t count);
574
575/* records */
576void c0_build_record(c0_builder *b, const c0_bytes *fields, size_t count);
577void c0_build_field(c0_builder *b, const uint8_t *value, size_t vlen);
578void c0_build_sub_unit(c0_builder *b, const uint8_t *value, size_t vlen, size_t depth);
579void c0_build_map(c0_builder *b, const c0_bytes *keys, const c0_bytes *values, size_t count);
580void c0_build_key(c0_builder *b, const uint8_t *key, size_t klen, const uint8_t *value, size_t vlen);
582void c0_build_key_level_open(c0_builder *b, const uint8_t *key, size_t klen);
584void c0_build_list(c0_builder *b, const c0_bytes *items, size_t count);
585void c0_build_ref(c0_builder *b, const uint8_t *name, size_t nlen);
587void c0_build_ref_record(c0_builder *b, const uint8_t *group, size_t glen, const uint8_t *record, size_t rlen, const uint8_t *field, size_t flen);
588void c0_build_note(c0_builder *b, const uint8_t *text, size_t tlen);
589
590/* document mode */
591void c0_build_block(c0_builder *b, const uint8_t *text, size_t tlen);
592void c0_build_item(c0_builder *b, const uint8_t *text, size_t tlen);
593
594/* NUL-terminated convenience wrappers */
595void c0_build_etb_str(c0_builder *b, const char *payload);
596void c0_build_file_str(c0_builder *b, const char *name);
597void c0_build_group_str(c0_builder *b, const char *name);
598void c0_build_section_str(c0_builder *b, const char *name, size_t depth);
599void c0_build_header_str(c0_builder *b, const char *const *names, size_t count);
600void c0_build_record_str(c0_builder *b, const char *const *fields, size_t count);
601void c0_build_field_str(c0_builder *b, const char *value);
602void c0_build_sub_unit_str(c0_builder *b, const char *value, size_t depth);
603void c0_build_map_str(c0_builder *b, const char *const *keys, const char *const *values, size_t count);
604void c0_build_key_str(c0_builder *b, const char *key, const char *value);
605void c0_build_key_level_open_str(c0_builder *b, const char *key);
606void c0_build_list_str(c0_builder *b, const char *const *items, size_t count);
607void c0_build_ref_str(c0_builder *b, const char *name);
608void c0_build_ref_record_str(c0_builder *b, const char *group, const char *record, const char *field);
609void c0_build_note_str(c0_builder *b, const char *text);
610void c0_build_block_str(c0_builder *b, const char *text);
611void c0_build_item_str(c0_builder *b, const char *text);
612
613/* ---- Stream mode (ETB commits) ----------------------------------------- */
614
630
636typedef struct {
637 const uint8_t *buf;
638 size_t len;
640 int torn;
646} c0_stream;
647
648c0_stream c0_stream_read(const uint8_t *buf, size_t len);
651
655typedef struct {
656 const uint8_t *buf;
657 size_t stop;
658 size_t pos;
661 size_t index;
664
666int c0_next_block(c0_block_iter *it, c0_bytes *out, int *damaged);
667
672size_t c0_stream_undamaged(const c0_stream *s, uint8_t *out);
673
677size_t c0_stream_before_damage(const c0_stream *s, uint8_t *out);
678
681size_t c0_stream_last_commit_end(const uint8_t *buf, size_t len);
682
683/* ---- Pretty form (Unicode Control Pictures, U+2400 block) -------------- */
684
690
698char *c0_pretty_format(const uint8_t *buf, size_t len, const char *indent, c0_pretty_mode mode, size_t *outlen, c0_error *err);
699
703uint8_t *c0_pretty_parse(const char *str, size_t len, size_t *outlen);
704
705#ifdef __cplusplus
706}
707#endif
708
710#ifdef C0_IMPLEMENTATION
711
712#include <stdlib.h>
713#include <string.h>
714
715/* ---- tables ------------------------------------------------------------ */
716
717static const unsigned char c0__assigned[32] = {
718 0, 1, 1, 1, 1, 1, 0, 1, /* 0x00-0x07: SOH STX ETX EOT ENQ BEL */
719 0, 0, 0, 0, 0, 0, 0, 0, /* 0x08-0x0F */
720 1, 0, 0, 0, 0, 0, 1, 1, /* 0x10-0x17: DLE SYN ETB */
721 1, 1, 1, 0, 1, 1, 1, 1 /* 0x18-0x1F: CAN EM SUB FS GS RS US */
722};
723
724static const unsigned char c0__text_escaped[32] = {
725 0, 0, 1, 1, 1, 0, 0, 0, /* STX ETX EOT */
726 0, 0, 0, 0, 0, 0, 0, 0,
727 1, 0, 0, 0, 0, 0, 1, 1, /* DLE SYN ETB */
728 0, 1, 0, 0, 0, 0, 0, 0 /* EM */
729};
730
731int c0_is_assigned(uint8_t byte) { return byte < 0x20 && c0__assigned[byte]; }
732int c0_is_layout(uint8_t byte) { return byte == C0_SP || byte == C0_HT || byte == C0_LF || byte == C0_CR; }
733int c0_is_text_escaped(uint8_t byte) { return byte < 0x20 && c0__text_escaped[byte]; }
734
735int c0_is_plain(const uint8_t *p, size_t len) {
736 size_t i;
737 if (len == 0) return 1;
738 if (c0_is_layout(p[0]) || c0_is_layout(p[len - 1])) return 0;
739 for (i = 0; i < len; i++) {
740 if (p[i] < 0x20) return 0;
741 }
742 return 1;
743}
744
745int c0_is_name(const uint8_t *p, size_t len) { return c0_is_plain(p, len); }
746
747c0_bytes c0_bytes_of(const uint8_t *ptr, size_t len) {
748 c0_bytes b;
749 b.ptr = ptr;
750 b.len = len;
751 return b;
752}
753
755 size_t s = 0, e = raw.len;
756 while (s < e && c0_is_layout(raw.ptr[s])) s++;
757 while (e > s && c0_is_layout(raw.ptr[e - 1])) e--;
758 raw.ptr += s;
759 raw.len = e - s;
760 return raw;
761}
762
763size_t c0_decode_text(const uint8_t *in, size_t len, uint8_t *out) {
764 size_t i = 0, n = 0;
765 while (i < len) {
766 if (in[i] == C0_DLE) {
767 i++;
768 if (i >= len) break;
769 }
770 out[n++] = in[i++];
771 }
772 return n;
773}
774
775/* ---- errors ------------------------------------------------------------ */
776
777static void c0__fail(c0_error *err, c0_status code, size_t pos, const char *msg) {
778 if (err && err->code == C0_OK) {
779 err->code = code;
780 err->pos = pos;
781 err->msg = msg;
782 }
783}
784
785static void c0__err_clear(c0_error *err) {
786 if (err) {
787 err->code = C0_OK;
788 err->pos = 0;
789 err->msg = "";
790 }
791}
792
793static c0_bytes c0__slice(const uint8_t *buf, size_t s, size_t e) {
794 c0_bytes b;
795 b.ptr = buf + s;
796 b.len = e > s ? e - s : 0;
797 return b;
798}
799
800/* ---- scanning primitives (c0.cr `Scan`) --------------------------------
801 * Each takes a buffer and a position and returns the position after the
802 * construct. On malformed input it records the error and returns `stop`, so
803 * callers' loops end; callers that care check err->code. */
804
805static size_t c0__layout(const uint8_t *buf, size_t pos, size_t stop) {
806 while (pos < stop && c0_is_layout(buf[pos])) pos++;
807 return pos;
808}
809
810static size_t c0__plain(const uint8_t *buf, size_t pos, size_t stop) {
811 while (pos < stop && buf[pos] >= 0x20) pos++;
812 return pos;
813}
814
815/* At the STX of a text: the position after its ETX. */
816static size_t c0__text(const uint8_t *buf, size_t pos, size_t stop, c0_error *err) {
817 size_t start = pos;
818 pos++;
819 while (pos < stop) {
820 uint8_t b = buf[pos];
821 if (b == C0_DLE) {
822 pos++;
823 if (pos >= stop) {
824 c0__fail(err, C0_ERR_UNEXPECTED_END, pos, "DLE at end of text");
825 return stop;
826 }
827 if (!c0_is_text_escaped(buf[pos])) {
828 c0__fail(err, C0_ERR_SYNTAX, pos, "DLE before a byte that is not one of the seven");
829 return stop;
830 }
831 pos++;
832 } else if (b == C0_ETX) {
833 return pos + 1;
834 } else if (b == C0_STX) {
835 c0__fail(err, C0_ERR_SYNTAX, pos, "STX inside text (text does not nest)");
836 return stop;
837 } else if (b == C0_ETB || b == C0_EOT || b == C0_SYN || b == C0_EM) {
838 c0__fail(err, C0_ERR_SYNTAX, pos, "framing inside open text");
839 return stop;
840 } else {
841 pos++;
842 }
843 }
844 c0__fail(err, C0_ERR_UNEXPECTED_END, start, "text is not closed");
845 return stop;
846}
847
848/* At the DLE of a level: the position after its matching CAN. */
849static size_t c0__level(const uint8_t *buf, size_t pos, size_t stop, c0_error *err) {
850 size_t start = pos, depth = 1;
851 pos++;
852 while (pos < stop) {
853 uint8_t b = buf[pos];
854 if (b >= 0x20) {
855 pos++;
856 } else if (b == C0_STX) {
857 pos = c0__text(buf, pos, stop, err);
858 if (err->code) return stop;
859 } else if (b == C0_DLE) {
860 depth++;
861 pos++;
862 } else if (b == C0_CAN) {
863 depth--;
864 pos++;
865 if (depth == 0) return pos;
866 } else if (b == C0_ETB || b == C0_EOT || b == C0_SYN || b == C0_EM) {
867 c0__fail(err, C0_ERR_SYNTAX, pos, "framing inside open level");
868 return stop;
869 } else {
870 pos++;
871 }
872 }
873 c0__fail(err, C0_ERR_UNEXPECTED_END, start, "level is not closed");
874 return stop;
875}
876
877static size_t c0__comment(const uint8_t *buf, size_t pos, size_t stop, c0_error *err);
878static size_t c0__record_end(const uint8_t *buf, size_t pos, size_t stop, c0_error *err);
879static size_t c0__keyed_unit_end(const uint8_t *buf, size_t pos, size_t stop, c0_error *err);
880
881/* Is the BEL at pos followed (after layout) by a code other than STX/DLE,
882 * i.e. does it kill a record-level element? */
883static int c0__bel_kills_element(const uint8_t *buf, size_t pos, size_t stop) {
884 size_t p2 = c0__layout(buf, pos + 1, stop);
885 return p2 < stop && buf[p2] < 0x20 && buf[p2] != C0_STX && buf[p2] != C0_DLE;
886}
887
888/* Is the SOH at pos followed (after layout) by RS: a header row? */
889static int c0__soh_is_header(const uint8_t *buf, size_t pos, size_t stop) {
890 size_t p2 = c0__layout(buf, pos + 1, stop);
891 return p2 < stop && buf[p2] == C0_RS;
892}
893
894/* A SUB run at pos (layout may follow each SUB): *run gets its length and
895 * *next the position of the code after it (stop when the input ends). */
896static void c0__sub_run(const uint8_t *buf, size_t pos, size_t stop, size_t *run, size_t *next) {
897 size_t n = 0;
898 while (pos < stop && buf[pos] == C0_SUB) {
899 n++;
900 pos = c0__layout(buf, pos + 1, stop);
901 }
902 *run = n;
903 *next = pos;
904}
905
906static size_t c0__unit(const uint8_t *buf, size_t pos, size_t stop, c0_error *err);
907
908/* Past the sub-units after a value ending at pos: SUB runs, each followed by
909 * US and a value. Returns the position after the last; a SUB run before
910 * anything but US (a depth prefix on the next line) is left where it is. */
911static size_t c0__skip_subs(const uint8_t *buf, size_t pos, size_t stop, c0_error *err) {
912 for (;;) {
913 size_t run, nx, p = c0__layout(buf, pos, stop);
914 if (!(p < stop && buf[p] == C0_SUB)) return pos;
915 c0__sub_run(buf, p, stop, &run, &nx);
916 if (!(nx < stop && buf[nx] == C0_US)) return pos;
917 pos = c0__unit(buf, nx + 1, stop, err);
918 if (err->code) return stop;
919 }
920}
921
922/* From just after a US (or a key's US): the end of one unit's value, i.e.
923 * the next control code at this depth that does not belong to the value.
924 * Layout at the edges stays inside the returned range. */
925static size_t c0__unit(const uint8_t *buf, size_t pos, size_t stop, c0_error *err) {
926 while (pos < stop) {
927 uint8_t b = buf[pos];
928 if (b >= 0x20 || c0_is_layout(b)) {
929 pos++;
930 } else if (b == C0_STX) {
931 pos = c0__text(buf, pos, stop, err);
932 if (err->code) return stop;
933 } else if (b == C0_DLE) {
934 pos = c0__level(buf, pos, stop, err);
935 if (err->code) return stop;
936 } else if (b == C0_ENQ) {
937 pos++;
938 } else if (b == C0_BEL) {
939 if (c0__bel_kills_element(buf, pos, stop)) return pos;
940 pos = c0__comment(buf, pos, stop, err);
941 if (err->code) return stop;
942 } else {
943 return pos;
944 }
945 }
946 return pos;
947}
948
949/* At a BEL: skip the note (plain or text) or the dead element's own line
950 * (a dead group or file line only, not what it holds). */
951static size_t c0__comment(const uint8_t *buf, size_t pos, size_t stop, c0_error *err) {
952 uint8_t b;
953 pos = c0__layout(buf, pos + 1, stop);
954 if (pos >= stop) {
955 c0__fail(err, C0_ERR_UNEXPECTED_END, pos, "BEL at end of input");
956 return stop;
957 }
958 b = buf[pos];
959 if (b >= 0x20) return c0__plain(buf, pos, stop);
960 if (b == C0_STX) return c0__text(buf, pos, stop, err);
961 if (b == C0_DLE) return c0__level(buf, pos, stop, err);
962 if (b == C0_RS) return c0__record_end(buf, pos + 1, stop, err);
963 if (b == C0_SOH) {
964 size_t p2 = c0__layout(buf, pos + 1, stop);
965 if (p2 < stop && buf[p2] == C0_RS) return c0__record_end(buf, p2 + 1, stop, err);
966 return c0__skip_subs(buf, c0__keyed_unit_end(buf, pos + 1, stop, err), stop, err); /* a dead keyed unit takes its sub-units */
967 }
968 if (b == C0_GS) return c0__plain(buf, c0__layout(buf, pos + 1, stop), stop);
969 if (b == C0_SUB) { /* a dead group line with its depth prefix */
970 size_t run, nx;
971 c0__sub_run(buf, pos, stop, &run, &nx);
972 if (nx < stop && buf[nx] == C0_GS) return c0__plain(buf, c0__layout(buf, nx + 1, stop), stop);
973 c0__fail(err, C0_ERR_SYNTAX, pos, "BEL before a code that is not an element");
974 return stop;
975 }
976 if (b == C0_FS) return c0__plain(buf, pos + 1, stop);
977 c0__fail(err, C0_ERR_SYNTAX, pos, "BEL before a code that is not an element");
978 return stop;
979}
980
981/* From just after an RS: the end of the record, i.e. the next record-level
982 * code at this depth. A sub-unit (a SUB run then US) stays inside the
983 * record; a SUB run before a line code ends it. */
984static size_t c0__record_end(const uint8_t *buf, size_t pos, size_t stop, c0_error *err) {
985 while (pos < stop) {
986 uint8_t b = buf[pos];
987 if (b >= 0x20 || c0_is_layout(b) || b == C0_US || b == C0_ENQ) {
988 pos++;
989 } else if (b == C0_SOH) {
990 if (c0__soh_is_header(buf, pos, stop)) return pos; /* a header row */
991 pos++;
992 } else if (b == C0_SUB) {
993 size_t run, nx;
994 c0__sub_run(buf, pos, stop, &run, &nx);
995 if (nx < stop && buf[nx] == C0_US) pos = nx;
996 else return pos;
997 } else if (b == C0_STX) {
998 pos = c0__text(buf, pos, stop, err);
999 if (err->code) return stop;
1000 } else if (b == C0_DLE) {
1001 pos = c0__level(buf, pos, stop, err);
1002 if (err->code) return stop;
1003 } else if (b == C0_BEL) {
1004 size_t p2 = c0__layout(buf, pos + 1, stop);
1005 if (p2 < stop && (buf[p2] == C0_RS || buf[p2] == C0_GS || buf[p2] == C0_FS || buf[p2] == C0_SUB)) return pos;
1006 if (p2 < stop && buf[p2] == C0_SOH && c0__soh_is_header(buf, p2, stop)) return pos;
1007 pos = c0__comment(buf, pos, stop, err);
1008 if (err->code) return stop;
1009 } else {
1010 return pos;
1011 }
1012 }
1013 return pos;
1014}
1015
1016/* From just after an SOH that is not a header row: past the key, US and value. */
1017static size_t c0__keyed_unit_end(const uint8_t *buf, size_t pos, size_t stop, c0_error *err) {
1018 pos = c0__layout(buf, pos, stop);
1019 pos = c0__plain(buf, pos, stop);
1020 if (!(pos < stop && buf[pos] == C0_US)) {
1021 c0__fail(err, C0_ERR_SYNTAX, pos, "key without a value (no US)");
1022 return stop;
1023 }
1024 return c0__unit(buf, pos + 1, stop, err);
1025}
1026
1027static size_t c0__trim_end(const uint8_t *buf, size_t start, size_t stop) {
1028 while (stop > start && c0_is_layout(buf[stop - 1])) stop--;
1029 return stop;
1030}
1031
1032#define C0__SCAN_WRAP(name, inner) \
1033 size_t name(const uint8_t *buf, size_t pos, size_t stop, c0_error *err) { \
1034 c0_error local = {C0_OK, 0, ""}; \
1035 if (!err) err = &local; \
1036 c0__err_clear(err); \
1037 return inner(buf, pos, stop, err); \
1038 }
1039size_t c0_scan_layout(const uint8_t *buf, size_t pos, size_t stop) { return c0__layout(buf, pos, stop); }
1040size_t c0_scan_plain(const uint8_t *buf, size_t pos, size_t stop) { return c0__plain(buf, pos, stop); }
1041C0__SCAN_WRAP(c0_scan_text, c0__text)
1042C0__SCAN_WRAP(c0_scan_level, c0__level)
1043C0__SCAN_WRAP(c0_scan_unit, c0__unit)
1044C0__SCAN_WRAP(c0_scan_comment, c0__comment)
1045C0__SCAN_WRAP(c0_scan_record_end, c0__record_end)
1046
1047static int c0__eq_str(c0_bytes b, const char *s) {
1048 size_t n = strlen(s);
1049 return b.len == n && (n == 0 || memcmp(b.ptr, s, n) == 0);
1050}
1051
1052/* ---- values ------------------------------------------------------------ */
1053
1055 c0_bytes t = c0_trim(raw);
1056 if (t.len == 0) return C0_UNIT_PLAIN;
1057 switch (t.ptr[0]) {
1058 case C0_STX: return C0_UNIT_TEXT;
1059 case C0_DLE: return C0_UNIT_LEVEL;
1060 case C0_ENQ: return C0_UNIT_REF;
1061 default: return C0_UNIT_PLAIN;
1062 }
1063}
1064
1065/* From pos to the end of t only notes (and layout) may follow. */
1066static c0_status c0__only_notes_after(c0_bytes t, size_t pos) {
1067 c0_error err = {C0_OK, 0, ""};
1068 pos = c0__layout(t.ptr, pos, t.len);
1069 while (pos < t.len) {
1070 if (t.ptr[pos] != C0_BEL) return C0_ERR_SYNTAX;
1071 pos = c0__layout(t.ptr, c0__comment(t.ptr, pos, t.len, &err), t.len);
1072 if (err.code) return err.code;
1073 }
1074 return C0_OK;
1075}
1076
1077c0_status c0_value(c0_bytes raw, uint8_t *scratch, c0_bytes *out) {
1078 c0_bytes t = c0_trim(raw);
1079 c0_error err = {C0_OK, 0, ""};
1080 size_t i;
1081 out->ptr = t.ptr;
1082 out->len = 0;
1083 if (t.len == 0) return C0_OK;
1084 switch (t.ptr[0]) {
1085 case C0_STX: {
1086 size_t stop = c0__text(t.ptr, 0, t.len, &err);
1087 c0_status st;
1088 if (err.code) return err.code;
1089 st = c0__only_notes_after(t, stop);
1090 if (st) return st;
1091 out->ptr = t.ptr + 1;
1092 out->len = stop - 2;
1093 for (i = 0; i < out->len; i++) {
1094 if (out->ptr[i] == C0_DLE) {
1095 if (!scratch) return C0_ERR_NEEDS_DECODE;
1096 out->len = c0_decode_text(out->ptr, out->len, scratch);
1097 out->ptr = scratch;
1098 break;
1099 }
1100 }
1101 return C0_OK;
1102 }
1103 case C0_BEL:
1104 return c0__only_notes_after(t, 0); /* a note or a dead level: the unit is empty */
1105 case C0_DLE:
1106 case C0_ENQ:
1107 return C0_ERR_NOT_SCALAR;
1108 default:
1109 for (i = 0; i < t.len; i++) {
1110 uint8_t b = t.ptr[i];
1111 if (b == C0_BEL) {
1112 c0_status st = c0__only_notes_after(t, i);
1113 if (st) return st;
1114 *out = c0_trim(c0__slice(t.ptr, 0, i));
1115 return C0_OK;
1116 }
1117 if (b < 0x20) return C0_ERR_SYNTAX; /* layout or control code inside a plain value */
1118 }
1119 *out = t;
1120 return C0_OK;
1121 }
1122}
1123
1124c0_body c0_body_view(const uint8_t *buf, size_t len) {
1125 c0_body b;
1126 b.buf = buf;
1127 b.start = 0;
1128 b.stop = len;
1129 return b;
1130}
1131
1133 c0_bytes t = c0_trim(raw);
1134 c0_error err = {C0_OK, 0, ""};
1135 size_t stop;
1136 if (!(t.len > 0 && t.ptr[0] == C0_DLE)) return C0_ERR_NOT_LEVEL;
1137 stop = c0__level(t.ptr, 0, t.len, &err);
1138 if (err.code) return err.code;
1139 out->buf = t.ptr;
1140 out->start = 1;
1141 out->stop = stop - 1;
1142 return C0_OK;
1143}
1144
1145/* ---- records ----------------------------------------------------------- */
1146
1148 size_t p = c0__layout(r.buf, r.start, r.stop);
1149 c0_error err = {C0_OK, 0, ""};
1150 while (p < r.stop && r.buf[p] == C0_BEL) {
1151 size_t p2 = c0__layout(r.buf, p + 1, r.stop);
1152 if (p2 < r.stop && r.buf[p2] == C0_SOH) return !c0__soh_is_header(r.buf, p2, r.stop);
1153 if (p2 >= r.stop || (r.buf[p2] < 0x20 && r.buf[p2] != C0_STX)) break;
1154 p = c0__layout(r.buf, c0__comment(r.buf, p, r.stop, &err), r.stop);
1155 if (err.code) return 0;
1156 }
1157 return p < r.stop && r.buf[p] == C0_SOH && !c0__soh_is_header(r.buf, p, r.stop);
1158}
1159
1161 c0_unit_iter it;
1162 it.buf = r.buf;
1163 it.pos = r.start;
1164 it.stop = r.stop;
1165 it.done = c0_record_keyed(r);
1166 c0__err_clear(&it.err);
1167 return it;
1168}
1169
1170static c0_unit c0__unit_at(const uint8_t *buf, size_t s, size_t e, size_t subs_end, size_t depth) {
1171 c0_unit u;
1172 u.raw = c0__slice(buf, s, e);
1173 u.buf = buf;
1174 u.subs_start = e;
1175 u.subs_end = subs_end;
1176 u.depth = depth;
1177 return u;
1178}
1179
1181 size_t s, e, nx;
1182 if (it->done) return 0;
1183 s = it->pos;
1184 e = c0__unit(it->buf, s, it->stop, &it->err);
1185 nx = e;
1186 if (!it->err.code) nx = c0__skip_subs(it->buf, e, it->stop, &it->err);
1187 if (it->err.code) {
1188 it->done = 1;
1189 return 0;
1190 }
1191 *out = c0__unit_at(it->buf, s, e, nx, 0);
1192 if (nx < it->stop && it->buf[nx] == C0_US) {
1193 it->pos = nx + 1;
1194 } else {
1195 it->done = 1;
1196 }
1197 return 1;
1198}
1199
1200int c0_next_unit(c0_unit_iter *it, c0_bytes *raw) {
1201 c0_unit u;
1202 if (!c0_next_unit_with_subs(it, &u)) return 0;
1203 *raw = u.raw;
1204 return 1;
1205}
1206
1207c0_status c0_record_unit(c0_record r, size_t n, c0_unit *out) {
1209 size_t i = 0;
1210 while (c0_next_unit_with_subs(&it, out)) {
1211 if (i == n) return C0_OK;
1212 i++;
1213 }
1214 return it.err.code ? it.err.code : C0_ERR_NOT_FOUND;
1215}
1216
1218 c0_sub_iter it;
1219 it.buf = u.buf;
1220 it.pos = u.subs_start;
1221 it.stop = u.subs_end;
1222 it.depth = u.depth;
1223 c0__err_clear(&it.err);
1224 return it;
1225}
1226
1227/* Within the parent's sub-unit span the direct children are the sub-units
1228 * one deeper than the parent; a run deeper than that belongs to the child
1229 * before it (the parser has refused skipped depths). */
1230int c0_next_sub(c0_sub_iter *it, c0_unit *out) {
1231 const uint8_t *buf = it->buf;
1232 size_t run, nx, s, e, p;
1233 if (it->err.code) return 0;
1234 p = c0__layout(buf, it->pos, it->stop);
1235 if (!(p < it->stop && buf[p] == C0_SUB)) {
1236 it->pos = it->stop;
1237 return 0;
1238 }
1239 c0__sub_run(buf, p, it->stop, &run, &nx);
1240 if (!(nx < it->stop && buf[nx] == C0_US) || run != it->depth + 1) {
1241 c0__fail(&it->err, C0_ERR_SYNTAX, p, "malformed sub-unit");
1242 it->pos = it->stop;
1243 return 0;
1244 }
1245 s = nx + 1;
1246 e = c0__unit(buf, s, it->stop, &it->err);
1247 if (it->err.code) {
1248 it->pos = it->stop;
1249 return 0;
1250 }
1251 p = e;
1252 for (;;) { /* the child's own sub-units: the deeper runs that follow */
1253 size_t q = c0__layout(buf, p, it->stop), r2, n2;
1254 if (!(q < it->stop && buf[q] == C0_SUB)) break;
1255 c0__sub_run(buf, q, it->stop, &r2, &n2);
1256 if (r2 <= run || !(n2 < it->stop && buf[n2] == C0_US)) break;
1257 p = c0__unit(buf, n2 + 1, it->stop, &it->err);
1258 if (it->err.code) {
1259 it->pos = it->stop;
1260 return 0;
1261 }
1262 }
1263 *out = c0__unit_at(buf, s, e, p, run);
1264 it->pos = p;
1265 return 1;
1266}
1267
1268size_t c0_unit_sub_count(c0_unit u) {
1269 c0_sub_iter it = c0_unit_subs(u);
1270 c0_unit s;
1271 size_t n = 0;
1272 while (c0_next_sub(&it, &s)) n++;
1273 return n;
1274}
1275
1276size_t c0_record_count(c0_record r) {
1278 c0_bytes u;
1279 size_t n = 0;
1280 while (c0_next_unit(&it, &u)) n++;
1281 return n;
1282}
1283
1284c0_status c0_record_field(c0_record r, size_t n, c0_bytes *raw) {
1286 size_t i = 0;
1287 while (c0_next_unit(&it, raw)) {
1288 if (i == n) return C0_OK;
1289 i++;
1290 }
1291 return it.err.code ? it.err.code : C0_ERR_NOT_FOUND;
1292}
1293
1294static c0_pair_iter c0__pairs(const uint8_t *buf, size_t start, size_t stop) {
1295 c0_pair_iter it;
1296 it.buf = buf;
1297 it.pos = start;
1298 it.stop = stop;
1299 c0__err_clear(&it.err);
1300 return it;
1301}
1302
1303c0_pair_iter c0_record_pairs(c0_record r) { return c0__pairs(r.buf, r.start, r.stop); }
1304
1306 const uint8_t *buf = it->buf;
1307 while (it->pos < it->stop) {
1308 uint8_t b = buf[it->pos];
1309 if (b == C0_SOH) {
1310 size_t ks = c0__layout(buf, it->pos + 1, it->stop);
1311 size_t ke = c0__plain(buf, ks, it->stop), vs, ve, nx;
1312 if (!(ke < it->stop && buf[ke] == C0_US)) {
1313 c0__fail(&it->err, C0_ERR_SYNTAX, ke, "key without a value (no US)");
1314 it->pos = it->stop;
1315 return 0;
1316 }
1317 vs = ke + 1;
1318 ve = c0__unit(buf, vs, it->stop, &it->err);
1319 nx = ve;
1320 if (!it->err.code) nx = c0__skip_subs(buf, ve, it->stop, &it->err);
1321 if (it->err.code) {
1322 it->pos = it->stop;
1323 return 0;
1324 }
1325 it->pos = nx;
1326 *key = c0_trim(c0__slice(buf, ks, ke));
1327 *out = c0__unit_at(buf, vs, ve, nx, 0);
1328 return 1;
1329 } else if (b == C0_BEL) {
1330 it->pos = c0__comment(buf, it->pos, it->stop, &it->err);
1331 if (it->err.code) return 0;
1332 } else if (c0_is_layout(b)) {
1333 it->pos++;
1334 } else {
1335 it->pos = it->stop;
1336 return 0;
1337 }
1338 }
1339 return 0;
1340}
1341
1342int c0_next_pair(c0_pair_iter *it, c0_bytes *key, c0_bytes *raw) {
1343 c0_unit u;
1344 if (!c0_next_pair_with_subs(it, key, &u)) return 0;
1345 *raw = u.raw;
1346 return 1;
1347}
1348
1349static c0_status c0__pairs_get(c0_pair_iter it, const uint8_t *key, size_t klen, c0_bytes *raw) {
1350 c0_bytes k, v;
1351 int found = 0;
1352 while (c0_next_pair(&it, &k, &v)) {
1353 if (k.len == klen && (klen == 0 || memcmp(k.ptr, key, klen) == 0)) {
1354 *raw = v;
1355 found = 1;
1356 }
1357 }
1358 if (it.err.code) return it.err.code;
1359 return found ? C0_OK : C0_ERR_NOT_FOUND;
1360}
1361
1362c0_status c0_record_get(c0_record r, const uint8_t *key, size_t klen, c0_bytes *raw) {
1363 return c0__pairs_get(c0_record_pairs(r), key, klen, raw);
1364}
1365
1366c0_status c0_record_get_str(c0_record r, const char *key, c0_bytes *raw) {
1367 return c0_record_get(r, (const uint8_t *)key, strlen(key), raw);
1368}
1369
1370c0_status c0_record_unit_get(c0_record r, const uint8_t *key, size_t klen, c0_unit *out) {
1372 c0_bytes k;
1373 c0_unit u;
1374 int found = 0;
1375 while (c0_next_pair_with_subs(&it, &k, &u)) {
1376 if (k.len == klen && (klen == 0 || memcmp(k.ptr, key, klen) == 0)) {
1377 *out = u;
1378 found = 1;
1379 }
1380 }
1381 if (it.err.code) return it.err.code;
1382 return found ? C0_OK : C0_ERR_NOT_FOUND;
1383}
1384
1385c0_status c0_record_unit_get_str(c0_record r, const char *key, c0_unit *out) {
1386 return c0_record_unit_get(r, (const uint8_t *)key, strlen(key), out);
1387}
1388
1389/* ---- element scanner over a body range ---------------------------------
1390 * Yields the next record-level element at this depth: a record, a header
1391 * row, a group line or a file line, live or dead. Notes and
1392 * commits are skipped. The cursors built on it assume well-formed input
1393 * (the parser below has checked it) and report the result model. */
1394
1395typedef enum { C0__EL_END = 0, C0__EL_RECORD, C0__EL_HEADER, C0__EL_GROUP, C0__EL_FILE } c0__el_kind;
1396
1397typedef struct {
1398 c0__el_kind kind;
1399 int dead; /* BEL before it */
1400 size_t depth; /* GROUP: one plus its SUB prefix */
1401 size_t a, b; /* RECORD/HEADER: the record's range; GROUP/FILE: the name's range */
1402 size_t at; /* where the element (or its BEL / SUB) begins */
1403 size_t next; /* position after the element's own line */
1404} c0__el;
1405
1406static void c0__el_record(const uint8_t *buf, size_t rs, size_t stop, c0__el *el, c0__el_kind kind, c0_error *err) {
1407 size_t e = c0__record_end(buf, rs, stop, err);
1408 el->kind = kind;
1409 el->a = rs;
1410 el->b = c0__trim_end(buf, rs, e);
1411 el->next = e;
1412}
1413
1414static void c0__next_el(const uint8_t *buf, size_t pos, size_t stop, c0__el *el, c0_error *err) {
1415 el->dead = 0;
1416 el->depth = 0;
1417 for (;;) {
1418 uint8_t b;
1419 pos = c0__layout(buf, pos, stop);
1420 el->at = pos;
1421 el->kind = C0__EL_END;
1422 el->next = pos;
1423 if (err->code || pos >= stop) return;
1424 b = buf[pos];
1425 if (b == C0_BEL) {
1426 size_t p2 = c0__layout(buf, pos + 1, stop);
1427 if (p2 >= stop) {
1428 c0__fail(err, C0_ERR_UNEXPECTED_END, p2, "BEL at end of input");
1429 return;
1430 }
1431 if (buf[p2] >= 0x20 || buf[p2] == C0_STX) {
1432 pos = c0__comment(buf, pos, stop, err); /* a note */
1433 continue;
1434 }
1435 el->dead = 1;
1436 pos = p2;
1437 b = buf[pos];
1438 if (b == C0_DLE) {
1439 c0__fail(err, C0_ERR_SYNTAX, pos, "a nested level is not an item");
1440 return;
1441 }
1442 }
1443 if (b == C0_SUB) { /* a group line's depth prefix */
1444 size_t run, p2;
1445 c0__sub_run(buf, pos, stop, &run, &p2);
1446 if (!(p2 < stop && buf[p2] == C0_GS)) {
1447 c0__fail(err, C0_ERR_SYNTAX, pos, "SUB before a byte that is not GS or US");
1448 return;
1449 }
1450 el->depth = run;
1451 pos = p2;
1452 b = C0_GS;
1453 }
1454 if (b == C0_RS) {
1455 c0__el_record(buf, pos + 1, stop, el, C0__EL_RECORD, err);
1456 return;
1457 }
1458 if (b == C0_SOH) {
1459 size_t p2 = c0__layout(buf, pos + 1, stop);
1460 if (p2 < stop && buf[p2] == C0_RS) {
1461 c0__el_record(buf, p2 + 1, stop, el, C0__EL_HEADER, err);
1462 return;
1463 }
1464 c0__fail(err, C0_ERR_SYNTAX, pos, "keyed unit outside a record");
1465 return;
1466 }
1467 if (b == C0_GS) {
1468 el->depth++;
1469 pos = c0__layout(buf, pos + 1, stop);
1470 el->kind = C0__EL_GROUP;
1471 el->a = pos;
1472 el->b = el->next = c0__plain(buf, pos, stop);
1473 return;
1474 }
1475 if (b == C0_FS) {
1476 el->kind = C0__EL_FILE;
1477 el->a = c0__layout(buf, pos + 1, stop);
1478 el->b = el->next = c0__plain(buf, el->a, stop);
1479 return;
1480 }
1481 if (el->dead) {
1482 c0__fail(err, C0_ERR_SYNTAX, pos, "BEL before a code that is not an element");
1483 return;
1484 }
1485 if (b == C0_ETB) {
1486 pos = c0__plain(buf, c0__layout(buf, pos + 1, stop), stop);
1487 continue;
1488 }
1489 if (b == C0_EOT || b == C0_SYN || b == C0_EM) return; /* the body ends here */
1490 if (b == C0_CAN) {
1491 c0__fail(err, C0_ERR_SYNTAX, pos, "CAN with no open level");
1492 } else if (b < 0x20 && !c0__assigned[b]) {
1493 c0__fail(err, C0_ERR_UNASSIGNED, pos, "unassigned control code");
1494 } else {
1495 c0__fail(err, C0_ERR_SYNTAX, pos, "unexpected byte at element level");
1496 }
1497 return;
1498 }
1499}
1500
1501/* After a dead group line (el): skip what it holds. Returns the position of
1502 * the element that ends its span (a group line at its depth or shallower, a
1503 * file line, or the end), which the caller reads next. */
1504static size_t c0__skip_dead_group(const uint8_t *buf, const c0__el *dead, size_t stop, c0_error *err) {
1505 size_t pos = dead->next;
1506 c0__el el;
1507 for (;;) {
1508 c0__next_el(buf, pos, stop, &el, err);
1509 if (el.kind == C0__EL_END || el.kind == C0__EL_FILE) return el.at;
1510 if (el.kind == C0__EL_GROUP && el.depth <= dead->depth) return el.at;
1511 pos = el.next;
1512 }
1513}
1514
1515/* After a dead file line: skip what it holds, up to the next file line or
1516 * the end. */
1517static size_t c0__skip_dead_file(const uint8_t *buf, const c0__el *dead, size_t stop, c0_error *err) {
1518 size_t pos = dead->next;
1519 c0__el el;
1520 for (;;) {
1521 c0__next_el(buf, pos, stop, &el, err);
1522 if (el.kind == C0__EL_END || el.kind == C0__EL_FILE) return el.at;
1523 pos = el.next;
1524 }
1525}
1526
1527/* ---- bodies: files ------------------------------------------------------ */
1528
1529c0_bytes c0_file_name(c0_file f) { return c0_trim(c0__slice(f.buf, f.name_start, f.name_end)); }
1530c0_bytes c0_group_name(c0_group g) { return c0_trim(c0__slice(g.buf, g.name_start, g.name_end)); }
1531
1533 c0_file_iter it;
1534 it.buf = b.buf;
1535 it.pos = b.start;
1536 it.stop = b.stop;
1537 it.first = 1;
1538 it.done = 0;
1539 c0__err_clear(&it.err);
1540 return it;
1541}
1542
1543/* Scan a file's contents from pos to the next file line (live or dead) or
1544 * the end; *has says whether a live element (outside dead spans) was passed. */
1545static void c0__part_end(const uint8_t *buf, size_t pos, size_t stop, c0__el *el, int *has, c0_error *err) {
1546 *has = 0;
1547 for (;;) {
1548 c0__next_el(buf, pos, stop, el, err);
1549 if (el->kind == C0__EL_END || el->kind == C0__EL_FILE || err->code) return;
1550 if (el->dead) {
1551 pos = el->kind == C0__EL_GROUP ? c0__skip_dead_group(buf, el, stop, err) : el->next;
1552 continue;
1553 }
1554 *has = 1;
1555 pos = el->next;
1556 }
1557}
1558
1559int c0_next_file(c0_file_iter *it, c0_file *out) {
1560 c0__el el;
1561 for (;;) {
1562 int have = 0, has;
1563 if (it->done || it->err.code) return 0;
1564 out->buf = it->buf;
1565 if (it->first) {
1566 it->first = 0;
1567 c0__part_end(it->buf, it->pos, it->stop, &el, &has, &it->err);
1568 out->leading = 1;
1569 out->name_start = out->name_end = it->pos;
1570 out->start = it->pos;
1571 out->stop = el.at;
1572 have = has;
1573 } else {
1574 c0__next_el(it->buf, it->pos, it->stop, &el, &it->err);
1575 if (el.kind != C0__EL_FILE) {
1576 it->done = 1;
1577 return 0;
1578 }
1579 out->leading = 0;
1580 out->name_start = el.a;
1581 out->name_end = el.b;
1582 out->start = el.next;
1583 c0__part_end(it->buf, el.next, it->stop, &el, &has, &it->err);
1584 out->stop = el.at;
1585 have = 1;
1586 }
1587 /* dead files after this one are dropped with their contents */
1588 while (el.kind == C0__EL_FILE && el.dead && !it->err.code) {
1589 size_t p = c0__skip_dead_file(it->buf, &el, it->stop, &it->err);
1590 c0__next_el(it->buf, p, it->stop, &el, &it->err);
1591 }
1592 if (it->err.code) return 0;
1593 if (el.kind == C0__EL_END) {
1594 /* a body with no live file, every element dead included, is an
1595 * empty body: it has one empty leading file */
1596 if (out->leading) have = 1;
1597 it->done = 1;
1598 it->pos = it->stop;
1599 } else {
1600 it->pos = el.at;
1601 }
1602 if (have) return 1;
1603 }
1604}
1605
1606/* ---- bodies: groups ---------------------------------------------------- */
1607
1608static c0_group_iter c0__groups(const uint8_t *buf, size_t start, size_t stop) {
1609 c0_group_iter it;
1610 it.buf = buf;
1611 it.pos = start;
1612 it.stop = stop;
1613 it.first = 1;
1614 it.done = 0;
1615 c0__err_clear(&it.err);
1616 return it;
1617}
1618
1619c0_group_iter c0_file_groups(c0_file f) { return c0__groups(f.buf, f.start, f.stop); }
1620c0_group_iter c0_body_groups(c0_body b) { return c0__groups(b.buf, b.start, b.stop); }
1621
1622/* Scan a group's own contents from pos: stop at the next group or file line
1623 * (live or dead) or the end; *has says whether a live header row or record
1624 * was passed. */
1625static void c0__group_end(const uint8_t *buf, size_t pos, size_t stop, c0__el *el, int *has, c0_error *err) {
1626 *has = 0;
1627 for (;;) {
1628 c0__next_el(buf, pos, stop, el, err);
1629 if (el->kind == C0__EL_END || el->kind == C0__EL_GROUP || el->kind == C0__EL_FILE || err->code) return;
1630 if (!el->dead) *has = 1;
1631 pos = el->next;
1632 }
1633}
1634
1635int c0_next_group(c0_group_iter *it, c0_group *out) {
1636 c0__el el;
1637 int has;
1638 out->buf = it->buf;
1639 for (;;) {
1640 if (it->done || it->err.code) return 0;
1641 if (it->first) {
1642 size_t start = it->pos;
1643 it->first = 0;
1644 c0__group_end(it->buf, start, it->stop, &el, &has, &it->err);
1645 it->pos = el.at;
1646 if (el.kind == C0__EL_END) it->done = 1;
1647 if (has) { /* the unnamed group: from where the scan began */
1648 out->depth = 0;
1649 out->name_start = out->name_end = out->start = start;
1650 out->stop = el.at;
1651 return 1;
1652 }
1653 continue;
1654 }
1655 c0__next_el(it->buf, it->pos, it->stop, &el, &it->err);
1656 if (el.kind == C0__EL_END || it->err.code) {
1657 it->done = 1;
1658 return 0;
1659 }
1660 if (el.kind == C0__EL_FILE) { /* body-wide iteration: a new part begins */
1661 if (el.dead) {
1662 it->pos = c0__skip_dead_file(it->buf, &el, it->stop, &it->err);
1663 } else {
1664 it->first = 1;
1665 it->pos = el.next;
1666 }
1667 continue;
1668 }
1669 if (el.dead) {
1670 it->pos = c0__skip_dead_group(it->buf, &el, it->stop, &it->err);
1671 continue;
1672 }
1673 out->depth = el.depth;
1674 out->name_start = el.a;
1675 out->name_end = el.b;
1676 out->start = el.next;
1677 c0__group_end(it->buf, el.next, it->stop, &el, &has, &it->err);
1678 out->stop = el.at;
1679 it->pos = el.at;
1680 if (el.kind == C0__EL_END) it->done = 1;
1681 return 1;
1682 }
1683}
1684
1685c0_status c0_body_find_group(c0_body b, const uint8_t *name, size_t nlen, c0_group *out) {
1687 while (c0_next_group(&it, out)) {
1688 c0_bytes n = c0_group_name(*out);
1689 if (n.len == nlen && (nlen == 0 || memcmp(n.ptr, name, nlen) == 0)) return C0_OK;
1690 }
1691 return it.err.code ? it.err.code : C0_ERR_NOT_FOUND;
1692}
1693
1694c0_status c0_body_find_group_str(c0_body b, const char *name, c0_group *out) {
1695 return c0_body_find_group(b, (const uint8_t *)name, strlen(name), out);
1696}
1697
1698int c0_body_bare(c0_body b) {
1700 c0_file f;
1701 c0_group_iter gi;
1702 c0_group g;
1703 size_t n = 0;
1704 if (!c0_next_file(&fi, &f)) return 0;
1705 if (!f.leading) return 0;
1706 if (c0_next_file(&fi, &f)) return 0;
1707 gi = c0_file_groups(f);
1708 while (c0_next_group(&gi, &g)) {
1709 n++;
1710 if (n > 1 || g.depth != 0) return 0;
1711 }
1712 return 1;
1713}
1714
1715int c0_group_header(c0_group g, c0_record *out) {
1716 c0_error err = {C0_OK, 0, ""};
1717 size_t pos = g.start;
1718 c0__el el;
1719 for (;;) {
1720 c0__next_el(g.buf, pos, g.stop, &el, &err);
1721 if (el.kind == C0__EL_END || err.code) return 0;
1722 if (el.kind == C0__EL_HEADER && !el.dead) {
1723 out->buf = g.buf;
1724 out->start = el.a;
1725 out->stop = el.b;
1726 return 1;
1727 }
1728 pos = el.next;
1729 }
1730}
1731
1733 c0_record_iter it;
1734 it.buf = g.buf;
1735 it.pos = g.start;
1736 it.stop = g.stop;
1737 it.done = 0;
1738 c0__err_clear(&it.err);
1739 return it;
1740}
1741
1744 c0_file f;
1745 c0_group_iter gi;
1746 c0_group g;
1747 c0_record_iter it;
1748 if (c0_next_file(&fi, &f)) {
1749 gi = c0_file_groups(f);
1750 if (c0_next_group(&gi, &g)) return c0_group_records(g);
1751 }
1752 it.buf = b.buf;
1753 it.pos = it.stop = b.start;
1754 it.done = 1;
1755 c0__err_clear(&it.err);
1756 return it;
1757}
1758
1760 c0__el el;
1761 if (it->done) return 0;
1762 for (;;) {
1763 c0__next_el(it->buf, it->pos, it->stop, &el, &it->err);
1764 if (el.kind == C0__EL_END || it->err.code) {
1765 it->done = 1;
1766 return 0;
1767 }
1768 it->pos = el.next;
1769 if (el.kind == C0__EL_RECORD && !el.dead) {
1770 out->buf = it->buf;
1771 out->start = el.a;
1772 out->stop = el.b;
1773 return 1;
1774 }
1775 }
1776}
1777
1778c0_status c0_group_column(c0_group g, const uint8_t *name, size_t nlen, size_t *index) {
1779 c0_record h;
1780 c0_unit_iter it;
1781 c0_bytes raw, v;
1782 size_t i = 0;
1783 if (!c0_group_header(g, &h)) return C0_ERR_NOT_FOUND;
1784 it = c0_record_units(h);
1785 while (c0_next_unit(&it, &raw)) {
1786 if (c0_value(raw, NULL, &v) == C0_OK && v.len == nlen && (nlen == 0 || memcmp(v.ptr, name, nlen) == 0)) {
1787 *index = i;
1788 return C0_OK;
1789 }
1790 i++;
1791 }
1792 return C0_ERR_NOT_FOUND;
1793}
1794
1796 c0_body body;
1797 c0_status st = c0_unit_level(raw, &body);
1798 c0_file_iter fi;
1799 c0_file f;
1800 c0_group_iter gi;
1801 c0_group g;
1802 c0_record_iter ri;
1803 c0_record r;
1804 if (st) return st;
1805 items->buf = body.buf;
1806 items->pos = items->stop = body.start;
1807 items->done = 1;
1808 c0__err_clear(&items->err);
1809 fi = c0_body_files(body);
1810 if (!c0_next_file(&fi, &f)) return C0_OK; /* an empty level: no items */
1811 if (!f.leading || c0_next_file(&fi, &f)) return C0_ERR_NOT_LIST;
1812 gi = c0_file_groups(f);
1813 if (!c0_next_group(&gi, &g)) return C0_OK;
1814 if (g.depth != 0 || c0_next_group(&gi, &g)) return C0_ERR_NOT_LIST;
1815 if (c0_group_header(g, &r)) return C0_ERR_NOT_LIST;
1816 ri = c0_group_records(g);
1817 if (!c0_next_record(&ri, &r)) return ri.err.code ? ri.err.code : C0_OK;
1818 if (c0_record_keyed(r)) return C0_ERR_NOT_LIST;
1819 *items = c0_record_units(r);
1820 if (c0_next_record(&ri, &r)) return C0_ERR_NOT_LIST;
1821 return C0_OK;
1822}
1823
1824/* ---- the parser (GRAMMAR.md; parser.cr) ---------------------------------
1825 * One walk of the grammar under everything else. It raises on the first
1826 * structural error (recorded in err; every function then returns `stop` so
1827 * loops end), notes every canonical violation when asked, and counts the
1828 * dead elements met in bodies for tools above the format. Body level is a
1829 * flat state machine over lines
1830 * (file line, group line, header row, record, note, commit) whose state is
1831 * a c0_parse_state, so a stream reader can carry it from block to block;
1832 * records and their values are recursive, since a level holds a body. */
1833
1834#define C0__MAX_DEPTH 512
1835#define C0__GS_DEPTH_MAX 256
1836
1837typedef struct {
1838 const uint8_t *buf;
1839 int canonical; /* check the canonical constraints too */
1840 int ok; /* no canonical violation met */
1841 size_t dead_elements;
1842 size_t depth; /* open levels */
1843 c0_error err;
1844} c0__parser;
1845
1846#define C0__P_ERR(p) ((p)->err.code != C0_OK)
1847
1848enum { C0__PH_START = 0, C0__PH_BODY, C0__PH_AFTER_EOT, C0__PH_EM };
1849
1850static void c0__p_init(c0__parser *p, const uint8_t *buf, int canonical) {
1851 p->buf = buf;
1852 p->canonical = canonical;
1853 p->ok = 1;
1854 p->dead_elements = 0;
1855 p->depth = 0;
1856 c0__err_clear(&p->err);
1857}
1858
1859static void c0__p_nc(c0__parser *p) { p->ok = 0; }
1860
1861static void c0__p_fail(c0__parser *p, c0_status code, size_t pos, const char *msg) { c0__fail(&p->err, code, pos, msg); }
1862
1863static size_t c0__p_layout(c0__parser *p, size_t pos, size_t stop) {
1864 size_t p2 = c0__layout(p->buf, pos, stop);
1865 if (p2 != pos) c0__p_nc(p);
1866 return p2;
1867}
1868
1869/* The body state at the start of a document. */
1870static void c0__st_body_reset(c0_parse_state *s, int in_level) {
1871 s->in_level = in_level;
1872 s->leading = 1;
1873 s->dead_file = 0;
1874 s->dead_depth = 0;
1875 s->prev_depth = 0;
1876 s->header_ok = 1;
1877 s->file_has_groups = 0;
1878 s->nfiles = 0;
1879}
1880
1881static void c0__st_init(c0_parse_state *s) {
1882 s->phase = C0__PH_START;
1883 s->first = 1;
1884 c0__st_body_reset(s, 0);
1885}
1886
1887static size_t c0__p_body(c0__parser *p, c0_parse_state *s, size_t pos, size_t stop);
1888static size_t c0__p_record(c0__parser *p, size_t pos, size_t stop);
1889static size_t c0__p_value(c0__parser *p, size_t pos, size_t stop, int heading);
1890static size_t c0__p_level(c0__parser *p, size_t pos, size_t stop);
1891static size_t c0__p_reference(c0__parser *p, size_t pos, size_t stop);
1892
1893/* The content of a note, from the byte after BEL and layout. */
1894static size_t c0__p_note_content(c0__parser *p, size_t pos, size_t stop) {
1895 return p->buf[pos] == C0_STX ? c0__text(p->buf, pos, stop, &p->err) : c0__plain(p->buf, pos, stop);
1896}
1897
1898/* Notes after a value. A BEL before a code is left for the caller. */
1899static size_t c0__p_trailing_notes(c0__parser *p, size_t pos, size_t stop) {
1900 const uint8_t *buf = p->buf;
1901 while (pos < stop && buf[pos] == C0_BEL) {
1902 size_t p2 = c0__layout(buf, pos + 1, stop);
1903 uint8_t c;
1904 if (p2 >= stop) {
1905 c0__p_fail(p, C0_ERR_UNEXPECTED_END, p2, "BEL at end of input");
1906 return stop;
1907 }
1908 c = buf[p2];
1909 if (!(c >= 0x20 || c == C0_STX)) break;
1910 c0__p_nc(p);
1911 pos = c0__p_note_content(p, p2, stop);
1912 if (C0__P_ERR(p)) return stop;
1913 pos = c0__p_layout(p, pos, stop);
1914 }
1915 return pos;
1916}
1917
1918static int c0__value_start(const uint8_t *buf, size_t pos, size_t stop) {
1919 uint8_t b;
1920 if (pos >= stop) return 0;
1921 b = buf[pos];
1922 return b >= 0x20 || b == C0_STX || b == C0_DLE || b == C0_ENQ;
1923}
1924
1925/* A label or path: plain, never text. *ns / *ne get the trimmed name. */
1926static size_t c0__p_name(c0__parser *p, size_t pos, size_t stop, size_t *ns, size_t *ne) {
1927 const uint8_t *buf = p->buf;
1928 size_t e;
1929 pos = c0__p_layout(p, pos, stop);
1930 if (pos < stop && buf[pos] == C0_STX) {
1931 c0__p_fail(p, C0_ERR_SYNTAX, pos, "a name cannot be text");
1932 return stop;
1933 }
1934 *ns = pos;
1935 pos = c0__plain(buf, pos, stop);
1936 e = c0__trim_end(buf, *ns, pos);
1937 if (e != pos) c0__p_nc(p);
1938 *ne = e;
1939 return pos;
1940}
1941
1942/* After SOH RS: names, each followed by notes, separated by US. */
1943static size_t c0__p_header_row(c0__parser *p, size_t pos, size_t stop) {
1944 const uint8_t *buf = p->buf;
1945 size_t ns, ne;
1946 for (;;) {
1947 pos = c0__p_name(p, pos, stop, &ns, &ne);
1948 if (C0__P_ERR(p)) return stop;
1949 pos = c0__p_trailing_notes(p, c0__p_layout(p, pos, stop), stop);
1950 if (C0__P_ERR(p)) return stop;
1951 if (!(pos < stop && buf[pos] == C0_US)) break;
1952 pos++;
1953 }
1954 if (pos < stop && buf[pos] == C0_SUB) {
1955 size_t run, p2;
1956 c0__sub_run(buf, pos, stop, &run, &p2);
1957 if (p2 < stop && buf[p2] == C0_US) {
1958 c0__p_fail(p, C0_ERR_SYNTAX, pos, "a header row admits no sub-units");
1959 return stop;
1960 }
1961 }
1962 return pos;
1963}
1964
1965/* One unit's value, possibly empty, with the notes after it. Returns the
1966 * position of the next code at this depth. */
1967static size_t c0__p_value(c0__parser *p, size_t pos, size_t stop, int heading) {
1968 const uint8_t *buf = p->buf;
1969 size_t after;
1970 uint8_t b;
1971 pos = c0__p_layout(p, pos, stop);
1972 if (pos >= stop) return pos;
1973 b = buf[pos];
1974 if (b >= 0x20) {
1975 pos = c0__plain(buf, pos, stop);
1976 if (buf[pos - 1] == C0_SP) c0__p_nc(p);
1977 } else if (b == C0_STX) {
1978 size_t start = pos;
1979 pos = c0__text(buf, pos, stop, &p->err);
1980 if (C0__P_ERR(p)) return stop;
1981 if (p->canonical) {
1982 size_t n = pos - start - 2, i;
1983 int plain = n > 0 && !c0_is_layout(buf[start + 1]) && !c0_is_layout(buf[pos - 2]);
1984 for (i = 0; plain && i < n; i++) {
1985 if (buf[start + 1 + i] < 0x20) plain = 0; /* a control byte, or a DLE escaping one */
1986 }
1987 if (n == 0 || plain) c0__p_nc(p); /* empty or gratuitous text */
1988 }
1989 } else if (b == C0_DLE) {
1990 pos = c0__p_level(p, pos, stop);
1991 if (C0__P_ERR(p)) return stop;
1992 } else if (b == C0_ENQ) {
1993 if (heading) {
1994 c0__p_fail(p, C0_ERR_SYNTAX, pos, "reference in a heading");
1995 return stop;
1996 }
1997 pos = c0__p_reference(p, pos, stop);
1998 if (C0__P_ERR(p)) return stop;
1999 } else if (b == C0_BEL) {
2000 size_t p2 = c0__layout(buf, pos + 1, stop);
2001 uint8_t c;
2002 if (p2 >= stop) {
2003 c0__p_fail(p, C0_ERR_UNEXPECTED_END, p2, "BEL at end of input");
2004 return stop;
2005 }
2006 c = buf[p2];
2007 if (c == C0_DLE) {
2008 c0__p_nc(p); /* a dead level: the unit is empty */
2009 pos = c0__p_level(p, p2, stop);
2010 if (C0__P_ERR(p)) return stop;
2011 } else if (c >= 0x20 || c == C0_STX) {
2012 pos = c0__p_trailing_notes(p, pos, stop);
2013 if (C0__P_ERR(p)) return stop;
2014 if (c0__value_start(buf, pos, stop)) {
2015 c0__p_fail(p, C0_ERR_SYNTAX, pos, "value after a note in the same unit");
2016 return stop;
2017 }
2018 return pos;
2019 } else {
2020 return pos; /* a dead element after this empty unit: the caller's business */
2021 }
2022 } else {
2023 return pos; /* an empty unit */
2024 }
2025 after = c0__p_trailing_notes(p, c0__p_layout(p, pos, stop), stop);
2026 if (C0__P_ERR(p)) return stop;
2027 if (c0__value_start(buf, after, stop)) {
2028 c0__p_fail(p, C0_ERR_SYNTAX, after, "two values in one unit");
2029 return stop;
2030 }
2031 return after;
2032}
2033
2034/* After SOH (not a header row): key, US, value. *ks / *ke get the key. */
2035static size_t c0__p_keyed_unit(c0__parser *p, size_t pos, size_t stop, int heading, size_t *ks, size_t *ke, size_t *vs) {
2036 pos = c0__p_name(p, pos, stop, ks, ke);
2037 if (C0__P_ERR(p)) return stop;
2038 if (!(pos < stop && p->buf[pos] == C0_US)) {
2039 c0__p_fail(p, C0_ERR_SYNTAX, pos, "key without a value (no US)");
2040 return stop;
2041 }
2042 *vs = pos + 1;
2043 return c0__p_value(p, *vs, stop, heading);
2044}
2045
2046/* Does the record starting here begin with a keyed unit, live or dead? */
2047static int c0__p_keyed_start(c0__parser *p, size_t pos, size_t stop) {
2048 const uint8_t *buf = p->buf;
2049 for (;;) {
2050 uint8_t b;
2051 size_t p2;
2052 pos = c0__layout(buf, pos, stop);
2053 if (pos >= stop) return 0;
2054 b = buf[pos];
2055 if (b == C0_SOH) return !c0__soh_is_header(buf, pos, stop);
2056 if (b != C0_BEL) return 0;
2057 p2 = c0__layout(buf, pos + 1, stop);
2058 if (p2 >= stop) return 0;
2059 if (buf[p2] == C0_SOH) return !c0__soh_is_header(buf, p2, stop);
2060 if (!(buf[p2] >= 0x20 || buf[p2] == C0_STX)) return 0;
2061 pos = c0__p_note_content(p, p2, stop); /* a note: look past it */
2062 if (C0__P_ERR(p)) return 0;
2063 }
2064}
2065
2066/* The sub-units after a unit's value at pos: runs of SUB, each then US and
2067 * a value, the run's length the sub-unit's depth, at most one deeper than
2068 * the sub-unit before it. Returns the position after the last. A SUB run
2069 * that prefixes a line code (RS, GS, FS) is left for the body, which
2070 * refuses the reserved grains; the other reserved or stray SUBs fail here. */
2071static size_t c0__p_sub_units(c0__parser *p, size_t pos, size_t stop) {
2072 const uint8_t *buf = p->buf;
2073 size_t prev = 0;
2074 for (;;) {
2075 size_t start, run = 0, nx;
2076 uint8_t c;
2077 start = c0__p_layout(p, pos, stop);
2078 if (!(start < stop && buf[start] == C0_SUB)) return pos;
2079 nx = start;
2080 while (nx < stop && buf[nx] == C0_SUB) {
2081 run++;
2082 nx = c0__p_layout(p, nx + 1, stop);
2083 }
2084 if (nx >= stop) {
2085 c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB at the end of input");
2086 return stop;
2087 }
2088 c = buf[nx];
2089 if (c == C0_US) {
2090 if (run > prev + 1) {
2091 c0__p_fail(p, C0_ERR_SYNTAX, start, "depth skipped: a sub-unit is at most one deeper than the sub-unit before it");
2092 return stop;
2093 }
2094 prev = run;
2095 pos = c0__p_value(p, nx + 1, stop, 0);
2096 if (C0__P_ERR(p)) return stop;
2097 } else if (c == C0_RS || c == C0_GS || c == C0_FS) {
2098 return pos; /* a prefix before the next line: the body's business */
2099 } else if (c == C0_SOH) {
2100 if (c0__soh_is_header(buf, nx, stop)) c0__p_fail(p, C0_ERR_SYNTAX, start, "a header row admits no SUB");
2101 else c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB before SOH is reserved (a sub-key)");
2102 return stop;
2103 } else if (c == C0_BEL) {
2104 c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB before BEL");
2105 return stop;
2106 } else {
2107 c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB before a byte that is not a separator");
2108 return stop;
2109 }
2110 }
2111}
2112
2113static size_t c0__p_positional(c0__parser *p, size_t pos, size_t stop) {
2114 const uint8_t *buf = p->buf;
2115 for (;;) {
2116 uint8_t b;
2117 pos = c0__p_value(p, pos, stop, 0);
2118 if (C0__P_ERR(p)) return stop;
2119 pos = c0__p_sub_units(p, pos, stop);
2120 if (C0__P_ERR(p)) return stop;
2121 pos = c0__p_layout(p, pos, stop);
2122 if (pos >= stop) break;
2123 b = buf[pos];
2124 if (b == C0_US) {
2125 pos++;
2126 } else if (b == C0_SUB) {
2127 break; /* a prefix before the next line: the body's business */
2128 } else if (b == C0_SOH) {
2129 if (c0__soh_is_header(buf, pos, stop)) break; /* a header row ends the record */
2130 c0__p_fail(p, C0_ERR_SYNTAX, pos, "keyed unit in a positional record (mixed record)");
2131 return stop;
2132 } else {
2133 break;
2134 }
2135 }
2136 return pos;
2137}
2138
2139/* Keys in [start, stop) must be unique (any order): canonical only. */
2140static void c0__p_check_keys(c0__parser *p, size_t start, size_t stop) {
2141 c0_pair_iter a = c0__pairs(p->buf, start, stop);
2142 c0_bytes k, k2, raw;
2143 while (c0_next_pair(&a, &k, &raw)) {
2144 c0_pair_iter rest = a;
2145 while (c0_next_pair(&rest, &k2, &raw)) {
2146 if (k2.len == k.len && (k.len == 0 || memcmp(k.ptr, k2.ptr, k.len) == 0)) c0__p_nc(p);
2147 }
2148 }
2149}
2150
2151static size_t c0__p_keyed(c0__parser *p, size_t pos, size_t stop) {
2152 const uint8_t *buf = p->buf;
2153 size_t start = pos, ks, ke, vs;
2154 for (;;) {
2155 uint8_t b;
2156 pos = c0__p_layout(p, pos, stop);
2157 if (pos >= stop) break;
2158 b = buf[pos];
2159 if (b == C0_SOH) {
2160 if (c0__soh_is_header(buf, pos, stop)) break;
2161 pos = c0__p_keyed_unit(p, pos + 1, stop, 0, &ks, &ke, &vs);
2162 if (C0__P_ERR(p)) return stop;
2163 pos = c0__p_sub_units(p, pos, stop);
2164 if (C0__P_ERR(p)) return stop;
2165 } else if (b == C0_BEL) {
2166 size_t p2 = c0__layout(buf, pos + 1, stop);
2167 uint8_t c;
2168 if (p2 >= stop) {
2169 c0__p_fail(p, C0_ERR_UNEXPECTED_END, p2, "BEL at end of input");
2170 return stop;
2171 }
2172 c = buf[p2];
2173 if (c == C0_SOH) {
2174 if (c0__soh_is_header(buf, p2, stop)) break;
2175 c0__p_nc(p); /* a dead keyed unit */
2176 pos = c0__p_keyed_unit(p, p2 + 1, stop, 0, &ks, &ke, &vs);
2177 if (C0__P_ERR(p)) return stop;
2178 pos = c0__p_sub_units(p, pos, stop);
2179 if (C0__P_ERR(p)) return stop;
2180 } else if (c >= 0x20 || c == C0_STX) {
2181 pos = c0__p_trailing_notes(p, pos, stop);
2182 if (C0__P_ERR(p)) return stop;
2183 } else if (c == C0_SUB) {
2184 c0__p_fail(p, C0_ERR_SYNTAX, p2, "BEL before a sub-unit: a unit cannot be dead");
2185 return stop;
2186 } else {
2187 break;
2188 }
2189 } else if (b == C0_SUB) {
2190 break; /* a prefix before the next line: the body's business */
2191 } else {
2192 break;
2193 }
2194 }
2195 if (pos < stop && buf[pos] == C0_US) {
2196 c0__p_fail(p, C0_ERR_SYNTAX, pos, "US after a keyed value (mixed record)");
2197 return stop;
2198 }
2199 if (p->canonical) c0__p_check_keys(p, start, pos);
2200 return pos;
2201}
2202
2203/* After RS. Returns the position after the record. */
2204static size_t c0__p_record(c0__parser *p, size_t pos, size_t stop) {
2205 return c0__p_keyed_start(p, pos, stop) ? c0__p_keyed(p, pos, stop) : c0__p_positional(p, pos, stop);
2206}
2207
2208/* DLE at pos: a nested level. Returns the position after its CAN. */
2209static size_t c0__p_level(c0__parser *p, size_t pos, size_t stop) {
2210 const uint8_t *buf = p->buf;
2211 size_t start = pos;
2212 uint8_t b;
2213 c0_parse_state st;
2214 if (++p->depth > C0__MAX_DEPTH) {
2215 c0__p_fail(p, C0_ERR_TOO_DEEP, pos, "levels nested too deep");
2216 return stop;
2217 }
2218 pos = c0__p_layout(p, pos + 1, stop);
2219 if (pos >= stop) {
2220 c0__p_fail(p, C0_ERR_UNEXPECTED_END, start, "level is not closed");
2221 return stop;
2222 }
2223 b = buf[pos];
2224 if (b == C0_CAN) {
2225 p->depth--;
2226 return pos + 1;
2227 }
2228 if (!(b == C0_FS || b == C0_GS || b == C0_RS || b == C0_SOH || b == C0_BEL || b == C0_SUB)) {
2229 c0__p_fail(p, C0_ERR_SYNTAX, pos, "DLE must be followed by a structural code");
2230 return stop;
2231 }
2232 c0__st_body_reset(&st, 1);
2233 pos = c0__p_body(p, &st, pos, stop);
2234 if (C0__P_ERR(p)) return stop;
2235 pos = c0__p_layout(p, pos, stop);
2236 if (pos >= stop) {
2237 c0__p_fail(p, C0_ERR_UNEXPECTED_END, start, "level is not closed");
2238 return stop;
2239 }
2240 if (buf[pos] != C0_CAN) {
2241 c0__p_fail(p, C0_ERR_SYNTAX, pos, "unexpected byte inside level");
2242 return stop;
2243 }
2244 p->depth--;
2245 return pos + 1;
2246}
2247
2248/* A pattern (DESIGN.md, References) is one branch of the target with its
2249 * values left out: the level [start, stop) has been parsed; walk it with
2250 * the cursors. `inner` is a pattern continued into a level, whose records
2251 * may stand in the unnamed group. */
2252static void c0__p_check_pattern(c0__parser *p, const uint8_t *buf, size_t start, size_t stop, int inner, size_t at) {
2253 c0_body body;
2254 c0_file_iter fi;
2255 c0_file f;
2256 c0_group_iter gi;
2257 c0_group g, last;
2258 c0_record_iter ri;
2259 c0_record r, h;
2260 size_t ngroups = 0, prev = 0, nrecs = 0, i;
2261 int have_prev = 0;
2262 memset(&last, 0, sizeof(last));
2263 body.buf = buf;
2264 body.start = start;
2265 body.stop = stop;
2266 fi = c0_body_files(body);
2267 if (!c0_next_file(&fi, &f)) {
2268 c0__p_fail(p, C0_ERR_SYNTAX, at, inner ? "an empty level continues nothing" : "an empty level is not a reference");
2269 return;
2270 }
2271 if (c0_next_file(&fi, &f)) {
2272 c0__p_fail(p, C0_ERR_SYNTAX, at, "a pattern is one branch: two files");
2273 return;
2274 }
2275 gi = c0_file_groups(f);
2276 while (c0_next_group(&gi, &g)) {
2277 if (ngroups == 0 && !inner && g.depth == 0) {
2278 c0__p_fail(p, C0_ERR_SYNTAX, at, "a pattern begins with a file or group line");
2279 return;
2280 }
2281 if (c0_group_header(g, &h)) {
2282 c0__p_fail(p, C0_ERR_SYNTAX, at, "a header row is not a step of a pattern");
2283 return;
2284 }
2285 if (have_prev && g.depth <= prev) {
2286 c0__p_fail(p, C0_ERR_SYNTAX, at, "a pattern is one branch: two groups at one depth");
2287 return;
2288 }
2289 if (ngroups > 0) { /* the group before holds no record: nothing follows a record */
2290 ri = c0_group_records(last);
2291 if (c0_next_record(&ri, &r)) {
2292 c0__p_fail(p, C0_ERR_SYNTAX, at, "nothing follows the record in a pattern");
2293 return;
2294 }
2295 }
2296 prev = g.depth;
2297 have_prev = 1;
2298 last = g;
2299 ngroups++;
2300 }
2301 if (ngroups == 0) {
2302 c0__p_fail(p, C0_ERR_SYNTAX, at, inner ? "an empty level continues nothing" : "an empty level is not a reference");
2303 return;
2304 }
2305 ri = c0_group_records(last);
2306 while (c0_next_record(&ri, &r)) nrecs++;
2307 if (nrecs > 1) {
2308 c0__p_fail(p, C0_ERR_SYNTAX, at, "a pattern is one branch: two records");
2309 return;
2310 }
2311 if (nrecs == 0) {
2312 if (!inner) c0__p_nc(p); /* a group reference written as a pattern */
2313 return;
2314 }
2315 ri = c0_group_records(last);
2316 c0_next_record(&ri, &r);
2317 if (c0_record_keyed(r)) {
2319 c0_bytes k, val;
2320 c0_unit u;
2321 size_t n = 0;
2322 while (c0_next_pair_with_subs(&pi, &k, &u)) {
2323 n++;
2324 if (n > 1) {
2325 c0__p_fail(p, C0_ERR_SYNTAX, at, "a keyed record in a pattern holds one keyed unit");
2326 return;
2327 }
2328 if (u.subs_end != u.subs_start) {
2329 c0__p_fail(p, C0_ERR_SYNTAX, at, "a sub-unit is not a step of a pattern");
2330 return;
2331 }
2332 if (c0_value(u.raw, NULL, &val) != C0_OK || val.len != 0) {
2333 c0__p_fail(p, C0_ERR_SYNTAX, at, "a keyed unit in a pattern has no value");
2334 return;
2335 }
2336 if (k.len == 0 || !c0_is_name(k.ptr, k.len)) {
2337 c0__p_fail(p, C0_ERR_SYNTAX, at, "a step of a pattern is a name");
2338 return;
2339 }
2340 }
2341 if (n == 0) c0__p_fail(p, C0_ERR_SYNTAX, at, "a keyed record in a pattern holds one keyed unit");
2342 return;
2343 }
2344 {
2346 c0_unit u;
2347 c0_bytes v;
2348 for (i = 0; c0_next_unit_with_subs(&ui, &u); i++) {
2349 c0_bytes t = c0_trim(u.raw);
2350 if (i >= 3) {
2351 c0__p_fail(p, C0_ERR_SYNTAX, at, "a pattern record holds at most a record id, a field name and a level");
2352 return;
2353 }
2354 if (u.subs_end != u.subs_start) {
2355 c0__p_fail(p, C0_ERR_SYNTAX, at, "a sub-unit is not a step of a pattern");
2356 return;
2357 }
2358 if (i == 2) {
2359 c0_body lv;
2360 if (!(t.len > 0 && t.ptr[0] == C0_DLE) || c0_unit_level(t, &lv) != C0_OK) {
2361 c0__p_fail(p, C0_ERR_SYNTAX, at, "the third unit of a pattern record is a level");
2362 return;
2363 }
2364 c0__p_check_pattern(p, lv.buf, lv.start, lv.stop, 1, at);
2365 if (C0__P_ERR(p)) return;
2366 } else {
2367 if (t.len > 0 && (t.ptr[0] == C0_DLE || t.ptr[0] == C0_ENQ || t.ptr[0] == C0_STX)) {
2368 c0__p_fail(p, C0_ERR_SYNTAX, at, "a step of a pattern is a name");
2369 return;
2370 }
2371 if (c0_value(t, NULL, &v) != C0_OK || v.len == 0 || !c0_is_name(v.ptr, v.len)) {
2372 c0__p_fail(p, C0_ERR_SYNTAX, at, "a step of a pattern is a name");
2373 return;
2374 }
2375 }
2376 }
2377 }
2378}
2379
2380/* ENQ at pos: a group name, or a pattern. Returns the position after it. */
2381static size_t c0__p_reference(c0__parser *p, size_t pos, size_t stop) {
2382 const uint8_t *buf = p->buf;
2383 size_t at = pos;
2384 uint8_t b;
2385 pos = c0__p_layout(p, pos + 1, stop);
2386 if (pos >= stop) {
2387 c0__p_fail(p, C0_ERR_SYNTAX, at, "reference without a name");
2388 return stop;
2389 }
2390 b = buf[pos];
2391 if (b == C0_DLE) {
2392 size_t dead0 = p->dead_elements, after;
2393 after = c0__p_level(p, pos, stop);
2394 if (C0__P_ERR(p)) return stop;
2395 if (p->dead_elements != dead0) {
2396 c0__p_fail(p, C0_ERR_SYNTAX, pos, "a dead element is not a step of a pattern");
2397 return stop;
2398 }
2399 c0__p_check_pattern(p, buf, pos + 1, after - 1, 0, pos);
2400 return C0__P_ERR(p) ? stop : after;
2401 }
2402 if (b == C0_STX) {
2403 c0__p_fail(p, C0_ERR_SYNTAX, pos, "a reference is a name or a pattern, not text");
2404 return stop;
2405 }
2406 if (b >= 0x20) {
2407 size_t ns, ne;
2408 pos = c0__p_name(p, pos, stop, &ns, &ne);
2409 if (ne == ns) {
2410 c0__p_fail(p, C0_ERR_SYNTAX, at, "reference without a name");
2411 return stop;
2412 }
2413 return pos;
2414 }
2415 c0__p_fail(p, C0_ERR_SYNTAX, at, "reference without a name");
2416 return stop;
2417}
2418
2419/* The body from pos to stop. At depth zero commits are legal and the body
2420 * ends at EOT, SYN, EM or stop; in a level it ends at CAN. Returns the
2421 * position of the code that ended it (or stop). */
2422static size_t c0__p_body(c0__parser *p, c0_parse_state *s, size_t pos, size_t stop) {
2423 const uint8_t *buf = p->buf;
2424 int dead = 0; /* BEL seen: the next element is dead */
2425 size_t prefix = 0; /* SUB run read before a GS: the subsection's depth less one */
2426 size_t mark_at = pos;
2427 for (;;) {
2428 uint8_t b;
2429 pos = c0__p_layout(p, pos, stop);
2430 if (pos >= stop) break;
2431 b = buf[pos];
2432 switch (b) {
2433 case C0_RS:
2434 pos = c0__p_record(p, pos + 1, stop);
2435 if (C0__P_ERR(p)) return stop;
2436 if (dead) {
2437 p->dead_elements++;
2438 } else {
2439 if (!s->dead_file && !s->dead_depth) s->file_has_groups = 1;
2440 s->header_ok = 0;
2441 }
2442 dead = 0;
2443 break;
2444 case C0_SOH: {
2445 size_t p2 = c0__layout(buf, pos + 1, stop);
2446 if (!(p2 < stop && buf[p2] == C0_RS)) {
2447 c0__p_fail(p, C0_ERR_SYNTAX, pos, "keyed unit outside a record");
2448 return stop;
2449 }
2450 if (!s->header_ok) {
2451 c0__p_fail(p, C0_ERR_SYNTAX, pos, "header row not at the start of its group");
2452 return stop;
2453 }
2454 pos = c0__p_header_row(p, p2 + 1, stop);
2455 if (C0__P_ERR(p)) return stop;
2456 if (dead) {
2457 p->dead_elements++;
2458 } else {
2459 if (!s->dead_file && !s->dead_depth) s->file_has_groups = 1;
2460 s->header_ok = 0;
2461 }
2462 dead = 0;
2463 break;
2464 }
2465 case C0_GS: {
2466 size_t depth = 1 + prefix, ns, ne;
2467 prefix = 0;
2468 if (depth >= C0__GS_DEPTH_MAX) {
2469 c0__p_fail(p, C0_ERR_TOO_DEEP, pos, "group depth too deep");
2470 return stop;
2471 }
2472 if (depth > (size_t)s->prev_depth + 1) {
2473 c0__p_fail(p, C0_ERR_SYNTAX, pos, "depth skipped: a group is at most one deeper than the group line before it");
2474 return stop;
2475 }
2476 s->prev_depth = (int)depth;
2477 pos = c0__p_name(p, pos + 1, stop, &ns, &ne);
2478 if (C0__P_ERR(p)) return stop;
2479 if (s->dead_depth && depth <= (size_t)s->dead_depth) s->dead_depth = 0; /* the dead group's span ends here */
2480 if (dead) {
2481 p->dead_elements++;
2482 if (!s->dead_file && !s->dead_depth) s->dead_depth = (int)depth;
2483 } else if (!s->dead_file && !s->dead_depth) {
2484 s->file_has_groups = 1;
2485 }
2486 s->header_ok = 1;
2487 dead = 0;
2488 break;
2489 }
2490 case C0_FS: {
2491 size_t ns, ne;
2492 pos = c0__p_name(p, pos + 1, stop, &ns, &ne);
2493 if (C0__P_ERR(p)) return stop;
2494 /* finish the file before: an empty leading file is dropped */
2495 if (!s->dead_file && (!s->leading || s->file_has_groups)) s->nfiles++;
2496 if (dead) {
2497 p->dead_elements++;
2498 s->dead_file = 1;
2499 } else {
2500 s->dead_file = 0;
2501 }
2502 s->leading = 0;
2503 s->file_has_groups = 0;
2504 s->dead_depth = 0;
2505 s->prev_depth = 0;
2506 s->header_ok = 1;
2507 dead = 0;
2508 break;
2509 }
2510 case C0_BEL: {
2511 size_t p2;
2512 uint8_t c;
2513 if (dead) {
2514 c0__p_fail(p, C0_ERR_SYNTAX, pos, "BEL before a code that is not an element");
2515 return stop;
2516 }
2517 p2 = c0__layout(buf, pos + 1, stop);
2518 if (p2 >= stop) {
2519 c0__p_fail(p, C0_ERR_UNEXPECTED_END, p2, "BEL at end of input");
2520 return stop;
2521 }
2522 c = buf[p2];
2523 if (c >= 0x20 || c == C0_STX) {
2524 c0__p_nc(p);
2525 pos = c0__p_note_content(p, p2, stop);
2526 if (C0__P_ERR(p)) return stop;
2527 } else if (c == C0_RS || c == C0_SOH || c == C0_GS || c == C0_FS) {
2528 c0__p_nc(p);
2529 dead = 1;
2530 mark_at = pos;
2531 pos = p2;
2532 } else if (c == C0_SUB) {
2533 /* BEL kills a group line whole, its SUB prefix included */
2534 size_t run, p3;
2535 c0__sub_run(buf, p2, stop, &run, &p3);
2536 if (p3 < stop && buf[p3] == C0_GS) {
2537 c0__p_nc(p);
2538 dead = 1;
2539 mark_at = pos;
2540 pos = p2;
2541 } else if (p3 < stop && buf[p3] == C0_US) {
2542 c0__p_fail(p, C0_ERR_SYNTAX, pos, "BEL before a sub-unit: a unit cannot be dead");
2543 return stop;
2544 } else {
2545 c0__p_fail(p, C0_ERR_SYNTAX, p2, "BEL before a code that is not an element");
2546 return stop;
2547 }
2548 } else if (c == C0_DLE) {
2549 c0__p_fail(p, C0_ERR_SYNTAX, p2, "a nested level is not an item");
2550 return stop;
2551 } else {
2552 c0__p_fail(p, C0_ERR_SYNTAX, p2, "BEL before a code that is not an element");
2553 return stop;
2554 }
2555 break;
2556 }
2557 case C0_SUB: {
2558 /* A run of SUB before GS is the subsection's depth prefix;
2559 * before RS, FS or SOH it is reserved; a sub-unit (SUB US)
2560 * lives inside a record and never reaches here. */
2561 size_t start = pos, run = 0;
2562 uint8_t c;
2563 while (pos < stop && buf[pos] == C0_SUB) {
2564 run++;
2565 pos = c0__p_layout(p, pos + 1, stop);
2566 }
2567 if (pos >= stop) {
2568 c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB at the end of input");
2569 return stop;
2570 }
2571 c = buf[pos];
2572 if (c == C0_GS) {
2573 prefix = run;
2574 } else if (c == C0_RS) {
2575 c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB before RS is reserved (a sub-record)");
2576 return stop;
2577 } else if (c == C0_FS) {
2578 c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB before FS is reserved (a sub-file)");
2579 return stop;
2580 } else if (c == C0_SOH) {
2581 c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB before SOH is reserved (a sub-key); a header row admits none");
2582 return stop;
2583 } else if (c == C0_US) {
2584 c0__p_fail(p, C0_ERR_SYNTAX, pos, "US outside a record");
2585 return stop;
2586 } else if (c == C0_BEL) {
2587 c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB before BEL");
2588 return stop;
2589 } else {
2590 c0__p_fail(p, C0_ERR_SYNTAX, start, "SUB before a byte that is not a separator");
2591 return stop;
2592 }
2593 break;
2594 }
2595 case C0_ETB:
2596 if (s->in_level) {
2597 c0__p_fail(p, C0_ERR_SYNTAX, pos, "commit inside a nested level");
2598 return stop;
2599 }
2600 if (dead) {
2601 c0__p_fail(p, C0_ERR_SYNTAX, mark_at, "BEL before ETB: framing cannot be commented out");
2602 return stop;
2603 }
2604 c0__p_nc(p);
2605 pos = c0__plain(buf, c0__p_layout(p, pos + 1, stop), stop);
2606 break;
2607 case C0_EOT:
2608 case C0_SYN:
2609 case C0_EM:
2610 case C0_CAN:
2611 if (b == C0_CAN ? !s->in_level : s->in_level) {
2612 c0__p_fail(p, C0_ERR_SYNTAX, pos, b == C0_CAN ? "CAN with no open level" : "framing inside open level");
2613 return stop;
2614 }
2615 if (dead) {
2616 c0__p_fail(p, C0_ERR_SYNTAX, mark_at, "BEL before framing");
2617 return stop;
2618 }
2619 return pos;
2620 case C0_US:
2621 c0__p_fail(p, C0_ERR_SYNTAX, pos, "US outside a record");
2622 return stop;
2623 case C0_STX:
2624 c0__p_fail(p, C0_ERR_SYNTAX, pos, "text outside a record");
2625 return stop;
2626 case C0_DLE:
2627 c0__p_fail(p, C0_ERR_SYNTAX, pos, "a nested level is not an item");
2628 return stop;
2629 case C0_ENQ:
2630 c0__p_fail(p, C0_ERR_SYNTAX, pos, "a reference outside a record");
2631 return stop;
2632 default:
2633 if (b >= 0x20) c0__p_fail(p, C0_ERR_SYNTAX, pos, "plain text outside a record");
2634 else c0__p_fail(p, C0_ERR_UNASSIGNED, pos, "unassigned control code");
2635 return stop;
2636 }
2637 }
2638 if (dead) {
2639 c0__p_fail(p, C0_ERR_UNEXPECTED_END, mark_at, "BEL at end of input");
2640 return stop;
2641 }
2642 return pos;
2643}
2644
2645/* The `schema` heading key: a plain name, or a level holding one keyed
2646 * record whose keys are drawn from name, url and hash (DESIGN.md, Start). */
2647static void c0__p_check_schema(c0__parser *p, c0_bytes rawv, size_t at) {
2648 c0_bytes t = c0_trim(rawv), v;
2649 if (t.len == 0) {
2650 c0__p_fail(p, C0_ERR_SYNTAX, at, "schema needs a value");
2651 return;
2652 }
2653 if (t.ptr[0] == C0_DLE) {
2654 c0_body body;
2655 c0_record_iter ri;
2656 c0_record r;
2657 c0_pair_iter pi;
2658 c0_bytes k;
2659 size_t n = 0;
2660 if (c0_unit_level(t, &body) != C0_OK || !c0_body_bare(body)) {
2661 c0__p_fail(p, C0_ERR_SYNTAX, at, "a schema level holds one keyed record");
2662 return;
2663 }
2664 ri = c0_body_records(body);
2665 if (!c0_next_record(&ri, &r)) {
2666 c0__p_fail(p, C0_ERR_SYNTAX, at, "a schema level holds one keyed record");
2667 return;
2668 }
2669 {
2670 c0_record r2;
2671 if (c0_next_record(&ri, &r2)) {
2672 c0__p_fail(p, C0_ERR_SYNTAX, at, "a schema level holds one keyed record");
2673 return;
2674 }
2675 }
2676 if (!c0_record_keyed(r)) {
2677 c0__p_fail(p, C0_ERR_SYNTAX, at, "a schema level holds a keyed record, not a positional one");
2678 return;
2679 }
2680 pi = c0_record_pairs(r);
2681 while (c0_next_pair(&pi, &k, &v)) {
2682 n++;
2683 if (!(c0__eq_str(k, "name") || c0__eq_str(k, "url") || c0__eq_str(k, "hash"))) {
2684 c0__p_fail(p, C0_ERR_SYNTAX, at, "unknown schema key");
2685 return;
2686 }
2687 if (c0_value(v, NULL, &v) != C0_OK || v.len == 0 || !c0_is_name(v.ptr, v.len)) {
2688 c0__p_fail(p, C0_ERR_SYNTAX, at, "a schema name, url or hash is a name");
2689 return;
2690 }
2691 }
2692 if (n == 0) c0__p_fail(p, C0_ERR_SYNTAX, at, "a schema record needs name, url or hash");
2693 return;
2694 }
2695 if (t.ptr[0] == C0_STX) {
2696 c0__p_fail(p, C0_ERR_SYNTAX, at, "a schema name cannot be text");
2697 return;
2698 }
2699 if (c0_value(t, NULL, &v) != C0_OK || v.len == 0 || !c0_is_name(v.ptr, v.len)) {
2700 c0__p_fail(p, C0_ERR_SYNTAX, at, "a schema name is a name");
2701 }
2702}
2703
2704/* After SYN: the heading. Returns the position of the first body code. */
2705static size_t c0__p_heading(c0__parser *p, size_t pos, size_t stop) {
2706 const uint8_t *buf = p->buf;
2707 size_t ks, ke, vs;
2708 for (;;) {
2709 uint8_t b;
2710 pos = c0__p_layout(p, pos, stop);
2711 if (pos >= stop) return pos;
2712 b = buf[pos];
2713 if (b == C0_SOH) {
2714 if (c0__soh_is_header(buf, pos, stop)) return pos; /* a header row begins the body */
2715 pos = c0__p_keyed_unit(p, pos + 1, stop, 1, &ks, &ke, &vs);
2716 if (C0__P_ERR(p)) return stop;
2717 if (c0__eq_str(c0__slice(buf, ks, ke), "schema")) c0__p_check_schema(p, c0__slice(buf, vs, pos), vs);
2718 if (C0__P_ERR(p)) return stop;
2719 } else if (b == C0_BEL) {
2720 size_t p2 = c0__layout(buf, pos + 1, stop);
2721 uint8_t c;
2722 if (p2 >= stop) {
2723 c0__p_fail(p, C0_ERR_UNEXPECTED_END, p2, "BEL at end of input");
2724 return stop;
2725 }
2726 c = buf[p2];
2727 if (c == C0_SOH) {
2728 if (c0__soh_is_header(buf, p2, stop)) return pos; /* a dead header row begins the body */
2729 c0__p_nc(p);
2730 pos = c0__p_keyed_unit(p, p2 + 1, stop, 1, &ks, &ke, &vs);
2731 if (C0__P_ERR(p)) return stop;
2732 } else if (c >= 0x20 || c == C0_STX) {
2733 c0__p_nc(p);
2734 pos = c0__p_note_content(p, p2, stop);
2735 if (C0__P_ERR(p)) return stop;
2736 } else if (c == C0_RS || c == C0_GS || c == C0_FS || c == C0_DLE) {
2737 return pos; /* a dead body element */
2738 } else {
2739 c0__p_fail(p, C0_ERR_SYNTAX, p2, "BEL before a code that is not an element");
2740 return stop;
2741 }
2742 } else if (b == C0_SUB) {
2743 size_t p2 = c0__layout(buf, pos + 1, stop);
2744 if (p2 >= stop) {
2745 c0__p_fail(p, C0_ERR_SYNTAX, pos, "SUB at the end of input");
2746 return stop;
2747 }
2748 if (buf[p2] == C0_US) {
2749 c0__p_fail(p, C0_ERR_SYNTAX, pos, "the heading's values take no sub-units");
2750 return stop;
2751 }
2752 return pos; /* a prefix before a body code: the body's business */
2753 } else if (b >= 0x20) {
2754 c0__p_fail(p, C0_ERR_SYNTAX, pos, "plain text directly after SYN");
2755 return stop;
2756 } else {
2757 return pos;
2758 }
2759 }
2760}
2761
2762/* Drive the container automaton over [pos, stop) from the state in st,
2763 * resumably: a stream reader calls it once per block. Returns the position
2764 * reached (stop, or where EM began the raw region). */
2765static size_t c0__p_run(c0__parser *p, c0_parse_state *st, size_t pos, size_t stop) {
2766 const uint8_t *buf = p->buf;
2767 for (;;) {
2768 uint8_t b;
2769 if (st->phase == C0__PH_EM) return stop;
2770 pos = c0__p_layout(p, pos, stop);
2771 if (pos >= stop || C0__P_ERR(p)) return pos;
2772 b = buf[pos];
2773 switch (st->phase) {
2774 case C0__PH_START:
2775 if (b == C0_EM) {
2776 c0__p_nc(p);
2777 st->phase = C0__PH_EM;
2778 return stop;
2779 }
2780 if (b == C0_SYN) {
2781 c0__p_nc(p);
2782 pos = c0__p_heading(p, pos + 1, stop);
2783 if (C0__P_ERR(p)) return stop;
2784 } else if (!st->first) {
2785 c0__p_fail(p, C0_ERR_SYNTAX, pos, "a document after the first must begin with SYN");
2786 return stop;
2787 }
2788 st->first = 0;
2789 st->phase = C0__PH_BODY;
2790 c0__st_body_reset(st, 0);
2791 break;
2792 case C0__PH_BODY:
2793 pos = c0__p_body(p, st, pos, stop);
2794 if (C0__P_ERR(p)) return stop;
2795 if (pos >= stop) return pos;
2796 b = buf[pos];
2797 if (b == C0_EOT) {
2798 c0__p_nc(p);
2799 pos++;
2800 st->phase = C0__PH_AFTER_EOT;
2801 } else if (b == C0_SYN) {
2802 st->phase = C0__PH_START;
2803 } else { /* EM */
2804 c0__p_nc(p);
2805 st->phase = C0__PH_EM;
2806 return stop;
2807 }
2808 break;
2809 case C0__PH_AFTER_EOT:
2810 if (b == C0_SYN) {
2811 st->phase = C0__PH_START;
2812 } else if (b == C0_EM) {
2813 c0__p_nc(p);
2814 st->phase = C0__PH_EM;
2815 return stop;
2816 } else {
2817 c0__p_fail(p, C0_ERR_SYNTAX, pos, "unexpected byte after EOT");
2818 return stop;
2819 }
2820 break;
2821 default:
2822 return stop;
2823 }
2824 }
2825}
2826
2827/* ---- references -------------------------------------------------------- */
2828
2830 c0_bytes t = c0_trim(raw);
2831 c0__parser p;
2832 size_t pos, after;
2833 memset(out, 0, sizeof(*out));
2834 if (!(t.len > 0 && t.ptr[0] == C0_ENQ)) return C0_ERR_NOT_REFERENCE;
2835 c0__p_init(&p, t.ptr, 0);
2836 after = c0__p_reference(&p, 0, t.len);
2837 if (C0__P_ERR(&p)) return p.err.code;
2838 if (c0__only_notes_after(t, after) != C0_OK) return C0_ERR_SYNTAX;
2839 pos = c0__layout(t.ptr, 1, t.len);
2840 if (t.ptr[pos] == C0_DLE) {
2841 c0_error err = {C0_OK, 0, ""};
2842 size_t end = c0__level(t.ptr, pos, t.len, &err);
2843 out->is_pattern = 1;
2844 out->pattern.buf = t.ptr;
2845 out->pattern.start = pos + 1;
2846 out->pattern.stop = end - 1;
2847 out->name = c0__slice(t.ptr, pos, pos);
2848 } else {
2849 out->name = c0_trim(c0__slice(t.ptr, pos, c0__plain(t.ptr, pos, t.len)));
2850 }
2851 return C0_OK;
2852}
2853
2854static size_t c0__ref_body_path(c0_body body, c0_bytes *steps, size_t max, size_t n) {
2855 c0_file_iter fi = c0_body_files(body);
2856 c0_file f;
2857 c0_group_iter gi;
2858 c0_group g, last;
2859 c0_record_iter ri;
2860 c0_record r;
2861 int have = 0;
2862 if (!c0_next_file(&fi, &f)) return n;
2863 if (!f.leading) {
2864 if (n < max) steps[n] = c0_file_name(f);
2865 n++;
2866 }
2867 gi = c0_file_groups(f);
2868 memset(&last, 0, sizeof(last));
2869 while (c0_next_group(&gi, &g)) {
2870 if (g.depth > 0) {
2871 if (n < max) steps[n] = c0_group_name(g);
2872 n++;
2873 }
2874 last = g;
2875 have = 1;
2876 }
2877 if (!have) return n;
2878 ri = c0_group_records(last);
2879 if (!c0_next_record(&ri, &r)) return n;
2880 if (c0_record_keyed(r)) {
2882 c0_bytes k, v;
2883 if (c0_next_pair(&pi, &k, &v)) {
2884 if (n < max) steps[n] = k;
2885 n++;
2886 }
2887 return n;
2888 }
2889 {
2891 c0_bytes raw, v;
2892 size_t i;
2893 for (i = 0; c0_next_unit(&ui, &raw); i++) {
2894 if (i < 2) {
2895 if (c0_value(raw, NULL, &v) != C0_OK) v = c0_trim(raw);
2896 if (n < max) steps[n] = v;
2897 n++;
2898 } else {
2899 c0_body lv;
2900 if (c0_unit_level(raw, &lv) == C0_OK) n = c0__ref_body_path(lv, steps, max, n);
2901 }
2902 }
2903 }
2904 return n;
2905}
2906
2907size_t c0_ref_path(const c0_ref *r, c0_bytes *steps, size_t max) {
2908 if (!r->is_pattern) {
2909 if (max > 0) steps[0] = r->name;
2910 return 1;
2911 }
2912 return c0__ref_body_path(r->pattern, steps, max, 0);
2913}
2914
2915int c0_ref_group(const c0_ref *r, c0_bytes *name) {
2916 c0_file_iter fi;
2917 c0_file f;
2918 c0_group_iter gi;
2919 c0_group g;
2920 c0_record_iter ri;
2921 c0_record rec;
2922 if (!r->is_pattern) {
2923 if (name) *name = r->name;
2924 return 1;
2925 }
2926 fi = c0_body_files(r->pattern);
2927 if (!c0_next_file(&fi, &f) || !f.leading) return 0;
2928 gi = c0_file_groups(f);
2929 if (!c0_next_group(&gi, &g) || g.depth == 0) return 0;
2930 if (c0_next_group(&gi, &g)) return 0;
2931 ri = c0_group_records(g);
2932 if (c0_next_record(&ri, &rec)) return 0;
2933 if (name) *name = c0_group_name(g);
2934 return 1;
2935}
2936
2937/* ---- documents --------------------------------------------------------- */
2938
2939/* Read one document with the parser p from start; the parser's counters
2940 * are reported as the document's. */
2941static c0_status c0__read_document(c0__parser *p, size_t len, size_t start, c0_document *out) {
2942 const uint8_t *buf = p->buf;
2943 size_t pos, dead0 = p->dead_elements;
2944 c0_parse_state st;
2945 memset(out, 0, sizeof(*out));
2946 out->buf = buf;
2947 out->start = start;
2948 pos = c0__p_layout(p, start, len);
2949 out->has_syn = pos < len && buf[pos] == C0_SYN;
2950 if (out->has_syn) {
2951 c0__p_nc(p);
2952 pos++;
2953 out->heading_start = pos;
2954 pos = c0__p_heading(p, pos, len);
2955 if (C0__P_ERR(p)) return p->err.code;
2956 out->heading_end = pos;
2957 } else {
2958 out->warnings |= C0_WARN_NO_SYN;
2959 out->heading_start = out->heading_end = pos;
2960 }
2961 out->body.buf = buf;
2962 out->body.start = pos;
2963 c0__st_body_reset(&st, 0);
2964 pos = c0__p_body(p, &st, pos, len);
2965 if (C0__P_ERR(p)) return p->err.code;
2966 out->body.stop = pos;
2967 pos = c0__p_layout(p, pos, len);
2968 out->has_eot = pos < len && buf[pos] == C0_EOT;
2969 if (out->has_eot) {
2970 c0__p_nc(p);
2971 pos++;
2972 } else if (!c0__eq_str(c0_heading_shape(out), "stream")) {
2973 out->warnings |= C0_WARN_NO_EOT;
2974 }
2975 out->stop = pos;
2976 out->dead_elements = p->dead_elements - dead0;
2977 {
2979 c0_bytes k, v, other;
2980 while (c0_next_pair(&it, &k, &v)) {
2981 c0_pair_iter rest = it;
2982 c0_bytes k2;
2983 if (!c0__eq_str(k, "shape") && !c0__eq_str(k, "schema") && !c0__eq_str(k, "version") && !c0__eq_str(k, "blob")) {
2985 }
2986 while (c0_next_pair(&rest, &k2, &other)) {
2987 if (k2.len == k.len && memcmp(k2.ptr, k.ptr, k.len) == 0) out->warnings |= C0_WARN_DUPLICATE_KEY;
2988 }
2989 }
2990 if (it.err.code) {
2991 p->err = it.err;
2992 return p->err.code;
2993 }
2994 {
2995 c0_bytes shape = c0_heading_shape(out);
2996 if (shape.len && !c0__eq_str(shape, "diff") && !c0__eq_str(shape, "stream")) out->warnings |= C0_WARN_UNKNOWN_SHAPE;
2997 }
2998 if (c0_heading_get_str(out, "version", &v) == C0_OK) {
2999 if (c0_value(v, NULL, &v) != C0_OK || !c0__eq_str(v, "1")) out->warnings |= C0_WARN_UNKNOWN_VERSION;
3000 }
3001 }
3002 return C0_OK;
3003}
3004
3005c0_status c0_document_read(const uint8_t *buf, size_t len, size_t start, c0_document *out, c0_error *err) {
3006 c0__parser p;
3007 c0_status st;
3008 c0__p_init(&p, buf, 0);
3009 st = c0__read_document(&p, len, start, out);
3010 if (err) *err = p.err;
3011 return st;
3012}
3013
3014c0_status c0_body_read(const uint8_t *buf, size_t len, c0_body *out, c0_error *err) {
3015 c0__parser p;
3016 c0_parse_state st;
3017 size_t pos;
3018 c0__p_init(&p, buf, 0);
3019 c0__st_body_reset(&st, 0);
3020 pos = c0__p_body(&p, &st, 0, len);
3021 if (!C0__P_ERR(&p)) {
3022 pos = c0__layout(buf, pos, len);
3023 if (pos < len) c0__p_fail(&p, C0_ERR_SYNTAX, pos, "unexpected byte in body");
3024 }
3025 if (err) *err = p.err;
3026 if (p.err.code) return p.err.code;
3027 *out = c0_body_view(buf, len);
3028 return C0_OK;
3029}
3030
3032 return c0__pairs(d->buf, d->heading_start, d->heading_end);
3033}
3034
3035c0_status c0_heading_get(const c0_document *d, const uint8_t *key, size_t klen, c0_bytes *raw) {
3036 return c0__pairs_get(c0_document_heading(d), key, klen, raw);
3037}
3038
3039c0_status c0_heading_get_str(const c0_document *d, const char *key, c0_bytes *raw) {
3040 return c0_heading_get(d, (const uint8_t *)key, strlen(key), raw);
3041}
3042
3044 c0_bytes raw, v;
3045 v.ptr = d->buf;
3046 v.len = 0;
3047 if (c0_heading_get_str(d, "shape", &raw) == C0_OK && c0_value(raw, NULL, &v) != C0_OK) v.len = 0;
3048 return v;
3049}
3050
3051int c0_heading_version(const c0_document *d) {
3052 c0_bytes raw, v;
3053 int n = 0;
3054 size_t i;
3055 if (c0_heading_get_str(d, "version", &raw) != C0_OK) return 1;
3056 if (c0_value(raw, NULL, &v) != C0_OK || v.len == 0) return 1;
3057 for (i = 0; i < v.len; i++) {
3058 if (v.ptr[i] < '0' || v.ptr[i] > '9') return 1;
3059 n = n * 10 + (v.ptr[i] - '0');
3060 }
3061 return n;
3062}
3063
3065 c0_bytes raw;
3066 c0_status st = c0_heading_get_str(d, "blob", &raw);
3067 if (st) return st;
3068 return c0_unit_level(raw, out);
3069}
3070
3071/* ---- containers -------------------------------------------------------- */
3072
3073c0_doc_iter c0_documents(const uint8_t *buf, size_t len) {
3074 c0_doc_iter it;
3075 it.buf = buf;
3076 it.len = len;
3077 it.pos = 0;
3078 it.has_em = 0;
3079 it.em_pos = len;
3080 it.done = 0;
3081 c0__err_clear(&it.err);
3082 return it;
3083}
3084
3085static int c0__next_document(c0_doc_iter *it, c0_document *out, c0__parser *p) {
3086 size_t pos;
3087 if (it->done) return 0;
3088 pos = c0__p_layout(p, it->pos, it->len);
3089 if (pos >= it->len) {
3090 it->done = 1;
3091 return 0;
3092 }
3093 if (it->buf[pos] == C0_EM) {
3094 c0__p_nc(p);
3095 it->has_em = 1;
3096 it->em_pos = pos;
3097 it->done = 1;
3098 return 0;
3099 }
3100 if (it->pos > 0 && it->buf[pos] != C0_SYN) {
3101 c0__fail(&it->err, C0_ERR_SYNTAX, pos, "a document after the first must begin with SYN");
3102 it->done = 1;
3103 return 0;
3104 }
3105 if (c0__read_document(p, it->len, pos, out) != C0_OK) {
3106 it->err = p->err;
3107 it->done = 1;
3108 return 0;
3109 }
3110 it->pos = c0__layout(it->buf, out->stop, it->len);
3111 if (it->pos < it->len && it->buf[it->pos] != C0_SYN && it->buf[it->pos] != C0_EM) {
3112 c0__fail(&it->err, C0_ERR_SYNTAX, it->pos, out->has_eot ? "unexpected byte after EOT" : "unexpected byte after document");
3113 it->done = 1;
3114 return 0;
3115 }
3116 return 1;
3117}
3118
3120 c0__parser p;
3121 c0__p_init(&p, it->buf, 0);
3122 return c0__next_document(it, out, &p);
3123}
3124
3126 c0_bytes t;
3127 t.ptr = it->buf + it->len;
3128 t.len = 0;
3129 if (it->has_em) {
3130 t.ptr = it->buf + it->em_pos + 1;
3131 t.len = it->len - it->em_pos - 1;
3132 }
3133 return t;
3134}
3135
3136c0_status c0_container_tail(const uint8_t *buf, size_t len, c0_bytes *tail, int *has_em, c0_error *err) {
3137 c0_doc_iter it = c0_documents(buf, len);
3138 c0_document d;
3139 while (c0_next_document(&it, &d)) {
3140 }
3141 if (err) *err = it.err;
3142 *tail = c0_doc_iter_tail(&it);
3143 if (has_em) *has_em = it.has_em;
3144 return it.err.code;
3145}
3146
3147/* ---- validation -------------------------------------------------------- */
3148
3149static c0_status c0__run_container(c0__parser *p, size_t len) {
3150 c0_doc_iter it = c0_documents(p->buf, len);
3151 c0_document d;
3152 while (c0__next_document(&it, &d, p)) {
3153 }
3154 if (it.err.code && !p->err.code) p->err = it.err;
3155 return p->err.code;
3156}
3157
3158c0_status c0_validate(const uint8_t *buf, size_t len, c0_error *err) {
3159 c0__parser p;
3160 c0__p_init(&p, buf, 0);
3161 c0__run_container(&p, len);
3162 if (err) *err = p.err;
3163 return p.err.code;
3164}
3165
3166int c0_canonical(const uint8_t *buf, size_t len) {
3167 c0__parser p;
3168 c0__p_init(&p, buf, 1);
3169 c0__run_container(&p, len);
3170 return p.err.code == C0_OK && p.ok;
3171}
3172
3173/* ---- blobs ------------------------------------------------------------- */
3174
3175static int c0__to_size(c0_bytes v, size_t *out) {
3176 size_t i, n = 0;
3177 if (v.len == 0) return 0;
3178 for (i = 0; i < v.len; i++) {
3179 if (v.ptr[i] < '0' || v.ptr[i] > '9') return 0;
3180 n = n * 10 + (size_t)(v.ptr[i] - '0');
3181 }
3182 *out = n;
3183 return 1;
3184}
3185
3186c0_status c0_blob(const uint8_t *buf, size_t len, const uint8_t *name, size_t nlen, c0_bytes *out, c0_error *err) {
3187 c0_doc_iter it = c0_documents(buf, len);
3188 c0_document first;
3189 c0_body table;
3190 c0_group_iter gi;
3191 c0_group g;
3192 c0_record_iter ri;
3193 c0_record r;
3194 c0_bytes tail;
3195 size_t ni = 0, oi = 1, li = 2;
3196 int found = 0;
3197 c0_status st;
3198 if (!c0_next_document(&it, &first)) {
3199 if (err) *err = it.err;
3200 return it.err.code ? it.err.code : C0_ERR_NOT_FOUND;
3201 }
3202 {
3203 c0_document d;
3204 while (c0_next_document(&it, &d)) {
3205 }
3206 }
3207 if (err) *err = it.err;
3208 if (it.err.code) return it.err.code;
3209 if (!it.has_em) return C0_ERR_NOT_FOUND;
3210 tail = c0_doc_iter_tail(&it);
3211 st = c0_heading_blob(&first, &table);
3212 if (st) return st;
3213 gi = c0_body_groups(table);
3214 if (!c0_next_group(&gi, &g)) return C0_ERR_NOT_FOUND;
3215 c0_group_column(g, (const uint8_t *)"name", 4, &ni);
3216 c0_group_column(g, (const uint8_t *)"offset", 6, &oi);
3217 c0_group_column(g, (const uint8_t *)"length", 6, &li);
3218 ri = c0_group_records(g);
3219 while (c0_next_record(&ri, &r)) {
3220 c0_bytes raw, v;
3221 size_t off, length;
3222 if (c0_record_field(r, ni, &raw) || c0_value(raw, NULL, &v)) continue;
3223 if (!(v.len == nlen && (nlen == 0 || memcmp(v.ptr, name, nlen) == 0))) continue;
3224 if (c0_record_field(r, oi, &raw) || c0_value(raw, NULL, &v) || !c0__to_size(v, &off)) continue;
3225 if (c0_record_field(r, li, &raw) || c0_value(raw, NULL, &v) || !c0__to_size(v, &length)) continue;
3226 if (off > tail.len || length > tail.len - off) continue;
3227 out->ptr = tail.ptr + off;
3228 out->len = length;
3229 found = 1; /* last wins */
3230 }
3231 return found ? C0_OK : C0_ERR_NOT_FOUND;
3232}
3233
3234c0_status c0_blob_str(const uint8_t *buf, size_t len, const char *name, c0_bytes *out, c0_error *err) {
3235 return c0_blob(buf, len, (const uint8_t *)name, strlen(name), out, err);
3236}
3237
3238/* ---- builder ----------------------------------------------------------- */
3239
3240enum { C0__B_TOP = 0, C0__B_HEADING = 1, C0__B_RECORD = 2 };
3241
3242static int c0__b_reserve(c0_builder *b, size_t extra) {
3243 if (b->status != C0_OK) return 0;
3244 if (b->len + extra > b->cap) {
3245 size_t ncap = b->cap ? b->cap : 64;
3246 uint8_t *nd;
3247 while (ncap < b->len + extra) ncap *= 2;
3248 nd = (uint8_t *)realloc(b->data, ncap);
3249 if (!nd) {
3250 b->status = C0_ERR_OOM;
3251 return 0;
3252 }
3253 b->data = nd;
3254 b->cap = ncap;
3255 }
3256 return 1;
3257}
3258
3259static void c0__b_byte(c0_builder *b, uint8_t x) {
3260 if (c0__b_reserve(b, 1)) b->data[b->len++] = x;
3261}
3262
3263static void c0__b_raw(c0_builder *b, const uint8_t *p, size_t n) {
3264 if (n && c0__b_reserve(b, n)) {
3265 memcpy(b->data + b->len, p, n);
3266 b->len += n;
3267 }
3268}
3269
3270static void c0__b_name(c0_builder *b, const uint8_t *p, size_t n) {
3271 if (!c0_is_name(p, n)) {
3272 if (b->status == C0_OK) b->status = C0_ERR_BAD_NAME;
3273 return;
3274 }
3275 c0__b_raw(b, p, n);
3276}
3277
3278/* A value in its one spelling. */
3279static void c0__b_value(c0_builder *b, const uint8_t *p, size_t n) {
3280 size_t i;
3281 if (c0_is_plain(p, n)) {
3282 c0__b_raw(b, p, n);
3283 return;
3284 }
3285 c0__b_byte(b, C0_STX);
3286 for (i = 0; i < n; i++) {
3287 if (c0_is_text_escaped(p[i])) c0__b_byte(b, C0_DLE);
3288 c0__b_byte(b, p[i]);
3289 }
3290 c0__b_byte(b, C0_ETX);
3291}
3292
3293static void c0__b_end_record(c0_builder *b) {
3294 b->state = C0__B_TOP;
3295 b->units = 0;
3296}
3297
3298/* The first value of a record, straight after RS. */
3299static void c0__b_first_value(c0_builder *b, const uint8_t *p, size_t n) {
3300 c0__b_value(b, p, n);
3301 b->units = 1;
3302}
3303
3304/* Position for the next unit of the open record (opening one if needed):
3305 * US between units, nothing before the first. */
3306static void c0__b_next_unit(c0_builder *b) {
3307 if (b->state != C0__B_RECORD) c0_builder_rs(b);
3308 else if (b->units > 0) c0__b_byte(b, C0_US);
3309 b->units++;
3310}
3311
3312/* SOH key US, opening a record first unless one (or the heading) is open. */
3313static void c0__b_key_head(c0_builder *b, const uint8_t *key, size_t klen) {
3314 if (b->state == C0__B_TOP) c0_builder_rs(b);
3315 c0_builder_soh_name(b, key, klen);
3316}
3317
3318static c0_bytes c0__cstr(const char *s) {
3319 c0_bytes b;
3320 b.ptr = (const uint8_t *)s;
3321 b.len = strlen(s);
3322 return b;
3323}
3324
3325/* Build a c0_bytes array from C strings on the heap; NULL on OOM. */
3326static c0_bytes *c0__cstrs(c0_builder *b, const char *const *strs, size_t count) {
3327 c0_bytes *out = (c0_bytes *)malloc((count ? count : 1) * sizeof(c0_bytes));
3328 size_t i;
3329 if (!out) {
3330 if (b->status == C0_OK) b->status = C0_ERR_OOM;
3331 return NULL;
3332 }
3333 for (i = 0; i < count; i++) out[i] = c0__cstr(strs[i]);
3334 return out;
3335}
3336
3337void c0_builder_init(c0_builder *b) {
3338 memset(b, 0, sizeof(*b));
3339 b->status = C0_OK;
3340}
3341
3342void c0_builder_free(c0_builder *b) {
3343 free(b->data);
3344 free(b->stack);
3345 memset(b, 0, sizeof(*b));
3346}
3347
3348c0_status c0_builder_status(const c0_builder *b) { return b->status; }
3349
3351 c0_bytes r;
3352 r.ptr = b->data;
3353 r.len = b->len;
3354 return r;
3355}
3356
3357/* ---- primitives: one function per code ---- */
3358
3359void c0_builder_fs(c0_builder *b, const uint8_t *name, size_t nlen) {
3360 c0__b_end_record(b);
3361 c0__b_byte(b, C0_FS);
3362 c0__b_name(b, name, nlen);
3363}
3364
3365void c0_builder_gs(c0_builder *b) {
3366 c0__b_end_record(b);
3367 c0__b_byte(b, C0_GS);
3368}
3369
3370void c0_builder_gs_name(c0_builder *b, const uint8_t *name, size_t nlen) {
3371 c0_builder_gs(b);
3372 c0__b_name(b, name, nlen);
3373}
3374
3375void c0_builder_rs(c0_builder *b) {
3376 c0__b_byte(b, C0_RS);
3377 b->state = C0__B_RECORD;
3378 b->units = 0;
3379}
3380
3381void c0_builder_rs_value(c0_builder *b, const uint8_t *value, size_t vlen) {
3382 c0_builder_rs(b);
3383 c0__b_first_value(b, value, vlen);
3384}
3385
3386void c0_builder_us(c0_builder *b) {
3387 c0__b_byte(b, C0_US);
3388 b->units++;
3389}
3390
3391void c0_builder_us_value(c0_builder *b, const uint8_t *value, size_t vlen) {
3392 c0__b_byte(b, C0_US);
3393 c0__b_value(b, value, vlen);
3394 b->units++;
3395}
3396
3397/* SUB prefixes the next code; it does not count as a unit. */
3398void c0_builder_sub(c0_builder *b) { c0__b_byte(b, C0_SUB); }
3399
3400void c0_builder_soh(c0_builder *b) { c0__b_byte(b, C0_SOH); }
3401
3402void c0_builder_soh_name(c0_builder *b, const uint8_t *name, size_t nlen) {
3403 c0__b_byte(b, C0_SOH);
3404 c0__b_name(b, name, nlen);
3405}
3406
3407void c0_builder_dle(c0_builder *b) {
3408 if (b->depth + 2 > b->stack_cap) {
3409 size_t ncap = b->stack_cap ? b->stack_cap * 2 : 16;
3410 int *ns = (int *)realloc(b->stack, ncap * sizeof(int) * 2);
3411 if (!ns) {
3412 if (b->status == C0_OK) b->status = C0_ERR_OOM;
3413 return;
3414 }
3415 b->stack = ns;
3416 b->stack_cap = ncap;
3417 }
3418 b->stack[2 * b->depth] = b->state;
3419 b->stack[2 * b->depth + 1] = (int)b->units;
3420 b->depth++;
3421 b->state = C0__B_TOP;
3422 b->units = 0;
3423 c0__b_byte(b, C0_DLE);
3424}
3425
3426void c0_builder_can(c0_builder *b) {
3427 if (b->depth == 0) {
3428 if (b->status == C0_OK) b->status = C0_ERR_BAD_STATE;
3429 return;
3430 }
3431 c0__b_byte(b, C0_CAN);
3432 b->depth--;
3433 b->state = b->stack[2 * b->depth];
3434 b->units = (size_t)b->stack[2 * b->depth + 1];
3435}
3436
3437void c0_builder_bel(c0_builder *b) { c0__b_byte(b, C0_BEL); }
3438
3439void c0_builder_bel_text(c0_builder *b, const uint8_t *text, size_t tlen) {
3440 if (tlen == 0) { /* a note needs content: bare BEL marks the next element dead */
3441 if (b->status == C0_OK) b->status = C0_ERR_BAD_STATE;
3442 return;
3443 }
3444 c0__b_byte(b, C0_BEL);
3445 c0__b_value(b, text, tlen);
3446}
3447
3448void c0_builder_enq(c0_builder *b, const uint8_t *name, size_t nlen) {
3449 c0__b_byte(b, C0_ENQ);
3450 if (nlen == 0 && b->status == C0_OK) b->status = C0_ERR_BAD_NAME;
3451 c0__b_name(b, name, nlen);
3452}
3453
3455 c0__b_byte(b, C0_ENQ);
3456 c0_builder_dle(b);
3457}
3458
3459void c0_builder_syn(c0_builder *b) {
3460 c0__b_end_record(b);
3461 c0__b_byte(b, C0_SYN);
3462 b->state = C0__B_HEADING;
3463}
3464
3465void c0_builder_eot(c0_builder *b) {
3466 c0__b_end_record(b);
3467 c0__b_byte(b, C0_EOT);
3468}
3469
3470void c0_builder_etb(c0_builder *b) {
3471 c0__b_end_record(b);
3472 c0__b_byte(b, C0_ETB);
3473}
3474
3475void c0_builder_etb_payload(c0_builder *b, const uint8_t *payload, size_t plen) {
3476 c0_builder_etb(b);
3477 c0__b_name(b, payload, plen);
3478}
3479
3480void c0_builder_em(c0_builder *b, const uint8_t *tail, size_t tlen) {
3481 c0__b_end_record(b);
3482 c0__b_byte(b, C0_EM);
3483 c0__b_raw(b, tail, tlen);
3484}
3485
3486void c0_builder_fs_str(c0_builder *b, const char *name) { c0_bytes n = c0__cstr(name); c0_builder_fs(b, n.ptr, n.len); }
3487void c0_builder_gs_str(c0_builder *b, const char *name) { c0_bytes n = c0__cstr(name); c0_builder_gs_name(b, n.ptr, n.len); }
3488void c0_builder_rs_str(c0_builder *b, const char *value) { c0_bytes v = c0__cstr(value); c0_builder_rs_value(b, v.ptr, v.len); }
3489void c0_builder_us_str(c0_builder *b, const char *value) { c0_bytes v = c0__cstr(value); c0_builder_us_value(b, v.ptr, v.len); }
3490void c0_builder_soh_str(c0_builder *b, const char *name) { c0_bytes n = c0__cstr(name); c0_builder_soh_name(b, n.ptr, n.len); }
3491void c0_builder_bel_str(c0_builder *b, const char *text) { c0_bytes t = c0__cstr(text); c0_builder_bel_text(b, t.ptr, t.len); }
3492void c0_builder_enq_str(c0_builder *b, const char *name) { c0_bytes n = c0__cstr(name); c0_builder_enq(b, n.ptr, n.len); }
3493void c0_builder_etb_str(c0_builder *b, const char *payload) { c0_bytes p = c0__cstr(payload); c0_builder_etb_payload(b, p.ptr, p.len); }
3494void c0_builder_em_str(c0_builder *b, const char *tail) { c0_bytes t = c0__cstr(tail); c0_builder_em(b, t.ptr, t.len); }
3495
3496/* ---- composed: wrappers over the primitives ---- */
3497
3498void c0_build_syn(c0_builder *b) { c0_builder_syn(b); }
3499
3500void c0_build_eot(c0_builder *b) { c0_builder_eot(b); }
3501
3502void c0_build_etb(c0_builder *b, const uint8_t *payload, size_t plen) {
3503 if (payload && plen) c0_builder_etb_payload(b, payload, plen);
3504 else c0_builder_etb(b);
3505}
3506
3507void c0_build_em(c0_builder *b, const uint8_t *tail, size_t tlen) { c0_builder_em(b, tail, tlen); }
3508
3509void c0_build_file(c0_builder *b, const uint8_t *name, size_t nlen) { c0_builder_fs(b, name, nlen); }
3510
3511void c0_build_section(c0_builder *b, const uint8_t *name, size_t nlen, size_t depth) {
3512 size_t i;
3513 c0__b_end_record(b);
3514 for (i = 1; i < depth; i++) c0__b_byte(b, C0_SUB);
3515 c0_builder_gs_name(b, name, nlen);
3516}
3517
3518void c0_build_group(c0_builder *b, const uint8_t *name, size_t nlen) { c0_builder_gs_name(b, name, nlen); }
3519
3520void c0_build_header(c0_builder *b, const c0_bytes *names, size_t count) {
3521 size_t i;
3522 for (i = 0; i < count; i++) { /* validate before writing anything */
3523 if (!c0_is_name(names[i].ptr, names[i].len)) {
3524 if (b->status == C0_OK) b->status = C0_ERR_BAD_NAME;
3525 return;
3526 }
3527 }
3528 c0__b_end_record(b);
3529 c0_builder_soh(b);
3530 c0_builder_rs(b);
3531 for (i = 0; i < count; i++) {
3532 if (i) c0_builder_us(b);
3533 c0__b_raw(b, names[i].ptr, names[i].len);
3534 }
3535 c0__b_end_record(b);
3536}
3537
3538void c0_build_record(c0_builder *b, const c0_bytes *fields, size_t count) {
3539 size_t i;
3540 c0_builder_rs(b);
3541 for (i = 0; i < count; i++) c0_build_field(b, fields[i].ptr, fields[i].len);
3542}
3543
3544void c0_build_field(c0_builder *b, const uint8_t *value, size_t vlen) {
3545 if (b->state != C0__B_RECORD) c0_builder_rs_value(b, value, vlen);
3546 else if (b->units == 0) c0__b_first_value(b, value, vlen);
3547 else c0_builder_us_value(b, value, vlen);
3548}
3549
3550/* A sub-unit hangs off the unit just written; the first unit of a record
3551 * exists even when empty, so one may follow a bare RS. It is not a unit:
3552 * the unit count is unchanged, except that the empty first unit now exists. */
3553void c0_build_sub_unit(c0_builder *b, const uint8_t *value, size_t vlen, size_t depth) {
3554 size_t i;
3555 if (depth == 0) {
3556 if (b->status == C0_OK) b->status = C0_ERR_BAD_STATE;
3557 return;
3558 }
3559 if (b->state != C0__B_RECORD) c0_builder_rs(b);
3560 if (b->units == 0) b->units = 1;
3561 for (i = 0; i < depth; i++) c0__b_byte(b, C0_SUB);
3562 c0__b_byte(b, C0_US);
3563 c0__b_value(b, value, vlen);
3564}
3565
3566void c0_build_map(c0_builder *b, const c0_bytes *keys, const c0_bytes *values, size_t count) {
3567 size_t i;
3568 c0_builder_rs(b);
3569 for (i = 0; i < count; i++) c0_build_key(b, keys[i].ptr, keys[i].len, values[i].ptr, values[i].len);
3570}
3571
3572void c0_build_key(c0_builder *b, const uint8_t *key, size_t klen, const uint8_t *value, size_t vlen) {
3573 c0__b_key_head(b, key, klen);
3574 c0_builder_us_value(b, value, vlen);
3575}
3576
3578 c0__b_next_unit(b);
3579 c0_builder_dle(b);
3580}
3581
3582void c0_build_key_level_open(c0_builder *b, const uint8_t *key, size_t klen) {
3583 c0__b_key_head(b, key, klen);
3584 c0_builder_us(b);
3585 c0_builder_dle(b);
3586}
3587
3589
3590void c0_build_list(c0_builder *b, const c0_bytes *items, size_t count) {
3591 size_t i;
3592 c0__b_next_unit(b);
3593 c0_builder_dle(b);
3594 if (count) {
3595 c0_builder_rs(b);
3596 for (i = 0; i < count; i++) c0_build_field(b, items[i].ptr, items[i].len);
3597 }
3598 c0_builder_can(b);
3599}
3600
3601void c0_build_ref(c0_builder *b, const uint8_t *name, size_t nlen) {
3602 c0__b_next_unit(b);
3603 c0_builder_enq(b, name, nlen);
3604}
3605
3607 c0__b_next_unit(b);
3609}
3610
3611void c0_build_ref_record(c0_builder *b, const uint8_t *group, size_t glen, const uint8_t *record, size_t rlen, const uint8_t *field, size_t flen) {
3612 if (glen == 0 || rlen == 0 || (field && flen == 0)) {
3613 if (b->status == C0_OK) b->status = C0_ERR_BAD_NAME;
3614 return;
3615 }
3617 c0_builder_gs_name(b, group, glen);
3618 c0_builder_rs(b);
3619 c0__b_name(b, record, rlen);
3620 b->units = 1;
3621 if (field) {
3622 c0_builder_us(b);
3623 c0__b_name(b, field, flen);
3624 }
3625 c0_builder_can(b);
3626}
3627
3628void c0_build_note(c0_builder *b, const uint8_t *text, size_t tlen) { c0_builder_bel_text(b, text, tlen); }
3629
3630void c0_build_block(c0_builder *b, const uint8_t *text, size_t tlen) {
3631 c0_bytes f;
3632 f.ptr = text;
3633 f.len = tlen;
3634 c0_build_record(b, &f, 1);
3635}
3636
3637void c0_build_item(c0_builder *b, const uint8_t *text, size_t tlen) { c0_build_field(b, text, tlen); }
3638
3639void c0_build_etb_str(c0_builder *b, const char *payload) {
3640 c0_bytes p = payload ? c0__cstr(payload) : c0__cstr("");
3641 c0_build_etb(b, p.ptr, p.len);
3642}
3643void c0_build_file_str(c0_builder *b, const char *name) { c0_bytes n = c0__cstr(name); c0_build_file(b, n.ptr, n.len); }
3644void c0_build_group_str(c0_builder *b, const char *name) { c0_bytes n = c0__cstr(name); c0_build_group(b, n.ptr, n.len); }
3645void c0_build_section_str(c0_builder *b, const char *name, size_t depth) { c0_bytes n = c0__cstr(name); c0_build_section(b, n.ptr, n.len, depth); }
3646void c0_build_header_str(c0_builder *b, const char *const *names, size_t count) {
3647 c0_bytes *v = c0__cstrs(b, names, count);
3648 if (!v) return;
3649 c0_build_header(b, v, count);
3650 free(v);
3651}
3652void c0_build_record_str(c0_builder *b, const char *const *fields, size_t count) {
3653 c0_bytes *v = c0__cstrs(b, fields, count);
3654 if (!v) return;
3655 c0_build_record(b, v, count);
3656 free(v);
3657}
3658void c0_build_field_str(c0_builder *b, const char *value) { c0_bytes v = c0__cstr(value); c0_build_field(b, v.ptr, v.len); }
3659void c0_build_sub_unit_str(c0_builder *b, const char *value, size_t depth) {
3660 c0_bytes v = c0__cstr(value);
3661 c0_build_sub_unit(b, v.ptr, v.len, depth);
3662}
3663void c0_build_map_str(c0_builder *b, const char *const *keys, const char *const *values, size_t count) {
3664 size_t i;
3665 c0_builder_rs(b);
3666 for (i = 0; i < count; i++) c0_build_key_str(b, keys[i], values[i]);
3667}
3668void c0_build_key_str(c0_builder *b, const char *key, const char *value) {
3669 c0_bytes k = c0__cstr(key), v = c0__cstr(value);
3670 c0_build_key(b, k.ptr, k.len, v.ptr, v.len);
3671}
3672void c0_build_key_level_open_str(c0_builder *b, const char *key) { c0_bytes k = c0__cstr(key); c0_build_key_level_open(b, k.ptr, k.len); }
3673void c0_build_list_str(c0_builder *b, const char *const *items, size_t count) {
3674 c0_bytes *v = c0__cstrs(b, items, count);
3675 if (!v) return;
3676 c0_build_list(b, v, count);
3677 free(v);
3678}
3679void c0_build_ref_str(c0_builder *b, const char *name) { c0_bytes n = c0__cstr(name); c0_build_ref(b, n.ptr, n.len); }
3680void c0_build_ref_record_str(c0_builder *b, const char *group, const char *record, const char *field) {
3681 c0_bytes g = c0__cstr(group), r = c0__cstr(record), f = field ? c0__cstr(field) : c0__cstr("");
3682 c0_build_ref_record(b, g.ptr, g.len, r.ptr, r.len, field ? f.ptr : NULL, f.len);
3683}
3684void c0_build_note_str(c0_builder *b, const char *text) { c0_bytes t = c0__cstr(text); c0_build_note(b, t.ptr, t.len); }
3685void c0_build_block_str(c0_builder *b, const char *text) { c0_bytes t = c0__cstr(text); c0_build_block(b, t.ptr, t.len); }
3686void c0_build_item_str(c0_builder *b, const char *text) { c0_bytes t = c0__cstr(text); c0_build_item(b, t.ptr, t.len); }
3687
3688/* ---- stream ------------------------------------------------------------ */
3689
3690/* After an ETB at pos-1: skip its payload; the result is committed_end
3691 * (layout after the payload belongs to the next block). */
3692static size_t c0__payload_end(const uint8_t *buf, size_t pos, size_t len) {
3693 size_t p = c0__layout(buf, pos, len);
3694 if (p < len && buf[p] >= 0x20) {
3695 p = c0__plain(buf, p, len);
3696 while (p > pos && buf[p - 1] == C0_SP) p--;
3697 return p;
3698 }
3699 return pos;
3700}
3701
3702static c0_block_iter c0__blocks(const uint8_t *buf, size_t stop) {
3703 c0_block_iter it;
3704 it.buf = buf;
3705 it.stop = stop;
3706 it.pos = 0;
3707 it.block_start = 0;
3708 it.in_text = 0;
3709 it.index = 0;
3710 c0__st_init(&it.st);
3711 return it;
3712}
3713
3714c0_block_iter c0_stream_blocks(const c0_stream *s) { return c0__blocks(s->buf, s->committed_end); }
3715
3716/* Parse one block in the context carried in st: on success st advances,
3717 * on an error (the block is damaged) it is left as it was. */
3718static int c0__block_sound(c0_parse_state *st, const uint8_t *buf, size_t start, size_t stop) {
3719 c0__parser p;
3720 c0_parse_state tmp = *st;
3721 c0__p_init(&p, buf, 0);
3722 c0__p_run(&p, &tmp, start, stop);
3723 if (C0__P_ERR(&p)) return 0;
3724 *st = tmp;
3725 return 1;
3726}
3727
3728int c0_next_block(c0_block_iter *it, c0_bytes *out, int *damaged) {
3729 const uint8_t *buf = it->buf;
3730 while (it->pos < it->stop) {
3731 uint8_t b = buf[it->pos];
3732 int commit = 0;
3733 if (it->in_text) {
3734 if (b == C0_DLE) {
3735 it->pos += 2;
3736 continue;
3737 } else if (b == C0_ETX) {
3738 it->in_text = 0;
3739 } else if (b == C0_ETB) {
3740 commit = 1;
3741 } else if (b == C0_SYN || b == C0_EOT || b == C0_EM) {
3742 it->in_text = 0; /* framing cuts the text */
3743 if (b == C0_SYN) it->block_start = it->pos;
3744 }
3745 } else {
3746 if (b == C0_STX) {
3747 it->in_text = 1;
3748 } else if (b == C0_ETB) {
3749 commit = 1;
3750 } else if (b == C0_SYN && it->pos > 0) {
3751 it->block_start = it->pos; /* tears the uncommitted bytes before it */
3752 }
3753 }
3754 if (commit) {
3755 int sound = c0__block_sound(&it->st, buf, it->block_start, it->pos);
3756 *out = c0__slice(buf, it->block_start, it->pos);
3757 if (damaged) *damaged = !sound;
3758 it->pos = c0__payload_end(buf, it->pos + 1, it->stop);
3759 it->block_start = it->pos;
3760 it->in_text = 0;
3761 it->index++;
3762 return 1;
3763 }
3764 it->pos++;
3765 }
3766 return 0;
3767}
3768
3769/* Is the tail after committed_end more than layout, notes, EOT or EM? */
3770static int c0__torn_tail(const uint8_t *buf, size_t pos, size_t len) {
3771 c0_error err = {C0_OK, 0, ""};
3772 for (;;) {
3773 uint8_t b;
3774 pos = c0__layout(buf, pos, len);
3775 if (pos >= len) return 0;
3776 b = buf[pos];
3777 if (b == C0_EOT) {
3778 pos++;
3779 } else if (b == C0_EM) {
3780 return 0; /* the raw region is not data */
3781 } else if (b == C0_BEL) {
3782 if (c0__bel_kills_element(buf, pos, len)) return 1; /* a dead element is data */
3783 pos = c0__comment(buf, pos, len, &err);
3784 if (err.code) return 1;
3785 } else {
3786 return 1;
3787 }
3788 }
3789}
3790
3791c0_stream c0_stream_read(const uint8_t *buf, size_t len) {
3792 c0_stream s;
3793 c0_block_iter it = c0__blocks(buf, len);
3794 c0_bytes blk;
3795 int damaged;
3796 s.buf = buf;
3797 s.len = len;
3798 s.committed_end = 0;
3799 s.block_count = 0;
3800 s.damaged_count = 0;
3801 s.has_damaged = 0;
3802 s.first_damaged = 0;
3803 s.resume_offset = 0;
3804 while (c0_next_block(&it, &blk, &damaged)) {
3805 if (damaged) {
3806 if (!s.has_damaged) {
3807 s.has_damaged = 1;
3809 s.resume_offset = it.pos;
3810 }
3811 s.damaged_count++;
3812 }
3813 s.block_count++;
3814 s.committed_end = it.pos;
3815 }
3816 s.torn = c0__torn_tail(buf, s.committed_end, len);
3817 return s;
3818}
3819
3820c0_bytes c0_stream_committed(const c0_stream *s) { return c0__slice(s->buf, 0, s->committed_end); }
3821c0_bytes c0_stream_tail(const c0_stream *s) { return c0__slice(s->buf, s->committed_end, s->len); }
3822
3823static size_t c0__stream_copy(const c0_stream *s, uint8_t *out, int stop_at_damage) {
3825 c0_bytes blk;
3826 int damaged;
3827 size_t n = 0;
3828 while (c0_next_block(&it, &blk, &damaged)) {
3829 if (damaged) {
3830 if (stop_at_damage) break;
3831 continue;
3832 }
3833 if (blk.len) memcpy(out + n, blk.ptr, blk.len);
3834 n += blk.len;
3835 }
3836 return n;
3837}
3838
3839size_t c0_stream_undamaged(const c0_stream *s, uint8_t *out) { return c0__stream_copy(s, out, 0); }
3840size_t c0_stream_before_damage(const c0_stream *s, uint8_t *out) { return c0__stream_copy(s, out, 1); }
3841
3842size_t c0_stream_last_commit_end(const uint8_t *buf, size_t len) {
3843 size_t i = len;
3844 while (i > 0) {
3845 i--;
3846 if (buf[i] == C0_ETB) {
3847 size_t dles = 0, j = i;
3848 while (j > 0 && buf[j - 1] == C0_DLE) {
3849 dles++;
3850 j--;
3851 }
3852 if (dles % 2 == 0) return c0__plain(buf, i + 1, len);
3853 }
3854 }
3855 return 0;
3856}
3857
3858/* ---- pretty form (pretty.cr) ------------------------------------------- */
3859
3860typedef struct {
3861 uint8_t *d;
3862 size_t n;
3863 size_t cap;
3864 int oom;
3865} c0__sb;
3866
3867static int c0__sb_reserve(c0__sb *s, size_t extra) {
3868 if (s->oom) return 0;
3869 if (s->n + extra > s->cap) {
3870 size_t ncap = s->cap ? s->cap : 64;
3871 uint8_t *nd;
3872 while (ncap < s->n + extra) ncap *= 2;
3873 nd = (uint8_t *)realloc(s->d, ncap);
3874 if (!nd) {
3875 s->oom = 1;
3876 return 0;
3877 }
3878 s->d = nd;
3879 s->cap = ncap;
3880 }
3881 return 1;
3882}
3883
3884static void c0__sb_byte(c0__sb *s, uint8_t b) {
3885 if (c0__sb_reserve(s, 1)) s->d[s->n++] = b;
3886}
3887
3888static void c0__sb_raw(c0__sb *s, const uint8_t *p, size_t n) {
3889 if (n && c0__sb_reserve(s, n)) {
3890 memcpy(s->d + s->n, p, n);
3891 s->n += n;
3892 }
3893}
3894
3895static void c0__sb_cstr(c0__sb *s, const char *p) { c0__sb_raw(s, (const uint8_t *)p, strlen(p)); }
3896
3897/* U+2400 + byte as 3-byte UTF-8. */
3898static void c0__sb_glyph(c0__sb *s, uint8_t byte) {
3899 c0__sb_byte(s, 0xE2);
3900 c0__sb_byte(s, 0x90);
3901 c0__sb_byte(s, (uint8_t)(0x80 | byte));
3902}
3903
3904static void c0__sb_spaces(c0__sb *s, size_t n) {
3905 while (n--) c0__sb_byte(s, ' ');
3906}
3907
3908typedef struct {
3909 const uint8_t *buf;
3910 size_t len;
3911 c0__sb *o;
3912 const char *indent;
3913 size_t ilen;
3914 size_t depth; /* nesting depth (levels) */
3915 size_t gdepth; /* group depth within the current level */
3916 int ls; /* at the start of a line */
3917 int prefixed; /* a ␚ already opened this line (before a GS or FS line) */
3918 size_t *stack;
3919 size_t sn, scap;
3920 c0_error *err;
3921} c0__pf;
3922
3923static void c0__pf_push(c0__pf *f, size_t v) {
3924 if (f->sn == f->scap) {
3925 size_t ncap = f->scap ? f->scap * 2 : 16;
3926 size_t *ns = (size_t *)realloc(f->stack, ncap * sizeof(size_t));
3927 if (!ns) {
3928 c0__fail(f->err, C0_ERR_OOM, 0, "out of memory");
3929 return;
3930 }
3931 f->stack = ns;
3932 f->scap = ncap;
3933 }
3934 f->stack[f->sn++] = v;
3935}
3936
3937static size_t c0__pf_pop(c0__pf *f) { return f->sn ? f->stack[--f->sn] : 0; }
3938
3939/* Pretty form cannot show a value holding a Control Picture (U+2400-U+241F:
3940 * UTF-8 E2 90 80-9F). */
3941static void c0__check_glyphs(c0__pf *f, const uint8_t *p, size_t n) {
3942 size_t i;
3943 for (i = 0; i + 2 < n; i++) {
3944 if (p[i] == 0xE2 && p[i + 1] == 0x90 && p[i + 2] >= 0x80 && p[i + 2] <= 0x9F) {
3945 c0__fail(f->err, C0_ERR_SYNTAX, 0, "glyph in data");
3946 return;
3947 }
3948 }
3949}
3950
3951static void c0__pf_data(c0__pf *f, c0_bytes d) {
3952 c0__check_glyphs(f, d.ptr, d.len);
3953 c0__sb_raw(f->o, d.ptr, d.len);
3954}
3955
3956/* A whole text (STX … ETX): glyphs for the brackets and for any control
3957 * byte inside other than HT, LF and CR; everything else as is. */
3958static void c0__pf_text(c0__pf *f, c0_bytes t) {
3959 size_t i;
3960 c0__check_glyphs(f, t.ptr, t.len);
3961 c0__sb_glyph(f->o, C0_STX);
3962 for (i = 1; i + 1 < t.len; i++) {
3963 uint8_t b = t.ptr[i];
3964 if (b < 0x20 && b != C0_LF && b != C0_CR && b != C0_HT) c0__sb_glyph(f->o, b);
3965 else c0__sb_byte(f->o, b);
3966 }
3967 c0__sb_glyph(f->o, C0_ETX);
3968}
3969
3970static size_t c0__pf_plain(c0__pf *f, size_t pos) {
3971 size_t start;
3972 pos = c0__layout(f->buf, pos, f->len);
3973 start = pos;
3974 pos = c0__plain(f->buf, pos, f->len);
3975 c0__pf_data(f, c0_trim(c0__slice(f->buf, start, pos)));
3976 return pos;
3977}
3978
3979static void c0__pf_indent(c0__pf *f, size_t depth) {
3980 while (depth--) c0__sb_raw(f->o, (const uint8_t *)f->indent, f->ilen);
3981}
3982
3983static void c0__pf_nl(c0__pf *f) {
3984 if (!f->ls) c0__sb_byte(f->o, '\n');
3985}
3986
3987/* A level written on one line (heading values). */
3988static void c0__pf_inline_level(c0__pf *f, c0_bytes raw) {
3989 size_t i = 0;
3990 while (i < raw.len && !f->err->code) {
3991 uint8_t b = raw.ptr[i];
3992 if (b == C0_STX) {
3993 size_t stop = c0__text(raw.ptr, i, raw.len, f->err);
3994 c0__pf_text(f, c0__slice(raw.ptr, i, stop));
3995 i = stop;
3996 } else if (b >= 0x20) {
3997 size_t start = i;
3998 i = c0__plain(raw.ptr, i, raw.len);
3999 c0__pf_data(f, c0_trim(c0__slice(raw.ptr, start, i)));
4000 } else if (c0_is_layout(b)) {
4001 i++;
4002 } else {
4003 c0__sb_glyph(f->o, b);
4004 i++;
4005 }
4006 }
4007}
4008
4009/* Units of a record, header or heading on the current line. Stops at a
4010 * record-level code. A level opener writes ␐, breaks the line and raises the
4011 * depth; the caller resumes at the matching CAN. */
4012static size_t c0__pf_units(c0__pf *f, size_t pos) {
4013 const uint8_t *buf = f->buf;
4014 size_t len = f->len;
4015 while (pos < len && !f->err->code) {
4016 uint8_t b = buf[pos];
4017 if (b >= 0x20) {
4018 size_t start = pos;
4019 pos = c0__plain(buf, pos, len);
4020 c0__pf_data(f, c0_trim(c0__slice(buf, start, pos)));
4021 } else if (c0_is_layout(b)) {
4022 pos++;
4023 } else if (b == C0_US || b == C0_ENQ) {
4024 c0__sb_glyph(f->o, b);
4025 pos++;
4026 } else if (b == C0_SUB) {
4027 /* a sub-unit (a SUB run then US) is inside this record, on this
4028 * line; a SUB run before a line code prefixes the next element */
4029 size_t run, p2;
4030 c0__sub_run(buf, pos, len, &run, &p2);
4031 if (!(p2 < len && buf[p2] == C0_US)) break;
4032 while (run--) c0__sb_glyph(f->o, C0_SUB);
4033 pos = p2;
4034 } else if (b == C0_SOH) {
4035 size_t p2 = c0__layout(buf, pos + 1, len);
4036 if (p2 < len && buf[p2] == C0_RS) break;
4037 c0__sb_glyph(f->o, C0_SOH);
4038 pos++;
4039 } else if (b == C0_STX) {
4040 size_t stop = c0__text(buf, pos, len, f->err);
4041 c0__pf_text(f, c0__slice(buf, pos, stop));
4042 pos = stop;
4043 } else if (b == C0_DLE) {
4044 c0__sb_glyph(f->o, C0_DLE);
4045 c0__sb_byte(f->o, '\n');
4046 c0__pf_push(f, f->gdepth);
4047 f->depth++;
4048 f->ls = 1;
4049 return pos + 1;
4050 } else if (b == C0_BEL) {
4051 size_t p2 = c0__layout(buf, pos + 1, len);
4052 if (p2 < len && (buf[p2] >= 0x20 || buf[p2] == C0_STX || buf[p2] == C0_DLE)) {
4053 c0__sb_glyph(f->o, C0_BEL);
4054 pos = p2;
4055 } else {
4056 break;
4057 }
4058 } else if (b == C0_ETB) {
4059 c0__sb_glyph(f->o, C0_ETB);
4060 pos = c0__pf_plain(f, pos + 1);
4061 } else {
4062 break;
4063 }
4064 }
4065 f->ls = 0;
4066 return pos;
4067}
4068
4069/* SOH / RS / BEL / ETB at element level: the element and its units on one
4070 * line (a level opener breaks the line). */
4071static size_t c0__pf_element(c0__pf *f, size_t pos) {
4072 const uint8_t *buf = f->buf;
4073 size_t len = f->len;
4074 uint8_t b = buf[pos];
4075 f->ls = 0;
4076 if (b == C0_BEL) {
4077 c0__sb_glyph(f->o, C0_BEL);
4078 pos = c0__layout(buf, pos + 1, len);
4079 if (pos < len && (buf[pos] >= 0x20 || buf[pos] == C0_STX)) {
4080 pos = c0__pf_units(f, pos);
4081 c0__sb_byte(f->o, '\n');
4082 f->ls = 1;
4083 return pos;
4084 }
4085 if (pos >= len) return pos;
4086 return c0__pf_element(f, pos); /* a dead element, rendered on this line */
4087 } else if (b == C0_SUB) {
4088 /* a SUB before a line code stands with the element it prefixes */
4089 c0__sb_glyph(f->o, C0_SUB);
4090 pos = c0__layout(buf, pos + 1, len);
4091 if (pos >= len) return pos;
4092 return c0__pf_element(f, pos);
4093 } else if (b == C0_SOH) {
4094 c0__sb_glyph(f->o, C0_SOH);
4095 pos = c0__layout(buf, pos + 1, len);
4096 if (pos < len && buf[pos] == C0_RS) {
4097 c0__sb_glyph(f->o, C0_RS);
4098 pos++;
4099 }
4100 pos = c0__pf_units(f, pos);
4101 } else if (b == C0_RS) {
4102 c0__sb_glyph(f->o, C0_RS);
4103 pos = c0__pf_units(f, pos + 1);
4104 } else if (b == C0_ETB) {
4105 c0__sb_glyph(f->o, C0_ETB);
4106 pos = c0__pf_plain(f, pos + 1);
4107 }
4108 if (!f->ls) {
4109 c0__sb_byte(f->o, '\n');
4110 f->ls = 1;
4111 }
4112 return pos;
4113}
4114
4115static size_t c0__pf_heading(c0__pf *f, size_t pos) {
4116 const uint8_t *buf = f->buf;
4117 size_t len = f->len;
4118 while (pos < len && !f->err->code) {
4119 uint8_t b = buf[pos];
4120 if (b == C0_SOH) {
4121 size_t p2 = c0__layout(buf, pos + 1, len);
4122 if (p2 < len && buf[p2] == C0_RS) break;
4123 c0__sb_glyph(f->o, C0_SOH);
4124 pos = c0__pf_plain(f, p2);
4125 if (pos < len && buf[pos] == C0_US) {
4126 c0__sb_glyph(f->o, C0_US);
4127 pos = c0__layout(buf, pos + 1, len);
4128 if (pos < len && buf[pos] == C0_STX) {
4129 size_t stop = c0__text(buf, pos, len, f->err);
4130 c0__pf_text(f, c0__slice(buf, pos, stop));
4131 pos = stop;
4132 } else if (pos < len && buf[pos] == C0_DLE) {
4133 size_t stop = c0__level(buf, pos, len, f->err);
4134 c0__pf_inline_level(f, c0__slice(buf, pos, stop));
4135 pos = stop;
4136 } else {
4137 pos = c0__pf_plain(f, pos);
4138 }
4139 }
4140 } else if (b == C0_BEL) {
4141 size_t p2 = c0__layout(buf, pos + 1, len);
4142 if (p2 < len && (buf[p2] >= 0x20 || buf[p2] == C0_STX)) {
4143 c0__sb_glyph(f->o, C0_BEL);
4144 pos = p2;
4145 if (buf[pos] == C0_STX) {
4146 size_t stop = c0__text(buf, pos, len, f->err);
4147 c0__pf_text(f, c0__slice(buf, pos, stop));
4148 pos = stop;
4149 } else {
4150 pos = c0__pf_plain(f, pos);
4151 }
4152 } else if (p2 < len && buf[p2] == C0_SOH) {
4153 c0__sb_glyph(f->o, C0_BEL);
4154 pos = p2;
4155 } else {
4156 break;
4157 }
4158 } else if (c0_is_layout(b)) {
4159 pos++;
4160 } else {
4161 break;
4162 }
4163 }
4164 return pos;
4165}
4166
4167static void c0__pf_compact(c0__pf *f) {
4168 const uint8_t *buf = f->buf;
4169 size_t len = f->len, pos = 0;
4170 f->depth = 0;
4171 f->gdepth = 0;
4172 f->ls = 1;
4173 while (pos < len && !f->err->code) {
4174 uint8_t b = buf[pos];
4175 if (b >= 0x20 || c0_is_layout(b)) {
4176 if (c0_is_layout(b)) {
4177 pos++;
4178 } else {
4179 size_t start = pos;
4180 pos = c0__plain(buf, pos, len);
4181 c0__pf_data(f, c0__slice(buf, start, pos));
4182 f->ls = 0;
4183 }
4184 continue;
4185 }
4186 switch (b) {
4187 case C0_SYN:
4188 c0__pf_nl(f);
4189 c0__sb_glyph(f->o, C0_SYN);
4190 pos = c0__pf_heading(f, pos + 1);
4191 c0__sb_byte(f->o, '\n');
4192 f->ls = 1;
4193 f->gdepth = 0;
4194 break;
4195 case C0_FS:
4196 if (!f->prefixed) {
4197 c0__pf_nl(f);
4198 c0__pf_indent(f, f->depth);
4199 }
4200 f->prefixed = 0;
4201 c0__sb_glyph(f->o, C0_FS);
4202 pos = c0__pf_plain(f, pos + 1);
4203 c0__sb_byte(f->o, '\n');
4204 f->ls = 1;
4205 f->gdepth = 1;
4206 break;
4207 case C0_GS:
4208 if (!f->prefixed) {
4209 c0__pf_nl(f);
4210 c0__pf_indent(f, f->depth);
4211 }
4212 f->prefixed = 0;
4213 c0__sb_glyph(f->o, C0_GS);
4214 pos = c0__pf_plain(f, pos + 1);
4215 c0__sb_byte(f->o, '\n');
4216 f->ls = 1;
4217 f->gdepth = 1;
4218 break;
4219 case C0_SUB: {
4220 /* a depth prefix stands on the line of the group it qualifies */
4221 size_t run, p2;
4222 c0__sub_run(buf, pos, len, &run, &p2);
4223 if (p2 < len && (buf[p2] == C0_GS || buf[p2] == C0_FS)) {
4224 c0__pf_nl(f);
4225 c0__pf_indent(f, f->depth);
4226 while (run--) c0__sb_glyph(f->o, C0_SUB);
4227 f->prefixed = 1;
4228 f->ls = 0;
4229 pos = p2;
4230 break;
4231 }
4232 c0__pf_nl(f);
4233 c0__pf_indent(f, f->depth + f->gdepth);
4234 pos = c0__pf_element(f, pos);
4235 break;
4236 }
4237 case C0_SOH:
4238 case C0_RS:
4239 case C0_BEL:
4240 case C0_ETB:
4241 c0__pf_nl(f);
4242 c0__pf_indent(f, f->depth + f->gdepth);
4243 pos = c0__pf_element(f, pos);
4244 break;
4245 case C0_CAN:
4246 if (f->depth > 0) f->depth--;
4247 f->gdepth = c0__pf_pop(f);
4248 c0__pf_nl(f);
4249 c0__pf_indent(f, f->depth + f->gdepth);
4250 c0__sb_glyph(f->o, C0_CAN);
4251 pos++;
4252 f->ls = 0;
4253 pos = c0__pf_units(f, pos); /* the rest of the enclosing record */
4254 if (!f->ls) {
4255 c0__sb_byte(f->o, '\n');
4256 f->ls = 1;
4257 }
4258 break;
4259 case C0_EOT:
4260 c0__pf_nl(f);
4261 c0__sb_glyph(f->o, C0_EOT);
4262 c0__sb_byte(f->o, '\n');
4263 pos++;
4264 f->ls = 1;
4265 break;
4266 case C0_EM: {
4267 size_t tail = len - pos - 1;
4268 c0__pf_nl(f);
4269 c0__sb_glyph(f->o, C0_EM);
4270 if (tail > 0) {
4271 char num[32];
4272 size_t k = sizeof(num);
4273 num[--k] = 0;
4274 do {
4275 num[--k] = (char)('0' + tail % 10);
4276 tail /= 10;
4277 } while (tail);
4278 c0__sb_byte(f->o, ' ');
4279 c0__sb_cstr(f->o, num + k);
4280 c0__sb_cstr(f->o, " bytes");
4281 }
4282 c0__sb_byte(f->o, '\n');
4283 return;
4284 }
4285 case C0_STX:
4286 case C0_DLE:
4287 case C0_ENQ:
4288 case C0_US:
4289 /* a unit-level code at element level: inline */
4290 pos = c0__pf_units(f, pos);
4291 c0__sb_byte(f->o, '\n');
4292 f->ls = 1;
4293 break;
4294 default:
4295 c0__fail(f->err, C0_ERR_UNASSIGNED, pos, "unassigned control code");
4296 return;
4297 }
4298 }
4299 if (!f->ls) c0__sb_byte(f->o, '\n');
4300}
4301
4302/* ---- alignment ---- */
4303
4304static int c0__glyph_at(c0_bytes s, size_t i, uint8_t *code) {
4305 if (i + 2 < s.len && s.ptr[i] == 0xE2 && s.ptr[i + 1] == 0x90 && (s.ptr[i + 2] & 0xE0) == 0x80) {
4306 *code = (uint8_t)(s.ptr[i + 2] & 0x1F);
4307 return 1;
4308 }
4309 return 0;
4310}
4311
4312static int c0__starts_glyph(c0_bytes s, uint8_t code) {
4313 uint8_t c;
4314 return c0__glyph_at(s, 0, &c) && c == code;
4315}
4316
4317static size_t c0__cp_count(c0_bytes s) {
4318 size_t i, n = 0;
4319 for (i = 0; i < s.len; i++) {
4320 if ((s.ptr[i] & 0xC0) != 0x80) n++;
4321 }
4322 return n;
4323}
4324
4325static size_t c0__utf8_adv(c0_bytes s, size_t i) {
4326 uint8_t c = s.ptr[i];
4327 size_t adv = 1;
4328 if ((c >> 5) == 0x6) adv = 2;
4329 else if ((c >> 4) == 0xE) adv = 3;
4330 else if ((c >> 3) == 0x1E) adv = 4;
4331 if (i + adv > s.len) adv = s.len - i;
4332 return adv;
4333}
4334
4335typedef struct {
4336 size_t line;
4337 c0_bytes prefix;
4338 c0_bytes *fields;
4339 int *sep_us; /* sep_us[i]: a ␟ stood between fields i and i+1 (else an SOH mark begins i+1) */
4340 size_t n, cap;
4341} c0__tline;
4342
4343static int c0__tl_push(c0__tline *t, c0_bytes field, int sep) {
4344 if (t->n == t->cap) {
4345 size_t ncap = t->cap ? t->cap * 2 : 8;
4346 c0_bytes *nf = (c0_bytes *)realloc(t->fields, ncap * sizeof(c0_bytes));
4347 int *ns;
4348 if (!nf) return 0;
4349 t->fields = nf;
4350 ns = (int *)realloc(t->sep_us, ncap * sizeof(int));
4351 if (!ns) return 0;
4352 t->sep_us = ns;
4353 t->cap = ncap;
4354 }
4355 t->fields[t->n] = c0_trim(field);
4356 t->sep_us[t->n] = sep;
4357 t->n++;
4358 return 1;
4359}
4360
4361/* Split a ␞ or ␁␞ line into its units on ␟ (text is not split; a keyed
4362 * record splits on its ␁ marks too). Returns 1 and fills *t, 0 when the
4363 * line is not a table line, -1 on OOM. */
4364static int c0__parse_table_line(c0_bytes text, size_t line, c0__tline *t) {
4365 size_t i = 0, field_start;
4366 uint8_t code;
4367 int in_text = 0, keyed;
4368 memset(t, 0, sizeof(*t));
4369 t->line = line;
4370 while (i < text.len && (text.ptr[i] == ' ' || text.ptr[i] == '\t')) i++;
4371 if (i >= text.len) return 0;
4372 if (c0__glyph_at(text, i, &code) && code == C0_SOH) {
4373 i += 3;
4374 if (!(c0__glyph_at(text, i, &code) && code == C0_RS)) return 0;
4375 i += 3;
4376 } else if (c0__glyph_at(text, i, &code) && code == C0_RS) {
4377 i += 3;
4378 } else {
4379 return 0;
4380 }
4381 t->prefix = c0__slice(text.ptr, 0, i);
4382 keyed = c0__glyph_at(text, i, &code) && code == C0_SOH;
4383 field_start = i;
4384 while (i < text.len) {
4385 size_t adv = c0__utf8_adv(text, i);
4386 int is_glyph = c0__glyph_at(text, i, &code);
4387 if (in_text) {
4388 if (is_glyph && code == C0_ETX) in_text = 0;
4389 i += adv;
4390 if (is_glyph && code == C0_DLE && i < text.len) i += c0__utf8_adv(text, i);
4391 } else if (is_glyph && code == C0_STX) {
4392 in_text = 1;
4393 i += adv;
4394 } else if (is_glyph && (code == C0_DLE || code == C0_CAN)) {
4395 goto not_table; /* nested levels are not aligned */
4396 } else if (is_glyph && code == C0_US) {
4397 if (!c0__tl_push(t, c0__slice(text.ptr, field_start, i), 1)) goto oom;
4398 i += adv;
4399 field_start = i;
4400 } else if (keyed && is_glyph && code == C0_SOH && i > t->prefix.len) {
4401 if (!c0__tl_push(t, c0__slice(text.ptr, field_start, i), 0)) goto oom;
4402 field_start = i;
4403 i += adv;
4404 } else {
4405 i += adv;
4406 }
4407 }
4408 if (in_text) goto not_table; /* text continues on the next line */
4409 if (!c0__tl_push(t, c0__slice(text.ptr, field_start, text.len), 1)) goto oom;
4410 if (t->n < 2) goto not_table;
4411 return 1;
4412not_table:
4413 free(t->fields);
4414 free(t->sep_us);
4415 memset(t, 0, sizeof(*t));
4416 return 0;
4417oom:
4418 free(t->fields);
4419 free(t->sep_us);
4420 memset(t, 0, sizeof(*t));
4421 return -1;
4422}
4423
4424static int c0__is_prefix_glyph(uint8_t c) {
4425 return c == C0_FS || c == C0_GS || c == C0_RS || c == C0_SOH || c == C0_US || c == C0_SYN || c == C0_BEL;
4426}
4427
4428/* Reformat a compact pretty string with column alignment. Keyed records
4429 * align on their US like two-column tables. Returns 0 on OOM. */
4430static int c0__align(const uint8_t *pretty, size_t plen, int spaced, c0__sb *out) {
4431 c0_bytes *lines = NULL;
4432 size_t nlines = 0, i, s = 0;
4433 c0__tline *tl = NULL; /* table lines, grouped contiguously */
4434 size_t ntl = 0, tlcap = 0;
4435 size_t *gstart = NULL; /* start index into tl of each group */
4436 size_t ng = 0, gcap = 0;
4437 int in_group = 0;
4438 c0__sb *repl = NULL; /* replacement text per line (NULL = unchanged) */
4439 int ok = 0;
4440 const char *sp = spaced ? " " : "";
4441
4442 /* split lines */
4443 for (i = 0; i <= plen; i++) {
4444 if (i == plen || pretty[i] == '\n') {
4445 if (i == plen && i == s) break; /* drop the empty last line */
4446 {
4447 c0_bytes *nl = (c0_bytes *)realloc(lines, (nlines + 1) * sizeof(c0_bytes));
4448 if (!nl) goto done;
4449 lines = nl;
4450 }
4451 lines[nlines++] = c0__slice(pretty, s, i);
4452 s = i + 1;
4453 }
4454 }
4455 repl = (c0__sb *)calloc(nlines ? nlines : 1, sizeof(c0__sb));
4456 if (!repl) goto done;
4457
4458 /* find table groups */
4459 for (i = 0; i < nlines; i++) {
4460 c0_bytes trimmed = c0_trim(lines[i]);
4461 int close = 0;
4462 if (trimmed.len == 0 || c0__starts_glyph(trimmed, C0_GS) || c0__starts_glyph(trimmed, C0_FS) ||
4463 c0__starts_glyph(trimmed, C0_EOT) || c0__starts_glyph(trimmed, C0_SYN) || c0__starts_glyph(trimmed, C0_CAN)) {
4464 close = 1;
4465 } else if (c0__starts_glyph(trimmed, C0_SOH) || c0__starts_glyph(trimmed, C0_RS)) {
4466 c0__tline t;
4467 int r = c0__parse_table_line(lines[i], i, &t);
4468 if (r < 0) goto done;
4469 if (r == 0) {
4470 close = 1;
4471 } else {
4472 if (ntl == tlcap) {
4473 size_t ncap = tlcap ? tlcap * 2 : 16;
4474 c0__tline *nt = (c0__tline *)realloc(tl, ncap * sizeof(c0__tline));
4475 if (!nt) {
4476 free(t.fields);
4477 free(t.sep_us);
4478 goto done;
4479 }
4480 tl = nt;
4481 tlcap = ncap;
4482 }
4483 if (!in_group) {
4484 if (ng == gcap) {
4485 size_t ncap = gcap ? gcap * 2 : 16;
4486 size_t *ngs = (size_t *)realloc(gstart, ncap * sizeof(size_t));
4487 if (!ngs) {
4488 free(t.fields);
4489 free(t.sep_us);
4490 goto done;
4491 }
4492 gstart = ngs;
4493 gcap = ncap;
4494 }
4495 gstart[ng++] = ntl;
4496 in_group = 1;
4497 }
4498 tl[ntl++] = t;
4499 }
4500 } else {
4501 close = 1;
4502 }
4503 if (close) in_group = 0;
4504 }
4505
4506 /* align each group */
4507 for (i = 0; i < ng; i++) {
4508 size_t from = gstart[i], to = (i + 1 < ng) ? gstart[i + 1] : ntl, j, c, cols = 0;
4509 size_t *widths;
4510 for (j = from; j < to; j++) {
4511 if (tl[j].n > cols) cols = tl[j].n;
4512 }
4513 widths = (size_t *)calloc(cols ? cols : 1, sizeof(size_t));
4514 if (!widths) goto done;
4515 for (j = from; j < to; j++) {
4516 for (c = 0; c < tl[j].n; c++) {
4517 size_t w = c0__cp_count(tl[j].fields[c]);
4518 if (w > widths[c]) widths[c] = w;
4519 }
4520 }
4521 for (j = from; j < to; j++) {
4522 c0__sb *o = &repl[tl[j].line];
4523 c0__sb_raw(o, tl[j].prefix.ptr, tl[j].prefix.len);
4524 c0__sb_cstr(o, sp);
4525 for (c = 0; c < tl[j].n; c++) {
4526 c0__sb_raw(o, tl[j].fields[c].ptr, tl[j].fields[c].len);
4527 if (c + 1 < tl[j].n) {
4528 c0__sb_spaces(o, widths[c] - c0__cp_count(tl[j].fields[c]));
4529 if (tl[j].sep_us[c]) {
4530 c0__sb_cstr(o, sp);
4531 c0__sb_glyph(o, C0_US);
4532 c0__sb_cstr(o, sp);
4533 } else {
4534 c0__sb_byte(o, ' ');
4535 }
4536 }
4537 }
4538 if (o->oom) {
4539 free(widths);
4540 goto done;
4541 }
4542 }
4543 free(widths);
4544 }
4545
4546 /* other lines: one space after the prefix glyphs in spaced mode */
4547 for (i = 0; i < nlines; i++) {
4548 c0_bytes text = lines[i];
4549 size_t ws_end = 0, glyph_end;
4550 uint8_t code;
4551 c0_bytes rest;
4552 c0__sb *o = &repl[i];
4553 if (o->d) continue;
4554 if (c0_trim(text).len == 0) continue;
4555 while (ws_end < text.len && (text.ptr[ws_end] == ' ' || text.ptr[ws_end] == '\t')) ws_end++;
4556 glyph_end = ws_end;
4557 while (c0__glyph_at(text, glyph_end, &code) && c0__is_prefix_glyph(code)) glyph_end += 3;
4558 if (glyph_end == ws_end || glyph_end >= text.len) continue;
4559 rest = c0__slice(text.ptr, glyph_end, text.len);
4560 while (rest.len && c0_is_layout(rest.ptr[0])) {
4561 rest.ptr++;
4562 rest.len--;
4563 }
4564 c0__sb_raw(o, text.ptr, glyph_end);
4565 c0__sb_cstr(o, sp);
4566 c0__sb_raw(o, rest.ptr, rest.len);
4567 if (o->oom) goto done;
4568 }
4569
4570 for (i = 0; i < nlines; i++) {
4571 if (repl[i].d) c0__sb_raw(out, repl[i].d, repl[i].n);
4572 else c0__sb_raw(out, lines[i].ptr, lines[i].len);
4573 c0__sb_byte(out, '\n');
4574 }
4575 ok = !out->oom;
4576done:
4577 for (i = 0; i < ntl; i++) {
4578 free(tl[i].fields);
4579 free(tl[i].sep_us);
4580 }
4581 free(tl);
4582 free(gstart);
4583 if (repl) {
4584 for (i = 0; i < nlines; i++) free(repl[i].d);
4585 free(repl);
4586 }
4587 free(lines);
4588 return ok;
4589}
4590
4591char *c0_pretty_format(const uint8_t *buf, size_t len, const char *indent, c0_pretty_mode mode, size_t *outlen, c0_error *err) {
4592 c0__sb o = {NULL, 0, 0, 0}, aligned = {NULL, 0, 0, 0};
4593 c0__pf f;
4594 c0_error local = {C0_OK, 0, ""};
4595 if (!err) err = &local;
4596 c0__err_clear(err);
4597 memset(&f, 0, sizeof(f));
4598 f.buf = buf;
4599 f.len = len;
4600 f.o = &o;
4601 f.indent = indent ? indent : " ";
4602 f.ilen = strlen(f.indent);
4603 f.err = err;
4604 c0__pf_compact(&f);
4605 free(f.stack);
4606 if (o.oom) c0__fail(err, C0_ERR_OOM, 0, "out of memory");
4607 if (err->code) {
4608 free(o.d);
4609 return NULL;
4610 }
4611 if (mode != C0_PRETTY_COMPACT) {
4612 if (!c0__align(o.d, o.n, mode == C0_PRETTY_SPACED, &aligned)) {
4613 free(o.d);
4614 free(aligned.d);
4615 c0__fail(err, C0_ERR_OOM, 0, "out of memory");
4616 return NULL;
4617 }
4618 free(o.d);
4619 o = aligned;
4620 }
4621 c0__sb_byte(&o, 0);
4622 if (o.oom) {
4623 free(o.d);
4624 c0__fail(err, C0_ERR_OOM, 0, "out of memory");
4625 return NULL;
4626 }
4627 if (outlen) *outlen = o.n - 1;
4628 return (char *)o.d;
4629}
4630
4631/* Decode one UTF-8 code point at s[i]; *adv gets its byte length. */
4632static unsigned c0__utf8(const uint8_t *s, size_t len, size_t i, size_t *adv) {
4633 uint8_t c = s[i];
4634 if (c < 0x80) {
4635 *adv = 1;
4636 return c;
4637 } else if ((c >> 5) == 0x6 && i + 1 < len) {
4638 *adv = 2;
4639 return (unsigned)((c & 0x1F) << 6) | (s[i + 1] & 0x3F);
4640 } else if ((c >> 4) == 0xE && i + 2 < len) {
4641 *adv = 3;
4642 return (unsigned)((c & 0x0F) << 12) | ((unsigned)(s[i + 1] & 0x3F) << 6) | (s[i + 2] & 0x3F);
4643 } else if ((c >> 3) == 0x1E && i + 3 < len) {
4644 *adv = 4;
4645 return (unsigned)((c & 0x07) << 18) | ((unsigned)(s[i + 1] & 0x3F) << 12) |
4646 ((unsigned)(s[i + 2] & 0x3F) << 6) | (s[i + 3] & 0x3F);
4647 }
4648 *adv = 1;
4649 return c;
4650}
4651
4652/* Inside text: everything verbatim until the ETX glyph; a DLE glyph takes
4653 * the next glyph with it. */
4654static size_t c0__pp_text(const uint8_t *str, size_t len, size_t i, c0__sb *o) {
4655 while (i < len) {
4656 size_t adv;
4657 unsigned cp = c0__utf8(str, len, i, &adv);
4658 if (cp >= 0x2400 && cp <= 0x241F) {
4659 uint8_t code = (uint8_t)(cp - 0x2400);
4660 c0__sb_byte(o, code);
4661 i += adv;
4662 if (code == C0_DLE && i < len) {
4663 unsigned nx = c0__utf8(str, len, i, &adv);
4664 if (nx >= 0x2400 && nx <= 0x241F) {
4665 c0__sb_byte(o, (uint8_t)(nx - 0x2400));
4666 i += adv;
4667 }
4668 } else if (code == C0_ETX) {
4669 return i;
4670 }
4671 } else {
4672 c0__sb_raw(o, str + i, adv);
4673 i += adv;
4674 }
4675 }
4676 return i;
4677}
4678
4679uint8_t *c0_pretty_parse(const char *str_, size_t len, size_t *outlen) {
4680 const uint8_t *str = (const uint8_t *)str_;
4681 c0__sb o = {NULL, 0, 0, 0}, pending = {NULL, 0, 0, 0};
4682 size_t i = 0;
4683 int after_code = 1;
4684 while (i < len) {
4685 size_t adv;
4686 unsigned cp = c0__utf8(str, len, i, &adv);
4687 if (cp >= 0x2400 && cp <= 0x241F) {
4688 uint8_t code = (uint8_t)(cp - 0x2400);
4689 pending.n = 0;
4690 c0__sb_byte(&o, code);
4691 i += adv;
4692 if (code == C0_STX) {
4693 i = c0__pp_text(str, len, i, &o);
4694 } else if (code == C0_EM) {
4695 while (i < len && str[i] != '\n') i++; /* the rest of the line is a summary */
4696 }
4697 after_code = 1;
4698 } else if (cp == '\n' || cp == '\r') {
4699 pending.n = 0;
4700 after_code = 1;
4701 i += adv;
4702 } else if (cp == ' ' || cp == '\t') {
4703 if (!after_code) c0__sb_byte(&pending, (uint8_t)cp);
4704 i += adv;
4705 } else {
4706 if (pending.n) {
4707 c0__sb_raw(&o, pending.d, pending.n);
4708 pending.n = 0;
4709 }
4710 after_code = 0;
4711 c0__sb_raw(&o, str + i, adv);
4712 i += adv;
4713 }
4714 }
4715 free(pending.d);
4716 if (o.oom || pending.oom) {
4717 free(o.d);
4718 return NULL;
4719 }
4720 if (!o.d) o.d = (uint8_t *)malloc(1); /* non-NULL even when empty */
4721 if (outlen) *outlen = o.n;
4722 return o.d;
4723}
4724
4725#endif /* C0_IMPLEMENTATION */
4726#endif /* C0_H */
c0_status c0_record_unit_get(c0_record r, const uint8_t *key, size_t klen, c0_unit *out)
The unit under a key with its sub-units (last wins), or C0_ERR_NOT_FOUND.
c0_status c0_record_unit(c0_record r, size_t n, c0_unit *out)
Unit n (0-based) with its sub-units, or C0_ERR_NOT_FOUND.
void c0_builder_gs_str(c0_builder *b, const char *name)
void c0_build_group(c0_builder *b, const uint8_t *name, size_t nlen)
GS name.
c0_status c0_value(c0_bytes raw, uint8_t *scratch, c0_bytes *out)
The logical value of a raw unit (as yielded by c0_next_unit, c0_next_pair, c0_record_field …): for a ...
void c0_builder_em(c0_builder *b, const uint8_t *tail, size_t tlen)
EM and the raw tail; nothing may follow.
void c0_builder_soh(c0_builder *b)
SOH alone: before RS, a header row.
int c0_body_bare(c0_body b)
Whether the body is a bare record stream: one unnamed file, at most the unnamed group.
c0_pretty_mode
Definition c0.h:685
@ C0_PRETTY_COMPACT
one element per line, no padding
Definition c0.h:686
@ C0_PRETTY_ALIGNED
table columns aligned
Definition c0.h:687
@ C0_PRETTY_SPACED
aligned, plus a space after each prefix and around ␟
Definition c0.h:688
size_t c0_record_count(c0_record r)
Number of positional units.
void c0_builder_bel_text(c0_builder *b, const uint8_t *text, size_t tlen)
BEL and a note; empty text is C0_ERR_BAD_STATE.
int c0_next_file(c0_file_iter *it, c0_file *out)
c0_bytes c0_trim(c0_bytes raw)
Layout trimmed from both ends of a raw slice.
void c0_build_field(c0_builder *b, const uint8_t *value, size_t vlen)
next unit of the open record (opens one if none)
c0_bytes c0_builder_bytes(const c0_builder *b)
char * c0_pretty_format(const uint8_t *buf, size_t len, const char *indent, c0_pretty_mode mode, size_t *outlen, c0_error *err)
Format compact bytes as pretty form: a malloc'd, NUL-terminated UTF-8 string the caller frees; *outle...
c0_status c0_container_tail(const uint8_t *buf, size_t len, c0_bytes *tail, int *has_em, c0_error *err)
Scan the whole container: *tail gets the raw region after EM (empty when there is none,...
void c0_build_key_level_open_str(c0_builder *b, const char *key)
#define C0_WARN_NO_SYN
Loud warnings a document reader raises (DESIGN.md "Warnings"), as bits.
Definition c0.h:98
c0_status c0_validate(const uint8_t *buf, size_t len, c0_error *err)
Check a whole buffer (one or more documents, an optional EM tail) against GRAMMAR....
c0_status c0_heading_get_str(const c0_document *d, const char *key, c0_bytes *raw)
#define C0_BEL
Comment: a note, or marks the next element dead.
Definition c0.h:47
int c0_next_unit_with_subs(c0_unit_iter *it, c0_unit *out)
The next positional unit with its sub-units (the walk of c0_next_unit).
void c0_build_ref(c0_builder *b, const uint8_t *name, size_t nlen)
ENQ name as the next unit: a group reference.
void c0_build_record(c0_builder *b, const c0_bytes *fields, size_t count)
RS and count units; count 0 opens an empty record.
void c0_builder_enq_str(c0_builder *b, const char *name)
void c0_builder_gs_name(c0_builder *b, const uint8_t *name, size_t nlen)
GS name; ends any open record.
void c0_builder_init(c0_builder *b)
#define C0_CR
Definition c0.h:62
size_t c0_decode_text(const uint8_t *inside, size_t len, uint8_t *out)
Decode the inside of a text (the bytes between STX and ETX): DLE escapes removed.
#define C0_GS
Group separator.
Definition c0.h:55
c0_status c0_record_get_str(c0_record r, const char *key, c0_bytes *raw)
c0_group_iter c0_file_groups(c0_file f)
Groups of one file.
void c0_build_field_str(c0_builder *b, const char *value)
void c0_build_etb(c0_builder *b, const uint8_t *payload, size_t plen)
ETB and an optional plain payload (NULL for none).
c0_body c0_body_view(const uint8_t *buf, size_t len)
A body over a whole buffer (a slice with no SYN: records, groups, files), unchecked: pair it with c0_...
size_t c0_scan_text(const uint8_t *buf, size_t pos, size_t stop, c0_error *err)
At an STX: the position after the matching ETX.
void c0_build_ref_record(c0_builder *b, const uint8_t *group, size_t glen, const uint8_t *record, size_t rlen, const uint8_t *field, size_t flen)
␅␐␝group␞record[␟field]␘ as the next unit (field NULL to omit)
int c0_ref_group(const c0_ref *r, c0_bytes *name)
Whether the reference names a group as a whole (a plain name, or a pattern that is a bare group line)...
c0_status c0_blob(const uint8_t *buf, size_t len, const uint8_t *name, size_t nlen, c0_bytes *out, c0_error *err)
The bytes of a named blob from the tail, located by the first document's blob table (columns matched ...
int c0_canonical(const uint8_t *buf, size_t len)
Whether bytes are a canonical span (GRAMMAR.md "Canonical constraints"): well-formed,...
c0_record_iter c0_body_records(c0_body b)
Records of a bare body (the unnamed group's).
#define C0_WARN_DUPLICATE_KEY
a duplicate heading key (last wins)
Definition c0.h:101
int c0_next_group(c0_group_iter *it, c0_group *out)
void c0_build_header(c0_builder *b, const c0_bytes *names, size_t count)
SOH RS name US name …
void c0_build_syn(c0_builder *b)
SYN; keyed units until the next element are the heading.
void c0_build_section_str(c0_builder *b, const char *name, size_t depth)
int c0_is_name(const uint8_t *p, size_t len)
Whether bytes are a legal name (label, key, header name): same test as plain.
c0_sub_iter c0_unit_subs(c0_unit u)
void c0_build_key_level_open(c0_builder *b, const uint8_t *key, size_t klen)
SOH key US DLE.
void c0_build_list_str(c0_builder *b, const char *const *items, size_t count)
void c0_build_record_str(c0_builder *b, const char *const *fields, size_t count)
void c0_build_key(c0_builder *b, const uint8_t *key, size_t klen, const uint8_t *value, size_t vlen)
SOH key US value, in the open record or the heading.
size_t c0_scan_comment(const uint8_t *buf, size_t pos, size_t stop, c0_error *err)
At a BEL: past the note, or past the whole dead element's own line.
c0_record_iter c0_group_records(c0_group g)
c0_stream c0_stream_read(const uint8_t *buf, size_t len)
#define C0_LF
Definition c0.h:61
#define C0_ENQ
Reference: a group name, or a pattern (ENQ DLE … CAN).
Definition c0.h:46
c0_status c0_heading_blob(const c0_document *d, c0_body *out)
The blob table (a level) as a body, or C0_ERR_NOT_FOUND / C0_ERR_NOT_LEVEL.
#define C0_EOT
End of document.
Definition c0.h:45
#define C0_FS
File separator.
Definition c0.h:54
size_t c0_unit_sub_count(c0_unit u)
Number of direct sub-units.
void c0_builder_us_str(c0_builder *b, const char *value)
c0_status c0_body_read(const uint8_t *buf, size_t len, c0_body *out, c0_error *err)
Parse a slice as a body (no SYN, heading or EOT): the grammar is applied to all of it; C0_OK and *out...
c0_status c0_builder_status(const c0_builder *b)
uint8_t * c0_pretty_parse(const char *str, size_t len, size_t *outlen)
Parse pretty form back to compact bytes: glyphs become codes; outside text whitespace touching a glyp...
c0_pair_iter c0_record_pairs(c0_record r)
Keyed units in written order, duplicates included, dead units skipped.
void c0_builder_soh_str(c0_builder *b, const char *name)
int c0_group_header(c0_group g, c0_record *out)
The group's header row as a record (its units are the header names).
c0_bytes c0_doc_iter_tail(const c0_doc_iter *it)
After the cursor is exhausted: the raw bytes after EM (empty without EM).
#define C0_SOH
Heading: a key for the value after it; SOH RS a header row.
Definition c0.h:42
void c0_build_map_str(c0_builder *b, const char *const *keys, const char *const *values, size_t count)
#define C0_WARN_NO_EOT
no EOT and the shape is not stream
Definition c0.h:99
void c0_build_em(c0_builder *b, const uint8_t *tail, size_t tlen)
EM and the raw tail; nothing may follow.
void c0_builder_rs_value(c0_builder *b, const uint8_t *value, size_t vlen)
RS and the record's first value.
void c0_builder_rs(c0_builder *b)
RS: open a record.
int c0_next_record(c0_record_iter *it, c0_record *out)
#define C0_ETX
End of text.
Definition c0.h:44
void c0_builder_fs_str(c0_builder *b, const char *name)
c0_status c0_record_field(c0_record r, size_t n, c0_bytes *raw)
Raw unit n (0-based), or C0_ERR_NOT_FOUND.
void c0_builder_enq(c0_builder *b, const uint8_t *name, size_t nlen)
ENQ name: a group reference.
int c0_next_document(c0_doc_iter *it, c0_document *out)
c0_unit_kind
What a raw unit holds, by its first non-layout byte.
Definition c0.h:165
@ C0_UNIT_REF
ENQ name, or ENQ DLE … CAN (a pattern).
Definition c0.h:169
@ C0_UNIT_TEXT
STX … ETX.
Definition c0.h:167
@ C0_UNIT_LEVEL
DLE … CAN.
Definition c0.h:168
@ C0_UNIT_PLAIN
a plain value, the empty value, or a unit holding only a note
Definition c0.h:166
void c0_builder_rs_str(c0_builder *b, const char *value)
#define C0_CAN
Close a nested level.
Definition c0.h:51
void c0_build_note(c0_builder *b, const uint8_t *text, size_t tlen)
BEL and the note (plain, or text when it must be).
void c0_builder_dle(c0_builder *b)
DLE: open a level (saves the record state).
c0_status c0_blob_str(const uint8_t *buf, size_t len, const char *name, c0_bytes *out, c0_error *err)
c0_bytes c0_bytes_of(const uint8_t *ptr, size_t len)
A view over len bytes at ptr.
c0_bytes c0_heading_shape(const c0_document *d)
The shape value (decoded, must be plain), or an empty slice when absent.
#define C0_SP
Definition c0.h:63
c0_bytes c0_file_name(c0_file f)
void c0_builder_etb_str(c0_builder *b, const char *payload)
void c0_build_item(c0_builder *b, const uint8_t *text, size_t tlen)
a list item: the next unit
c0_bytes c0_stream_committed(const c0_stream *s)
size_t c0_ref_path(const c0_ref *r, c0_bytes *steps, size_t max)
The steps of a reference in walking order: the group name alone, or the pattern's file,...
int c0_next_block(c0_block_iter *it, c0_bytes *out, int *damaged)
int c0_is_plain(const uint8_t *p, size_t len)
Whether a value can be written plain: no byte below 0x20, no edge whitespace.
int c0_is_text_escaped(uint8_t byte)
Whether a byte is one of the seven codes that take a DLE inside text (STX ETX DLE ETB EOT SYN EM).
int c0_next_pair(c0_pair_iter *it, c0_bytes *key, c0_bytes *raw)
c0_status
Status codes shared by every part of the library.
Definition c0.h:72
@ C0_ERR_NOT_LEVEL
c0_unit_level on a unit that is not DLE … CAN
Definition c0.h:79
@ C0_ERR_TOO_DEEP
nesting deeper than the parser's limit
Definition c0.h:77
@ C0_ERR_NOT_REFERENCE
c0_unit_ref on a unit that is not ENQ …
Definition c0.h:81
@ C0_ERR_NOT_SCALAR
c0_value on a level or reference
Definition c0.h:78
@ C0_ERR_UNASSIGNED
an unassigned control code outside text
Definition c0.h:75
@ C0_ERR_NOT_LIST
c0_unit_list on a level that is not a list
Definition c0.h:80
@ C0_ERR_SYNTAX
malformed input (see c0_error.msg / .pos)
Definition c0.h:74
@ C0_ERR_BAD_NAME
builder: a name with a control byte or edge space
Definition c0.h:84
@ C0_OK
Definition c0.h:73
@ C0_ERR_BAD_STATE
builder: e.g.
Definition c0.h:85
@ C0_ERR_UNEXPECTED_END
input ended inside text, a level, or after DLE/BEL
Definition c0.h:76
@ C0_ERR_NOT_FOUND
no such group / key / field / blob
Definition c0.h:83
@ C0_ERR_OOM
allocation failed
Definition c0.h:86
@ C0_ERR_NEEDS_DECODE
c0_value without scratch on text with escapes
Definition c0.h:82
void c0_build_level_close(c0_builder *b)
CAN.
void c0_build_block_str(c0_builder *b, const char *text)
size_t c0_scan_level(const uint8_t *buf, size_t pos, size_t stop, c0_error *err)
At a DLE: the position after the matching CAN.
c0_status c0_document_read(const uint8_t *buf, size_t len, size_t start, c0_document *out, c0_error *err)
Read the document starting at start (after any layout), applying the whole grammar to it: C0_OK,...
void c0_build_sub_unit(c0_builder *b, const uint8_t *value, size_t vlen, size_t depth)
SUB×depth US value: a sub-unit of the unit just written (depth 2: of the sub-unit before); not a unit...
void c0_build_map(c0_builder *b, const c0_bytes *keys, const c0_bytes *values, size_t count)
RS and keyed units in the order given.
c0_bytes c0_stream_tail(const c0_stream *s)
c0_bytes c0_group_name(c0_group g)
size_t c0_scan_plain(const uint8_t *buf, size_t pos, size_t stop)
Skip a run of bytes >= 0x20 (a label, key, payload or plain value with its layout).
void c0_builder_bel_str(c0_builder *b, const char *text)
c0_status c0_record_unit_get_str(c0_record r, const char *key, c0_unit *out)
void c0_builder_soh_name(c0_builder *b, const uint8_t *name, size_t nlen)
SOH key.
int c0_next_unit(c0_unit_iter *it, c0_bytes *raw)
size_t c0_stream_last_commit_end(const uint8_t *buf, size_t len)
Position just past the last commit, found by a backward scan (a shortcut for well-formed input; c0_st...
size_t c0_scan_record_end(const uint8_t *buf, size_t pos, size_t stop, c0_error *err)
From just after an RS: the end of the record (a sub-unit, a SUB run then US, stays inside; a SUB run ...
#define C0_RS
Record separator.
Definition c0.h:56
#define C0_EM
End of medium: a raw blob follows.
Definition c0.h:52
size_t c0_stream_before_damage(const c0_stream *s, uint8_t *out)
The same, stopping at the first damaged block: the default reading, which delivers the records before...
void c0_builder_us_value(c0_builder *b, const uint8_t *value, size_t vlen)
US and the value that follows it.
#define C0_US
Unit separator.
Definition c0.h:57
void c0_builder_sub(c0_builder *b)
SUB: the element after the next separator is subordinate to the one before (before GS depth,...
void c0_build_group_str(c0_builder *b, const char *name)
void c0_build_note_str(c0_builder *b, const char *text)
c0_status c0_group_column(c0_group g, const uint8_t *name, size_t nlen, size_t *index)
Index of a header name in the group's header row, or C0_ERR_NOT_FOUND.
c0_status c0_body_find_group_str(c0_body b, const char *name, c0_group *out)
c0_file_iter c0_body_files(c0_body b)
void c0_build_header_str(c0_builder *b, const char *const *names, size_t count)
void c0_builder_etb(c0_builder *b)
ETB alone.
void c0_builder_gs(c0_builder *b)
GS alone: an empty-named group (␝␝b is group "" then group b).
void c0_build_ref_open(c0_builder *b)
ENQ DLE as the next unit: a pattern; write its lines, then c0_build_level_close.
void c0_builder_em_str(c0_builder *b, const char *tail)
void c0_builder_etb_payload(c0_builder *b, const uint8_t *payload, size_t plen)
ETB and a plain payload.
c0_unit_iter c0_record_units(c0_record r)
The record's positional units.
void c0_build_block(c0_builder *b, const uint8_t *text, size_t tlen)
a paragraph: a record of one unit
#define C0_WARN_UNKNOWN_SHAPE
a shape other than diff or stream
Definition c0.h:102
void c0_builder_can(c0_builder *b)
CAN: close the innermost level; C0_ERR_BAD_STATE if none is open.
void c0_build_key_str(c0_builder *b, const char *key, const char *value)
int c0_record_keyed(c0_record r)
Whether the record is keyed (it holds a keyed unit, live or dead).
int c0_is_layout(uint8_t byte)
Whether a byte is layout outside text (SP, HT, LF, CR).
#define C0_HT
Definition c0.h:60
void c0_build_sub_unit_str(c0_builder *b, const char *value, size_t depth)
void c0_build_file_str(c0_builder *b, const char *name)
size_t c0_stream_undamaged(const c0_stream *s, uint8_t *out)
Copy the undamaged committed blocks, without their ETB markers and payloads, into out (room for commi...
void c0_build_etb_str(c0_builder *b, const char *payload)
c0_pair_iter c0_document_heading(const c0_document *d)
The heading's keyed units, in written order (dead units skipped).
c0_group_iter c0_body_groups(c0_body b)
Groups of every file of a body, in order (FS lines are skipped).
void c0_build_level_open(c0_builder *b)
DLE: a nested level as the next unit; inside, the builder is at the top of a fresh body.
void c0_builder_bel(c0_builder *b)
BEL alone: the element that follows is dead.
#define C0_WARN_UNKNOWN_VERSION
a version other than 1
Definition c0.h:103
c0_status c0_unit_ref(c0_bytes raw, c0_ref *out)
A raw unit as a reference.
void c0_builder_us(c0_builder *b)
US alone (an empty unit, or before DLE / ENQ).
#define C0_STX
Start of text (a literal value).
Definition c0.h:43
void c0_builder_syn(c0_builder *b)
SYN; soh_name + us_value pairs that follow are the heading.
c0_status c0_unit_list(c0_bytes raw, c0_unit_iter *items)
A raw unit as a flat list: a level holding at most one positional record.
int c0_next_pair_with_subs(c0_pair_iter *it, c0_bytes *key, c0_unit *out)
The same, the value as a unit with its sub-units.
#define C0_DLE
Recurse (opens a nested level) outside text; escape inside.
Definition c0.h:48
#define C0_WARN_UNKNOWN_KEY
a heading key the reader does not know
Definition c0.h:100
void c0_build_eot(c0_builder *b)
EOT.
int c0_heading_version(const c0_document *d)
The version value as an integer; 1 when absent or not a number.
c0_block_iter c0_stream_blocks(const c0_stream *s)
size_t c0_scan_layout(const uint8_t *buf, size_t pos, size_t stop)
Skip layout bytes.
#define C0_ETB
Commit marker (stream mode).
Definition c0.h:50
void c0_builder_fs(c0_builder *b, const uint8_t *name, size_t nlen)
FS name; ends any open record.
void c0_build_item_str(c0_builder *b, const char *text)
size_t c0_scan_unit(const uint8_t *buf, size_t pos, size_t stop, c0_error *err)
From just after a US (or a key's US): the end of the unit's value (its sub-units, SUB … US …,...
void c0_builder_free(c0_builder *b)
c0_status c0_record_get(c0_record r, const uint8_t *key, size_t klen, c0_bytes *raw)
Raw value for a key (last wins), or C0_ERR_NOT_FOUND.
c0_unit_kind c0_unit_type(c0_bytes raw)
void c0_builder_eot(c0_builder *b)
EOT.
int c0_next_sub(c0_sub_iter *it, c0_unit *out)
void c0_build_ref_record_str(c0_builder *b, const char *group, const char *record, const char *field)
void c0_build_section(c0_builder *b, const uint8_t *name, size_t nlen, size_t depth)
SUB×(depth−1) GS name: a group at depth (1 is a plain GS line).
c0_status c0_unit_level(c0_bytes raw, c0_body *out)
A raw unit as a nested level: the body between its DLE and CAN.
void c0_builder_enq_dle(c0_builder *b)
ENQ DLE: a pattern; write its lines, then c0_builder_can.
c0_status c0_body_find_group(c0_body b, const uint8_t *name, size_t nlen, c0_group *out)
First group with the given name in the body (any file), or C0_ERR_NOT_FOUND.
#define C0_SYN
Start of document, then the heading.
Definition c0.h:49
void c0_build_file(c0_builder *b, const uint8_t *name, size_t nlen)
FS name.
c0_status c0_heading_get(const c0_document *d, const uint8_t *key, size_t klen, c0_bytes *raw)
Raw heading value for a key (last wins), or C0_ERR_NOT_FOUND.
void c0_build_ref_str(c0_builder *b, const char *name)
#define C0_SUB
Subordinate: the element after is a child of the element before (GS: subsection, US: sub-unit).
Definition c0.h:53
c0_doc_iter c0_documents(const uint8_t *buf, size_t len)
void c0_build_list(c0_builder *b, const c0_bytes *items, size_t count)
a flat list as the next unit: DLE RS item US item … CAN, or DLE CAN
int c0_is_assigned(uint8_t byte)
Whether a byte is one of the sixteen assigned codes.
Cursor over the committed blocks (previous commit to ETB, marker and payload excluded); *damaged is s...
Definition c0.h:655
int in_text
Definition c0.h:660
size_t index
Definition c0.h:661
size_t pos
Definition c0.h:658
c0_parse_state st
Definition c0.h:662
const uint8_t * buf
Definition c0.h:656
size_t stop
Definition c0.h:657
size_t block_start
Definition c0.h:659
A body: a document body or the inside of a nested level, as a range of the buffer.
Definition c0.h:188
size_t stop
Definition c0.h:191
const uint8_t * buf
Definition c0.h:189
size_t start
Definition c0.h:190
Writes C0DATA in canonical compact form into a growable buffer it owns; call c0_builder_free when don...
Definition c0.h:508
size_t stack_cap
internal
Definition c0.h:517
size_t depth
internal: open levels
Definition c0.h:516
int * stack
internal: saved state per open level
Definition c0.h:515
size_t units
internal: units written in the open record
Definition c0.h:514
size_t len
Definition c0.h:510
uint8_t * data
Definition c0.h:509
int state
internal: top / heading / record
Definition c0.h:513
c0_status status
Definition c0.h:512
size_t cap
Definition c0.h:511
A zero-copy view into a buffer: not NUL-terminated.
Definition c0.h:66
const uint8_t * ptr
Definition c0.h:67
size_t len
Definition c0.h:68
Cursor over the documents of a container (a file or message): each begins with SYN except possibly th...
Definition c0.h:450
const uint8_t * buf
Definition c0.h:451
size_t em_pos
Definition c0.h:455
c0_error err
Definition c0.h:457
size_t pos
Definition c0.h:453
int done
Definition c0.h:456
size_t len
Definition c0.h:452
int has_em
Definition c0.h:454
One document: an optional SYN heading, a body, an optional EOT.
Definition c0.h:419
c0_body body
Definition c0.h:427
size_t stop
after the EOT, or where the document ends
Definition c0.h:422
size_t start
Definition c0.h:421
const uint8_t * buf
Definition c0.h:420
size_t dead_elements
dead records, header rows, groups and files met in the body
Definition c0.h:429
size_t heading_start
the keyed units after SYN …
Definition c0.h:425
int has_syn
Definition c0.h:423
size_t heading_end
… up to the first body code
Definition c0.h:426
int has_eot
Definition c0.h:424
unsigned warnings
C0_WARN_* bits.
Definition c0.h:428
Error detail: the code, the byte offset it was found at, and a static message.
Definition c0.h:91
const char * msg
Definition c0.h:94
size_t pos
Definition c0.h:93
c0_status code
Definition c0.h:92
Cursor over the files of a body as the result model has them.
Definition c0.h:355
size_t stop
Definition c0.h:358
int done
Definition c0.h:360
size_t pos
Definition c0.h:357
c0_error err
Definition c0.h:361
int first
Definition c0.h:359
const uint8_t * buf
Definition c0.h:356
A file within a body: its name and the range of its contents.
Definition c0.h:326
const uint8_t * buf
Definition c0.h:327
size_t start
Definition c0.h:330
size_t name_end
Definition c0.h:329
size_t name_start
Definition c0.h:328
int leading
Definition c0.h:332
size_t stop
Definition c0.h:331
Cursor over groups: every GS line at any depth, in order, plus the unnamed leading group of a file or...
Definition c0.h:371
size_t pos
Definition c0.h:373
int first
Definition c0.h:375
size_t stop
Definition c0.h:374
int done
Definition c0.h:376
c0_error err
Definition c0.h:377
const uint8_t * buf
Definition c0.h:372
A group: its depth (one plus the SUB prefix of its GS line: ␝a 1, ␚␝b 2; 0 for the unnamed group at t...
Definition c0.h:339
size_t stop
Definition c0.h:345
size_t name_end
Definition c0.h:343
size_t name_start
Definition c0.h:342
size_t depth
Definition c0.h:341
const uint8_t * buf
Definition c0.h:340
size_t start
Definition c0.h:344
Cursor over keyed units (a keyed record, or a document heading).
Definition c0.h:296
c0_error err
Definition c0.h:300
size_t stop
Definition c0.h:299
size_t pos
Definition c0.h:298
const uint8_t * buf
Definition c0.h:297
Parser state carried from one committed block to the next (every field is internal).
Definition c0.h:618
int phase
Definition c0.h:619
size_t nfiles
Definition c0.h:628
int header_ok
Definition c0.h:626
int first
Definition c0.h:620
int leading
Definition c0.h:622
int dead_file
Definition c0.h:623
int dead_depth
Definition c0.h:624
int in_level
Definition c0.h:621
int file_has_groups
Definition c0.h:627
int prev_depth
Definition c0.h:625
Cursor over the live records of a group (header rows, notes, commits and dead records skipped).
Definition c0.h:400
c0_error err
Definition c0.h:405
size_t stop
Definition c0.h:403
int done
Definition c0.h:404
size_t pos
Definition c0.h:402
const uint8_t * buf
Definition c0.h:401
A record: the bytes after its RS, trailing layout excluded.
Definition c0.h:232
const uint8_t * buf
Definition c0.h:233
size_t stop
Definition c0.h:235
size_t start
Definition c0.h:234
A parsed reference (DESIGN.md "References"): a group name written plain, or a pattern,...
Definition c0.h:208
c0_bytes name
the group name of a plain reference (empty for a pattern)
Definition c0.h:209
c0_body pattern
the pattern's body (the inside of its level) when is_pattern
Definition c0.h:210
int is_pattern
Definition c0.h:211
A scan of an append-only log.
Definition c0.h:636
size_t len
Definition c0.h:638
int torn
Definition c0.h:640
size_t first_damaged
index of the first damaged block
Definition c0.h:644
const uint8_t * buf
Definition c0.h:637
size_t damaged_count
Definition c0.h:642
size_t resume_offset
the offset after that block's ETB and payload, where reading can go on
Definition c0.h:645
size_t committed_end
just past the last ETB and its payload
Definition c0.h:639
size_t block_count
Definition c0.h:641
int has_damaged
whether any block is damaged
Definition c0.h:643
Cursor over the direct sub-units of a unit (those one deeper than it), in written order; each comes w...
Definition c0.h:277
size_t depth
the parent's depth
Definition c0.h:281
c0_error err
Definition c0.h:282
size_t stop
Definition c0.h:280
const uint8_t * buf
Definition c0.h:278
size_t pos
Definition c0.h:279
Cursor over the positional units of a record, or the items of a list.
Definition c0.h:242
c0_error err
Definition c0.h:247
const uint8_t * buf
Definition c0.h:243
size_t stop
Definition c0.h:245
int done
Definition c0.h:246
size_t pos
Definition c0.h:244
A unit with its sub-units (DESIGN.md "Subordinates"): SUB before US makes the unit after a child of t...
Definition c0.h:262
c0_bytes raw
the value with its layout: pass to c0_value / c0_unit_level / c0_unit_ref
Definition c0.h:263
const uint8_t * buf
Definition c0.h:264
size_t subs_start
its sub-units: [subs_start, subs_end), SUB runs each followed by US and a value
Definition c0.h:265
size_t depth
0 for a unit of a record; a sub-unit's depth is the length of its SUB run
Definition c0.h:267
size_t subs_end
Definition c0.h:266