c0data 1.0.0

C0DATA — structured data using ASCII C0 control codes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
---
title: C0DATA Technical Reference
---

# C0DATA Technical Reference

## Format Overview

C0DATA uses ASCII C0 control codes (0x00--0x1F) as structural delimiters
with UTF-8 text values. It sits between human-readable text formats (JSON,
YAML, TOML) and opaque binary formats (protobuf, msgpack). Values are plain
text. Structure is expressed through single-byte control codes.

See [DESIGN.md](DESIGN.md) for the
full specification and future directions.

### Assigned Control Codes

| Byte | Abbr | Glyph | Role |
|------|------|-------|------|
| 0x01 | SOH | ␁ | Heading: a key for the value after it, or `␁␞` a header row |
| 0x02 | STX | ␂ | Start of text (literal value) |
| 0x03 | ETX | ␃ | End of text |
| 0x04 | EOT | ␄ | End of document |
| 0x05 | ENQ | ␅ | Reference (look up named data) |
| 0x07 | BEL | ␇ | Comment: a note, or marks the next element dead |
| 0x10 | DLE | ␐ | Recurse: open a nested level (outside text); escape (inside text) |
| 0x16 | SYN | ␖ | Start of document, then the heading |
| 0x17 | ETB | ␗ | Commit marker (stream mode) |
| 0x18 | CAN | ␘ | Close a nested level |
| 0x19 | EM  | ␙ | End of medium: raw blob follows |
| 0x1A | SUB | ␚ | Subordinate: the element after is a child of the element before (GS: subsection, US: sub-unit) |
| 0x1C | FS  | ␜ | File separator |
| 0x1D | GS  | ␝ | Group / Table / Section separator |
| 0x1E | RS  | ␞ | Record / Row separator |
| 0x1F | US  | ␟ | Unit / Field separator |

Sixteen codes. HT, LF and CR are layout outside text. Every other C0
code is unassigned and a parser rejects it outside text. Inside text
every code is a plain byte except seven (see Text).

### Structural Hierarchy

The four separator codes form a fixed hierarchy:

```
FS  >  GS  >  RS  >  US
file   group  record  field
```

- **FS (0x1C)** -- Top-level container. A database, a file, a document.
- **GS (0x1D)** -- A group within a file. A table, a collection, a section.
- **RS (0x1E)** -- A record within a group. A row, an entry, a block.
- **US (0x1F)** -- A unit within a record. A field, a property, an element.

Text immediately following FS or GS is the **label** (name) for that scope.
Every code owns the text after it, up to the next code. A document may hold
several FS files.

### Documents

A document starts with SYN and ends with EOT. The text after SYN is the
**heading**, keyed units the reader must know before reading. An empty
heading is just `␖`.

```
␖␜mydb␝users␁␞name␟amount␞Alice␟100␄          empty heading
␖␁shape␟stream␞alice␟100␗␞bob␟200␗             a log (no EOT: logs have no end)
␖␁shape␟diff␜foo.txt␞␂Hello ␃␟world␚␟universe␟!␄  a C0DIFF
```

Heading keys: `shape` (`diff`, `stream`; absent means the application
decides), `version` (absent means 1), `blob` (see Trailing Blob),
`schema` (the schema the body claims to conform to: a plain name, or a
level holding one keyed record of `name`, `url` and `hash`, any subset,
`␁schema␟␐␞␁url␟https://example.org/ledger/1␁hash␟sha256:9f86…␘`; the
hash is of the schema's canonical body; the format checks the form, a
schema layer refuses on mismatch). An
unknown key is a loud warning. SYN is required at the start of every file
and message; EOT at the end of every document except a log. A missing one
is a loud warning; strict mode makes loud warnings errors.


---

## Two Forms: Compact and Pretty

C0DATA has two representations of the same data under one grammar: pretty
form is compact form plus layout plus glyphs.

**Whitespace touching a control code is layout; whitespace inside text is
data.** Outside text, in both forms:

- space, HT, LF, CR directly before or after a control code, or at the
  start or end of input, are layout;
- a space elsewhere in a plain value is data ("Alice Smith" keeps its space);
- HT, LF or CR elsewhere in a plain value is an error: use text.

