use std::borrow::Cow;
use std::fmt;
mod body;
mod builder;
mod document;
mod parser;
mod pretty;
mod stream;
mod validator;
pub mod csv;
pub mod diff;
pub mod json;
pub mod scan;
pub use body::{Body, FileView, Group, Pair, Record, Reference, Table, Unit};
pub use builder::Builder;
pub use document::{Container, Document, Heading};
pub use parser::Parser;
pub use pretty::{align, format, format_mode, format_with, glyph, parse, FormatMode};
pub use stream::{
last_commit_end, open_log, open_log_with, read_log, repair_log, FileLog, StreamReader,
StreamWriter,
};
pub use validator::{canonical, validate, Validator};
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub 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;
pub const LF: u8 = 0x0a;
pub const CR: u8 = 0x0d;
pub const SP: u8 = 0x20;
#[inline]
pub fn is_layout(byte: u8) -> bool {
byte == SP || byte == HT || byte == LF || byte == CR
}
#[inline]
pub fn is_control(byte: u8) -> bool {
byte < 0x20
}
#[inline]
pub fn is_assigned(byte: u8) -> bool {
matches!(
byte,
SOH | STX | ETX | EOT | ENQ | BEL | DLE | SYN | ETB | CAN | EM | SUB | FS | GS | RS | US
)
}
#[inline]
pub fn is_text_escaped(byte: u8) -> bool {
matches!(byte, STX | ETX | DLE | ETB | EOT | SYN | EM)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
Syntax { message: String, position: usize },
UnassignedCode { byte: u8, position: usize },
UnexpectedEnd { what: String, position: usize },
DamagedBlock { index: usize, resume_offset: usize },
Key(String),
GlyphInData,
Other(String),
}
impl Error {
pub(crate) fn syntax(message: impl Into<String>, position: usize) -> Self {
Error::Syntax {
message: message.into(),
position,
}
}
pub(crate) fn end(what: impl Into<String>, position: usize) -> Self {
Error::UnexpectedEnd {
what: what.into(),
position,
}
}
pub(crate) fn other(message: impl Into<String>) -> Self {
Error::Other(message.into())
}
pub fn position(&self) -> Option<usize> {
match self {
Error::Syntax { position, .. }
| Error::UnassignedCode { position, .. }
| Error::UnexpectedEnd { position, .. } => Some(*position),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Syntax { message, position } => write!(f, "{message} at byte {position}"),
Error::UnassignedCode { byte, position } => {
write!(f, "Unassigned control code 0x{byte:02x} at byte {position}")
}
Error::UnexpectedEnd { what, position } => {
write!(f, "Unexpected end of input: {what} at byte {position}")
}
Error::DamagedBlock {
index,
resume_offset,
} => write!(
f,
"block {index} is damaged; reading can resume at byte {resume_offset}"
),
Error::Key(what) => write!(f, "{what}"),
Error::GlyphInData => write!(
f,
"value contains a Control Picture character and cannot be shown in pretty form"
),
Error::Other(message) => write!(f, "{message}"),
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
pub fn trim(raw: &[u8]) -> &[u8] {
let mut s = 0;
let mut e = raw.len();
while s < e && is_layout(raw[s]) {
s += 1;
}
while e > s && is_layout(raw[e - 1]) {
e -= 1;
}
&raw[s..e]
}
pub fn is_text(raw: &[u8]) -> bool {
trim(raw).first() == Some(&STX)
}
pub fn is_level(raw: &[u8]) -> bool {
trim(raw).first() == Some(&DLE)
}
pub fn is_reference(raw: &[u8]) -> bool {
trim(raw).first() == Some(&ENQ)
}
pub fn value(raw: &[u8]) -> Result<Cow<'_, [u8]>> {
let t = trim(raw);
let Some(&first) = t.first() else {
return Ok(Cow::Borrowed(t));
};
match first {
STX => {
let stop = scan::text(t, 0, t.len())?;
only_notes_after(t, stop, "text cannot be part of a plain value")?;
Ok(decode_text(&t[1..stop - 1]))
}
BEL => {
only_notes_after(t, 0, "value after a comment in the same unit")?;
Ok(Cow::Borrowed(&[]))
}
DLE => Err(Error::syntax("a nested level is not a scalar value", 0)),
ENQ => Err(Error::syntax("a reference is not a scalar value", 0)),
_ => {
for (i, &b) in t.iter().enumerate() {
if b == BEL {
only_notes_after(t, i, "value after a note in the same unit")?;
return Ok(Cow::Borrowed(trim(&t[..i])));
}
if b < 0x20 {
let what = if is_layout(b) {
"layout code inside a plain value"
} else {
"control code inside a plain value"
};
return Err(Error::syntax(what, i));
}
}
Ok(Cow::Borrowed(t))
}
}
}
fn only_notes_after(t: &[u8], pos: usize, what: &str) -> Result<()> {
let mut pos = scan::layout(t, pos, t.len());
while pos < t.len() {
if t[pos] != BEL {
return Err(Error::syntax(what, pos));
}
pos = scan::layout(t, scan::comment(t, pos, t.len())?, t.len());
}
Ok(())
}
pub fn decode_text(inside: &[u8]) -> Cow<'_, [u8]> {
let Some(first) = inside.iter().position(|&b| b == DLE) else {
return Cow::Borrowed(inside);
};
let mut out = Vec::with_capacity(inside.len());
out.extend_from_slice(&inside[..first]);
let mut i = first;
while i < inside.len() {
if inside[i] == DLE {
i += 1;
if i >= inside.len() {
break;
}
}
out.push(inside[i]);
i += 1;
}
Cow::Owned(out)
}
pub fn is_plain(value: &[u8]) -> bool {
match (value.first(), value.last()) {
(None, _) | (_, None) => true,
(Some(&f), Some(&l)) => !is_layout(f) && !is_layout(l) && value.iter().all(|&b| b >= 0x20),
}
}
pub fn write_value(out: &mut Vec<u8>, value: &[u8]) {
if is_plain(value) {
out.extend_from_slice(value);
} else {
out.push(STX);
for &b in value {
if b < 0x20 && is_text_escaped(b) {
out.push(DLE);
}
out.push(b);
}
out.push(ETX);
}
}
pub fn is_name(value: &[u8]) -> bool {
is_plain(value)
}
pub fn write_name(out: &mut Vec<u8>, name: &[u8]) -> Result<()> {
if !is_name(name) {
return Err(Error::other(format!(
"not a legal name: {:?}",
String::from_utf8_lossy(name)
)));
}
out.extend_from_slice(name);
Ok(())
}