1use alloc::collections::BTreeMap;
18use alloc::string::String;
19use alloc::string::ToString;
20use alloc::vec::Vec;
21use core::fmt::Write as _;
22
23pub struct Object {
28 text: String,
29 first: bool,
30}
31
32impl Object {
33 pub fn new(capacity: usize) -> Object {
35 Object {
36 text: String::with_capacity(capacity),
37 first: true,
38 }
39 }
40
41 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 pub fn text(&mut self, name: &str, value: &str) -> &mut Object {
64 self.field(name, |out| write_text(out, value))
65 }
66
67 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 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 pub fn nothing(&mut self, name: &str) -> &mut Object {
83 self.field(name, |out| out.push_str("null"))
84 }
85
86 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 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 pub fn finish(self) -> String {
111 if self.first {
112 "{}".to_string()
113 } else {
114 self.text + "}"
115 }
116 }
117}
118
119fn write_name(out: &mut String, name: &str) {
121 write_text(out, name);
122}
123
124pub 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 #[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 #[test]
166 fn an_object_with_no_field_is_empty() {
167 assert_eq!(Object::new(8).finish(), "{}");
168 }
169
170 #[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#[derive(Debug, Clone, PartialEq)]
185pub enum Read {
186 Null,
188 Bool(bool),
190 Number(String),
194 Text(String),
196 Array(Vec<Read>),
198 Object(BTreeMap<String, Read>),
200}
201
202impl Read {
203 pub fn get(&self, name: &str) -> Option<&Read> {
205 match self {
206 Read::Object(members) => members.get(name),
207 _ => None,
208 }
209 }
210
211 pub fn at(&self, place: usize) -> Option<&Read> {
213 match self {
214 Read::Array(values) => values.get(place),
215 _ => None,
216 }
217 }
218
219 pub fn array(&self) -> &[Read] {
221 match self {
222 Read::Array(values) => values,
223 _ => &[],
224 }
225 }
226
227 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 pub fn as_str(&self) -> Option<&str> {
237 match self {
238 Read::Text(text) => Some(text),
239 _ => None,
240 }
241 }
242
243 pub fn field_text(&self, name: &str) -> Option<&str> {
245 self.get(name).and_then(Read::as_str)
246 }
247
248 pub fn as_i64(&self) -> Option<i64> {
250 match self {
251 Read::Number(text) => text.parse().ok(),
252 _ => None,
253 }
254 }
255
256 pub fn as_bool(&self) -> Option<bool> {
258 match self {
259 Read::Bool(value) => Some(*value),
260 _ => None,
261 }
262 }
263
264 pub fn is_number(&self) -> bool {
266 matches!(self, Read::Number(_))
267 }
268
269 pub fn is_string(&self) -> bool {
271 matches!(self, Read::Text(_))
272 }
273
274 pub fn is_null(&self) -> bool {
276 matches!(self, Read::Null)
277 }
278}
279
280#[derive(Debug, Clone, PartialEq, Eq)]
282pub struct ReadError {
283 pub reason: String,
285 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
298pub 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
312struct Reader<'a> {
314 bytes: &'a [u8],
315 at: usize,
316}
317
318impl Reader<'_> {
319 fn the_error(&self, reason: &str) -> ReadError {
321 ReadError {
322 reason: reason.to_string(),
323 at: self.at,
324 }
325 }
326
327 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 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 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 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 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 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 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 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}