### Compact Form (Canonical)

The wire/storage format: a continuous byte stream with no layout.

```
␖␜mydb␝users␁␞name␟amount␞Alice Smith␟1502.30␞Bob␟340.00␄
```

A document is bytes, not a string. Carry it and parse it as bytes: some
string routines treat FS, GS and RS as line breaks (Python's
`str.splitlines()`, following Unicode's paragraph-separator class), so
decoding a document to a string and splitting it into lines can cut it
at record boundaries.

### Pretty Form (Human-Readable)

Unicode Control Pictures (U+2400 block) for the codes, line breaks and
indentation for layout:

```
␖␜mydb
  ␝users
    ␁␞name␟amount
    ␞Alice Smith␟1502.30
    ␞Bob␟340.00
␄
```

A value with edge spaces, a tab, or a line break is text, in both forms:

```
␞␂  leading spaces  ␃␟normal value
␞note␟␂line one
line two␃
```


---

## Data Shapes

C0DATA is a system, not a single format. The same control code vocabulary
expresses multiple common data shapes.

| Shape      | Primary Codes Used          | Analogous To         |
|------------|-----------------------------|----------------------|
| Tabular    | FS, GS, SOH RS, RS, US     | CSV, SQL results     |
| Document   | FS, SUB GS, RS, US         | Markdown, outlines   |
| Key-Value  | GS, RS, SOH                | TOML, INI            |
| Nested     | DLE … CAN, any inner codes | JSON objects, arrays |
| Text       | STX/ETX                    | quoted strings       |
| Reference  | ENQ, a level pattern for paths | foreign keys, links  |
| Diff       | FS, RS, US, SUB            | unified diff, patches|
| Stream     | RS, US, ETB                | NDJSON, SSE, WAL     |
| Container  | SYN heading, EM            | tar, zip             |

### Tabular (header row present)

`␁␞` as the first item of a group is a header row: it declares field
names, and the positional records after it are read against them, like a
CSV header.

```
␝users
  ␁␞name␟amount
  ␞Alice␟100
  ␞Bob␟200
```

Without a header row, data is purely positional (schema known by both
sides). By convention the first field is the record's id.

### Keyed records (maps)

SOH inside a record introduces a keyed unit: `␁key␟value`. A record is
positional or keyed, never mixed: keyed when it holds at least one keyed
unit, live or dead, positional otherwise (`␞␇n`, a note alone, is one
empty unit). Keys are unique in canonical form and
stay in the order written; sorting is the producer's choice.

```
␝database
  ␞␁host␟localhost␁port␟5432
```

Two-field positional records, `␞host␟localhost`, remain legal and are a
table of pairs.

### Multi-field records (no header, N fields)

```
␝data
  ␞a␟b␟c
  ␞d␟e␟f
```

### Text (STX/ETX)

A value with edge whitespace, a line break, a tab, or any control code is
written as text. Inside text every byte is data except seven, which take
a DLE in front: STX, ETX, DLE, ETB, EOT, SYN, EM. Text does not nest.

```
␞Alice␟␂  padded  ␃
␞script␟␂#!/bin/sh
echo "a	b"␃
```

### Nested values (DLE … CAN)

When a field value is itself structured, open a nested level with DLE and
close it with CAN. DLE means *recurse*: the code after it is the first code
of a nested body, in which the hierarchy starts over. Levels nest for
arbitrary depth. A list is one record; a table is several; a map is a keyed
record; a level may even hold groups and files.

```
␝users
  ␁␞name␟roles␟address
  ␞Alice␟␐␞Admin␟Editor␘␟␐␁␞street␟city␞123 Main␟Springfield␘
```

`␐␘` is an empty level; `␐␞␘` is a list holding one empty string. DLE is
on the opener only, and must be followed by a code.

### Document (FS wrapper, depth via SUB GS)

SUB before GS indicates depth (like # in Markdown): `␝` is depth one,
`␚␝` depth two, `␚␚␝` depth three; a depth is never skipped. Within a section,
RS marks a content block (paragraph) and US marks sub-elements (list items).

```
␖␜My Document
  ␝Chapter 1
    ␞First paragraph.
    ␞A list:␟Item one␟Item two
    ␚␝Section 1.1
      ␞Nested content.
  ␝Chapter 2
    ␞And so on.
␄
```

### References (ENQ)

ENQ marks a value as a reference to data defined elsewhere in the document,
before or after the reference. A reference is hashed as written; resolution
is a library lookup against the whole body. In a stream log only committed
blocks can be looked up, so a reference resolves once its target lands.

Simple reference (entire group):

```
␅tags
```

Path reference: a level whose body is the target with its values left out,
written in the document's own codes, so a reader parses it as any level:

```
␅␐␝tags␞001␟label␘
```

Group `tags`, the record whose first field is `001`, its field under the
header name `label`. A file line names the file (`␅␐␜b␝tags␞001␘`), SUB
before GS is depth (`␅␐␝docs␚␝intro␞3␘`), a keyed unit is named with its
value left empty (`␅␐␝server␞␁host␟␘`), and a level in the third unit
continues into the field's level (`␅␐␝tags␞001␟children␟␐␞2␘␘`). Every
name is plain; text, header rows, dead elements and a second branch are
errors. A reference resolves to the nearest matching target before it,
else the first after it, so nothing appended later changes an earlier
reference.

### Comments (BEL)

BEL marks the next thing dead. BEL followed by a value is a note, which ends
at the next control code like any other code's text. BEL followed by a
structural code marks that element dead: a record, header row, keyed
unit or nested level, or a group or file with everything it holds, is
parsed as written and then discarded. A note that must hold control codes
is text, `␇␂…␃`, which is also how a group or file line is commented out
alone, with what follows falling through to the element before.

```
␇ settings for staging
␝server
  ␇␞␁host␟old.example.com
  ␞␁host␟0.0.0.0␁port␟8080␇ was 9090
```

Layout after the BEL is layout, so `␇␊␞x` is a dead record. BEL before
US, ETX, CAN or a framing code is an error.

### Stream logs (ETB)

ETB commits the bytes appended since the previous ETB. A trailing block
without ETB is torn and skipped; writers repair the tail before appending.
An unescaped ETB is always a commit, even inside text, so a torn text cannot
hide later commits. A committed block that is not well-formed, cut by its
ETB inside open text or holding any other error, is damaged: nothing in
it is delivered, it is reported with the offset where reading can resume,
and the library continues past it only when asked.

```
␖␁shape␟stream␁␞op␟id␗
␞create␟a1b2␗
␞name␟draft␗
```

### Trailing Blob (EM)

Everything after EM to the end of the container is one raw region, declared
in the first document's heading under `blob` as a table of name, offset,
length and optional hash. A reader stops at EM; any document may reference
a blob by name.

```
␖␁blob␟␐␁␞name␟offset␟length␟hash␞lamp␟0␟3072000␟sha256:cd34…␘
␜catalogue␝items␁␞name␟photo␞Lamp␟lamp␄
␙…raw bytes…
```


---

## C0DIFF

C0DIFF provides atomic multi-file edits using **anchored patterns**: literal
context text surrounding the parts to change, instead of line numbers. It
is a profile of C0DATA (`shape␟diff`) that parses under the base grammar,
specified in full in [DIFF.md](DIFF.md).

```
␖␁shape␟diff
␜greeting.txt
  ␞␂Hello ␃␟world␚␟universe␟!
␜tally.rb
  ␞def tally(items)
  ␞␂  ␃␟count␚␟total␟␂ = 0␃
  ␞␂  # TODO␃␚␟
␄
```

- `␜path` begins a file. `␞` begins a record, one anchored pattern whose
  US-separated units are anchors or substitutions, `old␚␟new` (a
  sub-unit: `new` is subordinate to `old` and, in a diff, replaces it).
  The pattern must match exactly once after the previous record's match.
- Empty old inserts; empty new deletes; a record with no `␚` asserts.
- Everything the diff does not use (keyed units, levels, references,
  header rows, GS, two sub-units on one unit, dead records or file
  lines) is an error in a diff. There is no replace-all: a tool expands
  one into anchored records against the target.
- The whole diff is validated before anything is written.

---

## Escaping (DLE)

Inside text, DLE (0x10) precedes one of seven codes to make it a data
byte: STX, ETX, DLE, ETB, EOT, SYN, EM. Outside text no control code is
data, and DLE means recurse (see Nested values).

```
␞␂a␐␃b␃        the three bytes a, ETX, b
```


---

## Document Termination (EOT)

EOT (0x04) marks the end of a complete C0DATA document. Required at the end
of every document in a file or message, except a log; a missing EOT is a
loud warning. Several documents in one file or connection each begin with
their own SYN.


---

## Consistent Roles Across Shapes

The separator codes maintain consistent meaning across all data shapes:

| Shape      | RS means          | US means                  |
|------------|-------------------|---------------------------|
| Tabular    | row               | field / column            |
| Document   | paragraph / block | list item / element       |
| Key-Value  | the section's map | key → value (after SOH)   |
| Diff       | --                | anchor ↔ replacement unit |


---

## Data Shape Mapping

How C0DATA maps to and from JSON/YAML/CSV. A positional record is an array,
a keyed record is an object; nothing is guessed.

### Tabular → JSON

```
␝users
  ␁␞name␟amount
  ␞Alice␟100
  ␞Bob␟200
```

```json
{"users": [{"name": "Alice", "amount": "100"}, {"name": "Bob", "amount": "200"}]}
```

```csv
name,amount
Alice,100
Bob,200
```

### Key-Value → JSON

```
␝database
  ␞␁host␟localhost␁port␟5432
```

```json
{"database": {"host": "localhost", "port": "5432"}}
```

### Multi-field → JSON

```
␝data
  ␞a␟b␟c
  ␞d␟e␟f
```

```json
{"data": [["a", "b", "c"], ["d", "e", "f"]]}
```

### Nested → JSON

```
␝users
  ␁␞name␟roles␟address
  ␞Alice␟␐␞Admin␟Editor␘␟␐␞␁street␟123 Main␁city␟Springfield␘
```

```json
{"users": [{"name": "Alice", "roles": ["Admin", "Editor"], "address": {"street": "123 Main", "city": "Springfield"}}]}
```

### Document → JSON

```
␖␜mydb
  ␝users
    ␁␞name
    ␞Alice
  ␝products
    ␁␞id
    ␞01
␄
```

```json
{"mydb": {"users": [{"name": "Alice"}], "products": [{"id": "01"}]}}
```


---

## Performance

The tokenizer's hot loop is a single comparison: `byte < 0x20`. This makes
C0DATA inherently fast to parse -- single-byte delimiters, zero-copy
friendly, and SIMD-acceleratable.

Benchmark on 10 MB document (Crystal, --release):

```
avg         4.88 ms       2048.0 MB/s
best        4.09 ms       2447.7 MB/s
```


---

## c0fmt CLI

Command-line tool for converting and inspecting C0DATA, its own shard at
[c0data/c0-fmt](https://github.com/c0data/c0-fmt) (`shards build
--release`). Every command reads a file or stdin in either form, compact
or pretty.

```
c0fmt import [format] [file]   CSV, JSON or YAML → C0DATA (-g group name)
c0fmt export <format> [file]   C0DATA → csv (-g which group), json, yaml
c0fmt pretty [file]            compact → pretty (-a aligns table columns)
c0fmt compact [file]           pretty → compact
c0fmt validate [file]          well-formedness; -c also canonical form,
                               -s a stream log (torn tail, damaged blocks)
```

Export maps a header row to objects, a keyed record to an object, a nested
level to a list or table, and a reference to `{"$ref": "group/record"}`
(JSON, YAML) or its path (CSV). `validate` prints reader warnings (a
missing SYN heading, an unknown heading key) without failing; `-c` names
each reason a file is not canonical. Exit status is 0 when valid.

## Crystal API

For the Crystal library API documentation, see the generated
[API docs](../api/index.html).

### Installation

Add to your `shard.yml`:

```yaml
dependencies:
  c0:
    github: c0data/c0-cr
```

```crystal
require "c0"
```