Skip to main content

jjpwrgem_parse/
format.rs

1mod prettify;
2#[cfg(feature = "serde")]
3pub mod serde;
4pub(crate) mod uglify;
5
6pub use prettify::{prettify_document, prettify_document_into, prettify_str};
7pub use uglify::{uglify_document, uglify_document_into, uglify_str, uglify_str_into};
8
9use crate::tokens::{FALSE, NULL, TRUE};
10
11pub(crate) fn join_into<T, B>(
12    buf: &mut B,
13    items: impl IntoIterator<Item = T>,
14    mut item_fmt: impl FnMut(&mut B, &T),
15    mut delim_fmt: impl FnMut(&mut B, &T),
16) {
17    let mut iter = items.into_iter();
18    if let Some(first) = iter.next() {
19        item_fmt(buf, &first);
20        for item in iter {
21            delim_fmt(buf, &item);
22            item_fmt(buf, &item);
23        }
24    }
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum LineEnding {
29    Lf,
30    CrLf,
31    Cr,
32}
33
34impl LineEnding {
35    pub const fn as_str(self) -> &'static str {
36        match self {
37            Self::Lf => "\n",
38            Self::CrLf => "\r\n",
39            Self::Cr => "\r",
40        }
41    }
42}
43
44pub(crate) trait Emitter {
45    fn push(&mut self, c: char);
46    fn push_str(&mut self, s: &str);
47
48    // defaults
49    fn push_quoted(&mut self, s: &str) {
50        self.push('"');
51        self.push_str(s);
52        self.push('"');
53    }
54
55    fn emit_null(&mut self) {
56        self.push_str(NULL);
57    }
58    fn emit_string(&mut self, s: &str) {
59        self.push_quoted(s);
60    }
61    fn emit_mantissa(&mut self, n: &str) {
62        self.push_str(n);
63    }
64    fn emit_exponent(&mut self, e: &str) {
65        self.push('e');
66        self.push_str(e);
67    }
68    fn emit_boolean(&mut self, b: bool) {
69        self.push_str(if b { TRUE } else { FALSE });
70    }
71    fn emit_item_delim(&mut self) {
72        self.push(',');
73    }
74    fn emit_array_open(&mut self) {
75        self.push('[');
76    }
77    fn emit_array_close(&mut self) {
78        self.push(']');
79    }
80    fn emit_object_open(&mut self) {
81        self.push('{');
82    }
83    fn emit_object_close(&mut self) {
84        self.push('}');
85    }
86    fn emit_key_val_delim(&mut self) {
87        self.push(':');
88    }
89}