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