c0
A Ruby implementation of C0DATA 1.0 — structured data built on ASCII C0 control codes.
This is not a reimplementation: it's a thin, fast binding over the c0 C core (a Ruby C extension, no runtime dependencies), so the scan-heavy work runs as native C while the Ruby layer provides an idiomatic API. The read path is zero-copy — accessors return shared byteslices into the input buffer.
Usage
require "c0"
# Write: ␖␁version␟1␝users␁␞name␟amount␞Alice␟1502.30␞Bob␟340.00␄
buf = C0.build do |b|
b.syn(version: "1")
b.group("users", %w[name amount]) do # ␝users then the header row ␁␞name␟amount
b.record("Alice", "1502.30")
b.record("Bob", "340.00")
end
b.eot
end
# Read (zero-copy: values are shared byteslices of buf)
doc = C0::Document.new(buf)
doc.heading.version # => 1
doc["users"].headers # => ["name", "amount"]
doc["users"].each do |rec|
name, amount = rec.values # logical values: text decoded, layout trimmed
rec.value(0) # => "Alice"
end
# Canonical form is hashable for content addressing
C0.canonical?(doc.body.raw) # => true
# Streams, containers, pretty form, diffs
C0::Stream::Reader.new(File.binread("events.c0")) # #torn?, #committed, #blocks, #records
C0::Container.new(buf) # several documents, EM tail, #blob(name)
C0::Pretty.format(buf, mode: :aligned) # Unicode Control Pictures
C0::Diff.apply(diff, "greeting.txt" => source) # C0DIFF, validated before anything is written
Values are byte-transparent and written in their one spelling: plain when
they can be, text (␂…␃) when they hold a control byte, a line break or edge
whitespace.
Parse is validate. Constructing a Document, Container, Body or
Stream::Reader applies the whole grammar to the bytes and raises a
C0::SyntaxError (with #position) on malformed input; the navigators then
assume well-formed input. C0.validate(buf) is the same check on a whole
buffer. C0.canonical?(buf) checks the canonical constraints and is opt-in:
a non-canonical document still reads.
The model is 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 makes the element after it a
child of the element before, at that code's grain: ␚␝s is a subsection at
depth two (g.depth), ␞a␟b␚␟c is two units with c a sub-unit of b,
not a unit of the record (field_count, values and pairs see units
only); ␚␞, ␚␜ and ␚␁ are reserved and refused. rec.unit(n) and
rec.unit(key) give a unit with its subs, each a C0::Unit with subs
of its own; rec.units lists every positional unit so.
Loud warnings (doc.warnings: no SYN, no EOT, an unknown or duplicate
heading key, a shape other than diff or stream, a version other than 1)
never fail a parse.
Keyed records, nesting, references
buf = C0.build do |b|
b.group("server")
b.map("host" => "0.0.0.0", "port" => "8080") # ␞␁host␟0.0.0.0␁port␟8080
b.record("Alice")
b.list(%w[Admin Editor]) # one unit: ␐␞Admin␟Editor␘
b.level do # ␐ … a whole body … ␘
b.header(%w[street city])
b.record("1 Main", "Springfield")
end
b.ref("tags") # ␅tags
b.ref("tags", "001", "label") # ␅␐␝tags␞001␟label␘
b.ref { b.gs("tags").rs.soh("host").us } # ␅␐␝tags␞␁host␟␘, any pattern
b.field("10").sub_unit("20") # 10␚␟20: 20 a sub-unit of 10
b.group("notes", nil, 2) # ␚␝notes: a subsection of server
end
g = C0::Document.new(buf)["server"]
g.record(0).keyed? # => true
g.record(0)["port"] # => "8080" (last wins)
g.record(1).list(1) # => ["Admin", "Editor"]
g.record(1).level(2).record(0) # => the nested record
g.record(1).ref(3).name # => "tags" (a plain group reference)
g.record(1).ref(4).pattern # => a Body: the level ␝tags␞001␟label parsed
g.record(1).ref(4).path # => ["tags", "001", "label"]
g.record(1).value(6) # => "10" (the unit)
g.record(1).unit(6).subs.map(&:value) # => ["20"] (its sub-unit)
g.record(1).field_count # => 7 (a sub-unit is not a unit)
A reference (rec.ref(i)) is a group name (␅tags) or a pattern: the
level ␅␐␝tags␞001␟label␘, one branch of the target with its values left
out, parsed as a body. ref.path linearises either form; ref.group? says
whether it names a group as a whole. The text form ␅␂…␃ is an error.
Resolution is not implemented.
The builder also has file, section, header, field, key (with a
block for a nested value), heading_level, note, block, item,
etb(payload) and em(tail), matching the Crystal reference; every method
returns the builder, so calls chain.
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. The argument is
optional where the grammar allows the bare code (gs, rs, us, soh,
bel, etb); sub is always bare; enq takes a group name, or a block
that writes a pattern:
b.rs("Alice").us("1502.30") # ␞Alice␟1502.30
b.rs.soh("host").us("localhost").soh("port").us("5432") # ␞␁host␟localhost␁port␟5432
b.gs("users").soh.rs("name").us("amount") # ␝users␁␞name␟amount: a header row
b.rs("cfg").us.dle.rs.soh("b").us("2").can # ␞cfg␟␐␞␁b␟2␘: a nested level
b.bel("checked").rs("x") # ␇checked␞x: a note
b.bel.gs("old") # ␇␝old: a dead group
b.rs("old").sub.us("new") # ␞old␚␟new: new a sub-unit of old
b.gs("a").rs("1").sub.gs("b").rs("2") # ␝a␞1␚␝b␞2: b a subsection of a
b.gs("a").gs("b", depth: 2) # ␝a␚␝b: the same, depth spelt
b.rs.enq("tags").us.enq { b.gs("tags").rs("001") } # ␞␅tags␟␅␐␝tags␞001␘
b.syn.soh("version").us("1").rs("a").eot # ␖␁version␟1␞a␄
sub writes SUB alone: the element after the next separator is subordinate
to the one before it, at that code's grain (␚␝ a subsection, ␚␟ a
sub-unit; ␚␞, ␚␜ and ␚␁ are reserved). gs(name, depth:) and
sub_unit(value, depth:) spell the prefix for you. A SUB prefix is
structure: it is hashed as written, kept by the canonical form and
round-tripped by the pretty form. A repeated GS is an empty-named group
(␝␝b is group "" then b), as a repeated code is an empty element
everywhere.
The composed methods above are built on these and cannot write ill-formed
output; with the primitives, well-formedness is yours. Values keep their one
spelling either way (there is no STX/ETX primitive), and names are still
checked. The two layers share the record state and mix freely:
b.rs("a").field("b") writes ␞a␟b, b.record.us("c") writes ␞␟c.
C0DIFF
A diff is an ordinary document of shape diff: files of records, each
record an anchored pattern, with old␚␟new as the substitution
(DIFF.md in the spec).
␖␁shape␟diff
␜greeting.txt
␞␂Hello ␃␟world␚␟universe␟!
␄
diff = C0::Diff.build do |d|
d.file("greeting.txt") do
d.record { |r| r.anchor("Hello "); r.sub("world", "universe"); r.anchor("!") }
d.assert("Bye") # must be present once; nothing changes
d.insert_after("!", "\n") # ␞!␟␚␟␂\n␃
end
end
C0::Diff.apply(diff, "greeting.txt" => source) # => { "greeting.txt" => edited }, validated first
C0::Diff.apply_files(diff, "src") # on disk, atomically (temporary file + rename)
C0::Diff.parse(diff) # => FileEdits of Patterns of Units
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, two
sub-units on one unit, a sub-unit of a sub-unit, an empty search text,
␟␚␟, the same path twice) is refused with a C0::Diff::Error.
Stream logs
r = C0::Stream::Reader.read("events.c0")
r.torn? # uncommitted tail?
r.damaged # indexes of committed blocks that are not well-formed
r.each_record { |rec| ... }
Any error inside a committed block damages the block, and a damaged block
delivers nothing. By default the reader yields the records before it and
raises C0::Stream::DamagedBlockError with the block's index and the
resume_offset to go on from; with
Reader.new(buf, continue_past_damage: true) it skips the block and reads
on. A damaged block adds nothing to the parse state, so what follows is read
in the context before it.
Install / build
gem install c0data # the gem is c0data; in code it is `require "c0"`
From a checkout, the C core and the shared conformance vectors are git submodules:
git submodule update --init # pulls in c0-c (the headers and c0_diff.c) and c0-spec
rake compile # builds the extension
Requires a C compiler and Ruby development headers (MRI).
Status
Binds the c0-c 1.0 core: one parser for the whole grammar (parse is
validate) and the canonical check, documents and containers (SYN heading
with shape, schema, version and blob, EOT, EM tail, warnings),
bodies with files, groups, header rows, positional and keyed records, nested
levels, lists and references (plain and pattern), subsections, sub-units
and dead elements, the canonical builder, ETB stream mode
(committed region, damaged blocks with resume offsets, torn-tail detection),
C0DIFF (parse, build, atomic apply) and pretty form (compact, aligned and
spaced). Passes every shared conformance vector from
c0-spec: decode, encode, canonical,
invalid, nested, stream and diff (277 cases).
Converters (CSV / JSON) are not yet wrapped.
Test
rake test
License
MIT