1use 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
49pub const VERSION: &str = env!("CARGO_PKG_VERSION");
51
52pub 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;
72pub const LF: u8 = 0x0a;
73pub const CR: u8 = 0x0d;
74pub const SP: u8 = 0x20;
75
76#[inline]
78pub fn is_layout(byte: u8) -> bool {
79 byte == SP || byte == HT || byte == LF || byte == CR
80}
81
82#[inline]
84pub fn is_control(byte: u8) -> bool {
85 byte < 0x20
86}
87
88#[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#[inline]
99pub fn is_text_escaped(byte: u8) -> bool {
100 matches!(byte, STX | ETX | DLE | ETB | EOT | SYN | EM)
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum Error {
106 Syntax { message: String, position: usize },
108 UnassignedCode { byte: u8, position: usize },
110 UnexpectedEnd { what: String, position: usize },
112 Key(String),
114 GlyphInData,
117 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 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
174pub type Result<T> = std::result::Result<T, Error>;
176
177pub 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
194pub fn is_text(raw: &[u8]) -> bool {
196 trim(raw).first() == Some(&STX)
197}
198
199pub fn is_level(raw: &[u8]) -> bool {
201 trim(raw).first() == Some(&DLE)
202}
203
204pub fn is_reference(raw: &[u8]) -> bool {
206 trim(raw).first() == Some(&ENQ)
207}
208
209pub 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
251fn 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
263pub 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
286pub 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
295pub 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
312pub fn is_name(value: &[u8]) -> bool {
315 is_plain(value)
316}
317
318pub 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}