1use 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
52pub const VERSION: &str = env!("CARGO_PKG_VERSION");
54
55pub const SOH: u8 = 0x01; pub const STX: u8 = 0x02; pub const ETX: u8 = 0x03; pub const EOT: u8 = 0x04; pub const ENQ: u8 = 0x05; pub const BEL: u8 = 0x07; pub const DLE: u8 = 0x10; pub const SYN: u8 = 0x16; pub const ETB: u8 = 0x17; pub const CAN: u8 = 0x18; pub const EM: u8 = 0x19; pub const SUB: u8 = 0x1a; pub const FS: u8 = 0x1c; pub const GS: u8 = 0x1d; pub const RS: u8 = 0x1e; pub const US: u8 = 0x1f; pub const HT: u8 = 0x09;
75pub const LF: u8 = 0x0a;
76pub const CR: u8 = 0x0d;
77pub const SP: u8 = 0x20;
78
79#[inline]
81pub fn is_layout(byte: u8) -> bool {
82 byte == SP || byte == HT || byte == LF || byte == CR
83}
84
85#[inline]
87pub fn is_control(byte: u8) -> bool {
88 byte < 0x20
89}
90
91#[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#[inline]
102pub fn is_text_escaped(byte: u8) -> bool {
103 matches!(byte, STX | ETX | DLE | ETB | EOT | SYN | EM)
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum Error {
109 Syntax { message: String, position: usize },
111 UnassignedCode { byte: u8, position: usize },
113 UnexpectedEnd { what: String, position: usize },
115 DamagedBlock { index: usize, resume_offset: usize },
119 Key(String),
121 GlyphInData,
124 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 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
188pub type Result<T> = std::result::Result<T, Error>;
190
191pub 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
208pub fn is_text(raw: &[u8]) -> bool {
210 trim(raw).first() == Some(&STX)
211}
212
213pub fn is_level(raw: &[u8]) -> bool {
215 trim(raw).first() == Some(&DLE)
216}
217
218pub fn is_reference(raw: &[u8]) -> bool {
220 trim(raw).first() == Some(&ENQ)
221}
222
223pub 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
265fn 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
277pub 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
300pub 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
309pub 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
326pub fn is_name(value: &[u8]) -> bool {
329 is_plain(value)
330}
331
332pub 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}