Skip to main content

c0/
lib.rs

1//! C0DATA — structured data using ASCII C0 control codes.
2//!
3//! Values are UTF-8 text (any bytes, as text); structure is sixteen
4//! single-byte control codes. This crate is a zero-copy reader/writer for
5//! the 1.0 design: [`Container`], [`Document`] and [`Body`] index a buffer
6//! and hand back slices into it, [`Builder`] writes canonical compact form,
7//! [`validate`] and [`canonical`] check well-formedness and canonicality,
8//! and the `stream`, `pretty`, `diff`, `csv` and `json` modules cover the
9//! rest of the spec. One [`Parser`] implements GRAMMAR.md; everything
10//! else sits on it.
11//!
12//! ```
13//! let buf = c0::Builder::build(|b| {
14//!     b.group("users", Some(&["name", "amount"]));
15//!     b.record(&["Alice", "100"]);
16//!     b.record(&["Bob", "200"]);
17//! });
18//! let body = c0::Body::new(&buf).unwrap();
19//! let users = body.group(0);
20//! assert_eq!(users.headers(), [b"name".as_slice(), b"amount"]);
21//! assert_eq!(users.record(1).value(0).unwrap().as_ref(), b"Bob");
22//! assert!(c0::canonical(&buf));
23//! ```
24
25use std::borrow::Cow;
26use std::fmt;
27
28mod body;
29mod builder;
30mod document;
31mod parser;
32mod pretty;
33mod stream;
34mod validator;
35
36pub mod csv;
37pub mod diff;
38pub mod json;
39pub mod scan;
40
41pub use body::{Body, FileView, Group, Pair, Record, Reference, Table, Unit};
42pub use builder::Builder;
43pub use document::{Container, Document, Heading};
44pub use parser::Parser;
45pub use pretty::{align, format, format_mode, format_with, glyph, parse, FormatMode};
46pub use stream::{
47    last_commit_end, open_log, open_log_with, read_log, repair_log, FileLog, StreamReader,
48    StreamWriter,
49};
50pub use validator::{canonical, validate, Validator};
51
52/// Crate version (mirrors the Crystal reference's `C0::VERSION`).
53pub const VERSION: &str = env!("CARGO_PKG_VERSION");
54
55// Assigned C0 control codes (DESIGN.md "Assigned Control Codes").
56pub const SOH: u8 = 0x01; // Heading: a key for the value after it, or SOH RS a header row
57pub const STX: u8 = 0x02; // Start of text (literal value)
58pub const ETX: u8 = 0x03; // End of text
59pub const EOT: u8 = 0x04; // End of document
60pub const ENQ: u8 = 0x05; // Reference
61pub const BEL: u8 = 0x07; // Comment: a note, or marks the next element dead
62pub const DLE: u8 = 0x10; // Recurse: opens a nested level (outside text); escape (inside text)
63pub const SYN: u8 = 0x16; // Start of document, then the heading
64pub const ETB: u8 = 0x17; // Commit marker (stream mode)
65pub const CAN: u8 = 0x18; // Close a nested level
66pub const EM: u8 = 0x19; // End of medium: raw blob follows
67pub const SUB: u8 = 0x1a; // Subordinate: the element after is a child of the element before (GS: subsection, US: sub-unit)
68pub const FS: u8 = 0x1c; // File separator
69pub const GS: u8 = 0x1d; // Group separator
70pub const RS: u8 = 0x1e; // Record separator
71pub const US: u8 = 0x1f; // Unit separator
72
73// Layout codes outside text.
74pub const HT: u8 = 0x09;
75pub const LF: u8 = 0x0a;
76pub const CR: u8 = 0x0d;
77pub const SP: u8 = 0x20;
78
79/// Whether a byte is layout outside text (SP, HT, LF, CR).
80#[inline]
81pub fn is_layout(byte: u8) -> bool {
82    byte == SP || byte == HT || byte == LF || byte == CR
83}
84
85/// Whether a byte is a control code (below 0x20).
86#[inline]
87pub fn is_control(byte: u8) -> bool {
88    byte < 0x20
89}
90
91/// Whether a byte is one of the sixteen assigned structural or framing codes.
92#[inline]
93pub fn is_assigned(byte: u8) -> bool {
94    matches!(
95        byte,
96        SOH | STX | ETX | EOT | ENQ | BEL | DLE | SYN | ETB | CAN | EM | SUB | FS | GS | RS | US
97    )
98}
99
100/// Whether a byte is one of the seven codes that take a DLE inside text.
101#[inline]
102pub fn is_text_escaped(byte: u8) -> bool {
103    matches!(byte, STX | ETX | DLE | ETB | EOT | SYN | EM)
104}
105
106/// Errors raised while scanning, validating or decoding C0DATA.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum Error {
109    /// Malformed input: what went wrong and the byte offset.
110    Syntax { message: String, position: usize },
111    /// A control byte that is not one of the assigned codes, outside text.
112    UnassignedCode { byte: u8, position: usize },
113    /// The input ended inside a construct.
114    UnexpectedEnd { what: String, position: usize },
115    /// A committed stream block that is not well-formed (DESIGN.md, Damaged
116    /// Blocks). `resume_offset` is where reading can go on, after the
117    /// block's ETB and payload.
118    DamagedBlock { index: usize, resume_offset: usize },
119    /// No group or key by that name.
120    Key(String),
121    /// A value holds a Control Picture character and cannot be shown in
122    /// pretty form without ambiguity.
123    GlyphInData,
124    /// A misuse of the API: a unit that is not a level, a level that is
125    /// not a list, a name that is not legal, and the like.
126    Other(String),
127}
128
129impl Error {
130    pub(crate) fn syntax(message: impl Into<String>, position: usize) -> Self {
131        Error::Syntax {
132            message: message.into(),
133            position,
134        }
135    }
136
137    pub(crate) fn end(what: impl Into<String>, position: usize) -> Self {
138        Error::UnexpectedEnd {
139            what: what.into(),
140            position,
141        }
142    }
143
144    pub(crate) fn other(message: impl Into<String>) -> Self {
145        Error::Other(message.into())
146    }
147
148    /// The byte offset the error refers to, when it has one.
149    pub fn position(&self) -> Option<usize> {
150        match self {
151            Error::Syntax { position, .. }
152            | Error::UnassignedCode { position, .. }
153            | Error::UnexpectedEnd { position, .. } => Some(*position),
154            _ => None,
155        }
156    }
157}
158
159impl fmt::Display for Error {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        match self {
162            Error::Syntax { message, position } => write!(f, "{message} at byte {position}"),
163            Error::UnassignedCode { byte, position } => {
164                write!(f, "Unassigned control code 0x{byte:02x} at byte {position}")
165            }
166            Error::UnexpectedEnd { what, position } => {
167                write!(f, "Unexpected end of input: {what} at byte {position}")
168            }
169            Error::DamagedBlock {
170                index,
171                resume_offset,
172            } => write!(
173                f,
174                "block {index} is damaged; reading can resume at byte {resume_offset}"
175            ),
176            Error::Key(what) => write!(f, "{what}"),
177            Error::GlyphInData => write!(
178                f,
179                "value contains a Control Picture character and cannot be shown in pretty form"
180            ),
181            Error::Other(message) => write!(f, "{message}"),
182        }
183    }
184}
185
186impl std::error::Error for Error {}
187
188/// Crate result type.
189pub type Result<T> = std::result::Result<T, Error>;
190
191// ---------------------------------------------------------------------
192// Values
193// ---------------------------------------------------------------------
194
195/// Trim layout from both ends of a raw slice.
196pub fn trim(raw: &[u8]) -> &[u8] {
197    let mut s = 0;
198    let mut e = raw.len();
199    while s < e && is_layout(raw[s]) {
200        s += 1;
201    }
202    while e > s && is_layout(raw[e - 1]) {
203        e -= 1;
204    }
205    &raw[s..e]
206}
207
208/// Whether the raw unit (layout included) is a text value.
209pub fn is_text(raw: &[u8]) -> bool {
210    trim(raw).first() == Some(&STX)
211}
212
213/// Whether the raw unit is a nested level.
214pub fn is_level(raw: &[u8]) -> bool {
215    trim(raw).first() == Some(&DLE)
216}
217
218/// Whether the raw unit is a reference.
219pub fn is_reference(raw: &[u8]) -> bool {
220    trim(raw).first() == Some(&ENQ)
221}
222
223/// The logical value of a raw unit slice: for text, the inside with its
224/// escapes decoded (zero-copy when there are none); for a plain value, the
225/// slice with edge layout removed. A unit holding only a note or a dead
226/// level is the empty value. Fails on malformed input, on a level and on a
227/// reference (see [`Record::level`] and [`Record::reference`]).
228pub fn value(raw: &[u8]) -> Result<Cow<'_, [u8]>> {
229    let t = trim(raw);
230    let Some(&first) = t.first() else {
231        return Ok(Cow::Borrowed(t));
232    };
233    match first {
234        STX => {
235            let stop = scan::text(t, 0, t.len())?;
236            only_notes_after(t, stop, "text cannot be part of a plain value")?;
237            Ok(decode_text(&t[1..stop - 1]))
238        }
239        BEL => {
240            only_notes_after(t, 0, "value after a comment in the same unit")?;
241            Ok(Cow::Borrowed(&[]))
242        }
243        DLE => Err(Error::syntax("a nested level is not a scalar value", 0)),
244        ENQ => Err(Error::syntax("a reference is not a scalar value", 0)),
245        _ => {
246            for (i, &b) in t.iter().enumerate() {
247                if b == BEL {
248                    only_notes_after(t, i, "value after a note in the same unit")?;
249                    return Ok(Cow::Borrowed(trim(&t[..i])));
250                }
251                if b < 0x20 {
252                    let what = if is_layout(b) {
253                        "layout code inside a plain value"
254                    } else {
255                        "control code inside a plain value"
256                    };
257                    return Err(Error::syntax(what, i));
258                }
259            }
260            Ok(Cow::Borrowed(t))
261        }
262    }
263}
264
265// From pos to the end of the unit only notes (and layout) may follow.
266fn only_notes_after(t: &[u8], pos: usize, what: &str) -> Result<()> {
267    let mut pos = scan::layout(t, pos, t.len());
268    while pos < t.len() {
269        if t[pos] != BEL {
270            return Err(Error::syntax(what, pos));
271        }
272        pos = scan::layout(t, scan::comment(t, pos, t.len())?, t.len());
273    }
274    Ok(())
275}
276
277/// Decode the inside of a text: DLE escapes removed. Zero-copy when there
278/// are none. The inside of a scanned text never ends in a lone DLE; one on
279/// an arbitrary slice is dropped.
280pub fn decode_text(inside: &[u8]) -> Cow<'_, [u8]> {
281    let Some(first) = inside.iter().position(|&b| b == DLE) else {
282        return Cow::Borrowed(inside);
283    };
284    let mut out = Vec::with_capacity(inside.len());
285    out.extend_from_slice(&inside[..first]);
286    let mut i = first;
287    while i < inside.len() {
288        if inside[i] == DLE {
289            i += 1;
290            if i >= inside.len() {
291                break;
292            }
293        }
294        out.push(inside[i]);
295        i += 1;
296    }
297    Cow::Owned(out)
298}
299
300/// Whether a value can be written plain: no byte below 0x20 and no edge
301/// whitespace.
302pub fn is_plain(value: &[u8]) -> bool {
303    match (value.first(), value.last()) {
304        (None, _) | (_, None) => true,
305        (Some(&f), Some(&l)) => !is_layout(f) && !is_layout(l) && value.iter().all(|&b| b >= 0x20),
306    }
307}
308
309/// Write a value in its one canonical spelling: plain when it can be, text
310/// otherwise, with only the seven codes escaped.
311pub fn write_value(out: &mut Vec<u8>, value: &[u8]) {
312    if is_plain(value) {
313        out.extend_from_slice(value);
314    } else {
315        out.push(STX);
316        for &b in value {
317            if b < 0x20 && is_text_escaped(b) {
318                out.push(DLE);
319            }
320            out.push(b);
321        }
322        out.push(ETX);
323    }
324}
325
326/// Whether bytes are a legal name (label, key, header name): no byte below
327/// 0x20 and no edge whitespace. A name may be empty.
328pub fn is_name(value: &[u8]) -> bool {
329    is_plain(value)
330}
331
332/// Write a name; fails if it is not one.
333pub fn write_name(out: &mut Vec<u8>, name: &[u8]) -> Result<()> {
334    if !is_name(name) {
335        return Err(Error::other(format!(
336            "not a legal name: {:?}",
337            String::from_utf8_lossy(name)
338        )));
339    }
340    out.extend_from_slice(name);
341    Ok(())
342}