Skip to main content

ahk/
json.rs

1//! The JSON the runner writes, and the one it reads back.
2//!
3//! The report is a fixed shape -- the fields the notes of the runner name --
4//! and it is written here field by field rather than through a value tree:
5//! the shape is known at the point of writing, so a tree would be built only
6//! to be walked again.
7//!
8//! The reading is the other half, and a test is what asks for it: a case runs
9//! the runner, takes the report off its standard output, and asks the report
10//! what it holds. The reader answers with a tree of its own, which is small
11//! on purpose: the format has six kinds of value, and a report carries all of
12//! them.
13//!
14//! The escaping is the one of the format: the characters that must be
15//! escaped are escaped, and every other character goes through as it is.
16
17use alloc::collections::BTreeMap;
18use alloc::string::String;
19use alloc::string::ToString;
20use alloc::vec::Vec;
21use core::fmt::Write as _;
22
23/// A builder for one JSON object.
24///
25/// It writes the opening brace when the first field arrives, so an object
26/// that has no field is `{}` and not a broken one.
27pub struct Object {
28    text: String,
29    first: bool,
30}
31
32impl Object {
33    /// A new object, with room for `fields` of them.
34    pub fn new(capacity: usize) -> Object {
35        Object {
36            text: String::with_capacity(capacity),
37            first: true,
38        }
39    }
40
41    /// Write the name of a field and its value, which the caller writes.
42    ///
43    /// The value is written by the closure into the same buffer, so a field
44    /// that is an array or another object nests without a value tree in
45    /// between.
46    pub fn field<F>(&mut self, name: &str, value: F) -> &mut Object
47    where
48        F: FnOnce(&mut String),
49    {
50        if self.first {
51            self.text.push('{');
52            self.first = false;
53        } else {
54            self.text.push(',');
55        }
56        write_name(&mut self.text, name);
57        self.text.push(':');
58        value(&mut self.text);
59        self
60    }
61
62    /// Write a field whose value is a text.
63    pub fn text(&mut self, name: &str, value: &str) -> &mut Object {
64        self.field(name, |out| write_text(out, value))
65    }
66
67    /// Write a field whose value is a whole number.
68    pub fn number(&mut self, name: &str, value: i64) -> &mut Object {
69        self.field(name, |out| {
70            let _ = write!(out, "{value}");
71        })
72    }
73
74    /// Write a field whose value is a truth value.
75    pub fn boolean(&mut self, name: &str, value: bool) -> &mut Object {
76        self.field(name, |out| {
77            out.push_str(if value { "true" } else { "false" });
78        })
79    }
80
81    /// Write a field whose value is null.
82    pub fn nothing(&mut self, name: &str) -> &mut Object {
83        self.field(name, |out| out.push_str("null"))
84    }
85
86    /// Write a field whose value is a whole number, or null when it is not
87    /// there.
88    pub fn optional_number(&mut self, name: &str, value: Option<i64>) -> &mut Object {
89        match value {
90            Some(value) => self.number(name, value),
91            None => self.nothing(name),
92        }
93    }
94
95    /// Write a field whose value is an array of texts.
96    pub fn texts(&mut self, name: &str, values: &[String]) -> &mut Object {
97        self.field(name, |out| {
98            out.push('[');
99            for (index, value) in values.iter().enumerate() {
100                if index > 0 {
101                    out.push(',');
102                }
103                write_text(out, value);
104            }
105            out.push(']');
106        })
107    }
108
109    /// The object, as JSON.
110    pub fn finish(self) -> String {
111        if self.first {
112            "{}".to_string()
113        } else {
114            self.text + "}"
115        }
116    }
117}
118
119/// Write the name of a field: the text, quoted and escaped.
120fn write_name(out: &mut String, name: &str) {
121    write_text(out, name);
122}
123
124/// Write a text as a JSON text, with the quotes.
125///
126/// The escapement is the one of the format: the quote and the reverse solidus
127/// are spelled out, and so are the control characters, which have no spelling
128/// of their own. Everything else -- including the letters that are not ASCII
129/// -- goes through as it is, which the format allows and which keeps a report
130/// of a script in the language the script was written in.
131pub fn write_text(out: &mut String, value: &str) {
132    out.push('"');
133    for letter in value.chars() {
134        match letter {
135            '"' => out.push_str("\\\""),
136            '\\' => out.push_str("\\\\"),
137            '\n' => out.push_str("\\n"),
138            '\r' => out.push_str("\\r"),
139            '\t' => out.push_str("\\t"),
140            '\u{08}' => out.push_str("\\b"),
141            '\u{0C}' => out.push_str("\\f"),
142            other if (other as u32) < 0x20 => {
143                let _ = write!(out, "\\u{:04x}", other as u32);
144            }
145            other => out.push(other),
146        }
147    }
148    out.push('"');
149}
150
151#[cfg(test)]
152mod tests {
153    use super::{Object, write_text};
154
155    /// A text is quoted, and the characters the format spells out are the
156    /// ones that are spelled out.
157    #[test]
158    fn a_text_is_quoted_and_escaped() {
159        let mut out = String::new();
160        write_text(&mut out, "a\"b\\c");
161        assert_eq!(out, "\"a\\\"b\\\\c\"");
162    }
163
164    /// An object with no field is `{}`.
165    #[test]
166    fn an_object_with_no_field_is_empty() {
167        assert_eq!(Object::new(8).finish(), "{}");
168    }
169
170    /// The fields are in the order they are written, and each one is
171    /// separated from the one before it.
172    #[test]
173    fn the_fields_are_written_in_the_order_they_arrive() {
174        let mut object = Object::new(32);
175        object
176            .boolean("ok", true)
177            .number("line", 3)
178            .nothing("error");
179        assert_eq!(object.finish(), "{\"ok\":true,\"line\":3,\"error\":null}");
180    }
181}
182
183/// A value of a document, read.
184#[derive(Debug, Clone, PartialEq)]
185pub enum Read {
186    /// The `null` of the format.
187    Null,
188    /// A truth value.
189    Bool(bool),
190    /// A number, kept as the text of it: the format has no limit on the
191    /// digits, and a report asks a number for what it is and not for how it is
192    /// spelled.
193    Number(String),
194    /// A text.
195    Text(String),
196    /// An array.
197    Array(Vec<Read>),
198    /// An object, in the order of the names it arrived in.
199    Object(BTreeMap<String, Read>),
200}
201
202impl Read {
203    /// The value under a name, when this one is an object that has it.
204    pub fn get(&self, name: &str) -> Option<&Read> {
205        match self {
206            Read::Object(members) => members.get(name),
207            _ => None,
208        }
209    }
210
211    /// The value at a place, when this one is an array that has it.
212    pub fn at(&self, place: usize) -> Option<&Read> {
213        match self {
214            Read::Array(values) => values.get(place),
215            _ => None,
216        }
217    }
218
219    /// The values of an array.
220    pub fn array(&self) -> &[Read] {
221        match self {
222            Read::Array(values) => values,
223            _ => &[],
224        }
225    }
226
227    /// The names of the members of an object, in the order of the document.
228    pub fn names(&self) -> Vec<&str> {
229        match self {
230            Read::Object(members) => members.keys().map(String::as_str).collect(),
231            _ => Vec::new(),
232        }
233    }
234
235    /// The text of the value, when it is a text.
236    pub fn as_str(&self) -> Option<&str> {
237        match self {
238            Read::Text(text) => Some(text),
239            _ => None,
240        }
241    }
242
243    /// The text under a name, when the member is a text.
244    pub fn field_text(&self, name: &str) -> Option<&str> {
245        self.get(name).and_then(Read::as_str)
246    }
247
248    /// The value as a whole number.
249    pub fn as_i64(&self) -> Option<i64> {
250        match self {
251            Read::Number(text) => text.parse().ok(),
252            _ => None,
253        }
254    }
255
256    /// The value as a truth value.
257    pub fn as_bool(&self) -> Option<bool> {
258        match self {
259            Read::Bool(value) => Some(*value),
260            _ => None,
261        }
262    }
263
264    /// Whether the value is a number of any kind.
265    pub fn is_number(&self) -> bool {
266        matches!(self, Read::Number(_))
267    }
268
269    /// Whether the value is a text.
270    pub fn is_string(&self) -> bool {
271        matches!(self, Read::Text(_))
272    }
273
274    /// Whether the value is null.
275    pub fn is_null(&self) -> bool {
276        matches!(self, Read::Null)
277    }
278}
279
280/// The reason a document could not be read.
281#[derive(Debug, Clone, PartialEq, Eq)]
282pub struct ReadError {
283    /// What went wrong, in a sentence.
284    pub reason: String,
285    /// Where in the text it went wrong.
286    pub at: usize,
287}
288
289impl core::fmt::Display for ReadError {
290    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
291        write!(formatter, "{} at byte {}", self.reason, self.at)
292    }
293}
294
295#[cfg(feature = "std")]
296impl std::error::Error for ReadError {}
297
298/// Read a document.
299pub fn read(text: &str) -> Result<Read, ReadError> {
300    let mut parser = Reader {
301        bytes: text.as_bytes(),
302        at: 0,
303    };
304    let value = parser.value()?;
305    parser.space();
306    if parser.at != parser.bytes.len() {
307        return Err(parser.the_error("the document ends before its value does"));
308    }
309    Ok(value)
310}
311
312/// The reader of one document.
313struct Reader<'a> {
314    bytes: &'a [u8],
315    at: usize,
316}
317
318impl Reader<'_> {
319    /// The reason of a failure, at the place the reader is.
320    fn the_error(&self, reason: &str) -> ReadError {
321        ReadError {
322            reason: reason.to_string(),
323            at: self.at,
324        }
325    }
326
327    /// Skip the spaces the format allows between the values.
328    fn space(&mut self) {
329        while let Some(byte) = self.bytes.get(self.at) {
330            if matches!(byte, b' ' | b'\t' | b'\n' | b'\r') {
331                self.at += 1;
332            } else {
333                break;
334            }
335        }
336    }
337
338    /// Read one value.
339    fn value(&mut self) -> Result<Read, ReadError> {
340        self.space();
341        match self.bytes.get(self.at) {
342            Some(b'{') => self.object(),
343            Some(b'[') => self.array(),
344            Some(b'"') => Ok(Read::Text(self.text()?)),
345            Some(b't') => self.word("true", Read::Bool(true)),
346            Some(b'f') => self.word("false", Read::Bool(false)),
347            Some(b'n') => self.word("null", Read::Null),
348            Some(byte) if *byte == b'-' || byte.is_ascii_digit() => self.number(),
349            Some(_) => Err(self.the_error("the document holds a character that begins no value")),
350            None => Err(self.the_error("the document ends where a value was wanted")),
351        }
352    }
353
354    /// Read the word that is there, which must be the one named.
355    fn word(&mut self, word: &str, answer: Read) -> Result<Read, ReadError> {
356        if self.bytes[self.at..].starts_with(word.as_bytes()) {
357            self.at += word.len();
358            Ok(answer)
359        } else {
360            Err(self.the_error("the document holds a word that is not a value of the format"))
361        }
362    }
363
364    /// Read an object.
365    fn object(&mut self) -> Result<Read, ReadError> {
366        self.at += 1;
367        let mut members = BTreeMap::new();
368        self.space();
369        if self.bytes.get(self.at) == Some(&b'}') {
370            self.at += 1;
371            return Ok(Read::Object(members));
372        }
373        loop {
374            self.space();
375            if self.bytes.get(self.at) != Some(&b'"') {
376                return Err(self.the_error("a name of an object is not a text"));
377            }
378            let name = self.text()?;
379            self.space();
380            if self.bytes.get(self.at) != Some(&b':') {
381                return Err(self.the_error("a name of an object is not followed by a colon"));
382            }
383            self.at += 1;
384            let value = self.value()?;
385            members.insert(name, value);
386            self.space();
387            match self.bytes.get(self.at) {
388                Some(b',') => self.at += 1,
389                Some(b'}') => {
390                    self.at += 1;
391                    return Ok(Read::Object(members));
392                }
393                _ => return Err(self.the_error("an object ends without its closing brace")),
394            }
395        }
396    }
397
398    /// Read an array.
399    fn array(&mut self) -> Result<Read, ReadError> {
400        self.at += 1;
401        let mut values = Vec::new();
402        self.space();
403        if self.bytes.get(self.at) == Some(&b']') {
404            self.at += 1;
405            return Ok(Read::Array(values));
406        }
407        loop {
408            values.push(self.value()?);
409            self.space();
410            match self.bytes.get(self.at) {
411                Some(b',') => self.at += 1,
412                Some(b']') => {
413                    self.at += 1;
414                    return Ok(Read::Array(values));
415                }
416                _ => return Err(self.the_error("an array ends without its closing bracket")),
417            }
418        }
419    }
420
421    /// Read a text, with its quotes.
422    fn text(&mut self) -> Result<String, ReadError> {
423        self.at += 1;
424        let mut out = String::new();
425        loop {
426            let byte = *self
427                .bytes
428                .get(self.at)
429                .ok_or_else(|| self.the_error("a text ends before its closing quote"))?;
430            match byte {
431                b'"' => {
432                    self.at += 1;
433                    return Ok(out);
434                }
435                b'\\' => {
436                    self.at += 1;
437                    let escape = *self
438                        .bytes
439                        .get(self.at)
440                        .ok_or_else(|| self.the_error("a text ends in the middle of an escape"))?;
441                    self.at += 1;
442                    match escape {
443                        b'"' => out.push('"'),
444                        b'\\' => out.push('\\'),
445                        b'/' => out.push('/'),
446                        b'b' => out.push('\u{08}'),
447                        b'f' => out.push('\u{0C}'),
448                        b'n' => out.push('\n'),
449                        b'r' => out.push('\r'),
450                        b't' => out.push('\t'),
451                        b'u' => {
452                            let place = self.at;
453                            let digits = self.bytes.get(place..place + 4).ok_or_else(|| {
454                                self.the_error("an escape of four digits is short")
455                            })?;
456                            let hex = core::str::from_utf8(digits)
457                                .map_err(|_| self.the_error("an escape is not four digits"))?;
458                            let code = u32::from_str_radix(hex, 16)
459                                .map_err(|_| self.the_error("an escape is not four digits"))?;
460                            self.at += 4;
461                            out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
462                        }
463                        _ => {
464                            return Err(
465                                self.the_error("a text holds an escape the format does not define")
466                            );
467                        }
468                    }
469                }
470                other => {
471                    // A text of the format is UTF-8, and the bytes of a
472                    // letter that is not ASCII are taken as they are.
473                    let rest = core::str::from_utf8(&self.bytes[self.at..])
474                        .map_err(|_| self.the_error("a text is not a text of the format"))?;
475                    let letter = rest
476                        .chars()
477                        .next()
478                        .ok_or_else(|| self.the_error("a text ends where a letter was wanted"))?;
479                    out.push(letter);
480                    self.at += letter.len_utf8();
481                    if other == 0 {
482                        return Err(self.the_error("a text holds a byte that is not of the format"));
483                    }
484                }
485            }
486        }
487    }
488
489    /// Read a number, and keep the text of it.
490    fn number(&mut self) -> Result<Read, ReadError> {
491        let start = self.at;
492        if self.bytes.get(self.at) == Some(&b'-') {
493            self.at += 1;
494        }
495        while let Some(byte) = self.bytes.get(self.at) {
496            if byte.is_ascii_digit() || matches!(byte, b'.' | b'e' | b'E' | b'+' | b'-') {
497                self.at += 1;
498            } else {
499                break;
500            }
501        }
502        let text = core::str::from_utf8(&self.bytes[start..self.at])
503            .map_err(|_| self.the_error("a number is not a number of the format"))?;
504        if text.is_empty() || text == "-" {
505            return Err(self.the_error("a number holds no digits"));
506        }
507        Ok(Read::Number(text.to_string()))
508    }
509}