c0
A Rust implementation of C0DATA — structured data built on ASCII C0 control codes. Values are UTF-8 text (any bytes, as text); structure is sixteen single-byte codes: FS/GS/RS/US separators, SOH keys and header rows, STX…ETX text, DLE…CAN nesting, ENQ references, BEL comments, SUB subordinates (subsections and sub-units), SYN/EOT document framing, ETB stream commits, EM trailing blobs.
This crate is a zero-copy reader/writer: readers index a buffer once and
hand back slices (&[u8]) into it, decoding text only on demand
(Cow<[u8]>). It has no dependencies.
Status
Implements the 1.0 redesign of the spec, mirroring the Crystal reference
(c0-cr):
- one
Parserfor the grammar (GRAMMAR.md); validator (validate,canonical) on top of it Container/Document/Body/Group/Record/Referencereaders,Builderwriter- stream mode:
StreamReader(commits, damaged blocks, torn tail),StreamWriter,FileLogwith tail repair and fsync - pretty form: compact, aligned and spaced layouts, and the round-tripping
parse - CSV ⇄ C0DATA conversion
- C0DIFF: parse, build, and atomic multi-file apply (anchored patterns with
old␚␟newsubstitutions) - JSON: the
Valuetree andto_value/from_value(dependency-free), withto_json/from_jsontext helpers behind the optionaljsonfeature
It passes every case of the shared conformance vectors from
c0-spec, read from the git submodule at
c0-spec/. After cloning:
Not ported: a YAML converter and a serde-style derive (the Serializable
equivalent).
Features
The library is dependency-free by default. The optional json feature adds
JSON text conversion and pulls in serde_json:
= { = "1.0", = ["json"] } # used in code as `c0`
Usage
use ;
// Build canonical compact bytes: ␝users␁␞name␟amount␞Alice␟1502.30␞Bob␟340.00
let buf = build;
// Read them back, zero-copy
let body = new?;
let users = body.group;
assert_eq!;
assert_eq!;
// The builder's output is canonical — hashable for content addressing
assert!;
Values (record, field, list, key, map) take any AsRef<[u8]> and are
written in their one spelling: plain when they have no byte below 0x20 and no
edge whitespace, otherwise text ␂…␃ with only STX, ETX, DLE, ETB, EOT, SYN
and EM escaped. Names (labels, keys, header names) are identifiers and panic
when they are not.
Keyed records and nesting
let buf = build;
let body = new?;
let server = body.group.record;
assert_eq!;
let origins = server.get_level?.unwrap;
assert_eq!;
A positional unit holding a level is read with Record::level (any body) or
Record::list (a level holding one positional record, written with
Builder::list). A reference is a group name (␅tags) or a pattern,
a level that is one branch of the target with its values left out
(␅␐␝tags␞001␟label␘: group tags, record 001, field label). It is
written with reference(name), reference_to(group, record, field) or
reference_level(|b| …), and read with Record::reference, which gives a
Reference with name() or pattern() (the level as a Body) and
path() to linearise it.
The result model
The readers report the result. A dead element (␇␞…) is parsed and
dropped with everything it holds: ␇␝g takes the group's header row,
records and subsections, ␇␜f the file's groups. ␚ (SUB) before a
separator makes the element after it a child of the element before,
at that code's grain: ␚␝s is a subsection at depth two (␚␚␝t depth
three; a depth is never skipped, and ␝␝b is an empty-named group then
b), and ␞a␟b␚␟c is two units, a and b, with c a sub-unit of b
that is not a unit of the record: values() reads ["a", "b"],
Record::unit(n) and Record::get_unit(key) give a unit with its
subs(), nested (␞a␚␟b␚␚␟c). ␚␞, ␚␜ and ␚␁ are reserved and
refused. The prefix is structure: canonical form keeps it and hashes it as
written. Malformed input fails at construction (Body::new,
Document::new, Container::new return Err); canonical checking is
separate and never fails construction.
Primitives
Underneath, the builder has one method per code: fs, gs, rs, us,
sub, soh, dle, can, bel, enq, syn, eot, etb, em. Each writes
its code and, when given, what follows it, so a chain reads like the bytes,
and anything the grammar allows can be written. Rust has no optional
arguments, so a code that may stand bare has two spellings: the bare code
(rs(), us(), gs(), soh(), bel(), etb()) and the code with what
follows it (rs_value, us_value, gs_name, soh_key, bel_note,
etb_payload); sub is always bare; a reference is enq(name) or
enq_level(|b| …), the pattern built inside.
let buf = build;
The composed methods above are built on these and cannot write ill-formed
output; with the primitives, well-formedness is yours. The two layers
share the record state and mix freely: rs_value("a") then field("b")
writes ␞a␟b, and gs_name("g") then key("k", "v") writes ␝g␞␁k␟v.
Documents
let buf = build;
let doc = new?;
assert_eq!;
assert!; // a missing SYN or EOT warns, never fails
Heading keys are shape (diff or stream), schema (a name, or a level
holding one keyed record of name, url, hash), version and blob;
anything else, an unknown shape, or a duplicate key (last wins) is a loud
warning. Container::new reads a buffer of several documents and the raw
region after EM (blob_bytes(name) looks a blob up through the first
heading's blob table). validate rejects malformed bytes; canonical
tells whether bytes are a canonical span.
Stream logs (ETB commits)
use ;
let mut log = open_log?; // truncates a torn tail first
log.start?; // ␖␁shape␟stream␗
log.record?;
log.batch?;
let bytes = read_log?;
let r = new;
assert!; // an uncommitted tail is skipped
let doc = r.document?; // the committed region
A committed block that is not well-formed, cut by its ETB inside open text
or holding any other error, is damaged and delivers nothing. By default
the reader yields the records before it (each_record) and then fails with
Error::DamagedBlock { index, resume_offset }, the offset after the
block's ETB and payload; StreamReader::continuing(&bytes) reads on past
it, which is what r.damaged() lists. A SYN inside the stream tears the
uncommitted bytes before it: they are no block and deliver nothing
(r.torn_regions() gives their [start, end) ranges), and the new
document's blocks are read as usual.
C0DIFF
A diff is a document of shape diff whose records are anchored patterns;
old␚␟new inside one (the sub-unit of old) is the substitution (DIFF.md
in the spec):
␖␁shape␟diff
␜greeting.txt
␞␂Hello ␃␟world␚␟universe␟!
␄
let diff = build;
let out = apply?; // validates everything first
apply_files?; // atomic on disk
Each record's search text must match once from the previous match to the
end of the file. There is no replace-all mark: a tool expands one into
anchored records against the target. Anything the text diff does not use
(keyed units, levels, references, header rows, GS, dead records or file
lines, two sub-units on one unit, a sub-unit of a sub-unit) is refused
with DiffError::Refused; a hunk is kept without applying by writing it
in a note (␇␂␞…␃).
Pretty form
format/format_mode render compact bytes with Control Picture glyphs,
line breaks and indentation (FormatMode::{Compact, Aligned, Spaced});
parse reads them back. A value containing a glyph character is refused.
Development
License
MIT