Skip to main content

vitrify_cli/
out.rs

1//! The single output module: stdout is data, stderr is diagnostics —
2//! everywhere, no exceptions. JSON emitters match
3//! the golden corpus' output formats byte for byte: non-ASCII escaped as `\uXXXX`,
4//! separators `(", ", ": ")` on the single-line form, or two-space indent
5//! with separators `(",", ": ")`. Normative JSON is built from ordered
6//! pairs, never from maps (Conventions).
7
8/// Ordered JSON value — insertion-ordered objects for byte-stable output.
9#[derive(Debug, Clone, PartialEq)]
10pub enum J {
11    Null,
12    Bool(bool),
13    Int(i64),
14    Str(String),
15    Arr(Vec<J>),
16    Obj(Vec<(String, J)>),
17}
18
19impl J {
20    pub fn s(v: impl Into<String>) -> J {
21        J::Str(v.into())
22    }
23
24    pub fn opt_str(v: Option<String>) -> J {
25        match v {
26            Some(s) => J::Str(s),
27            None => J::Null,
28        }
29    }
30
31    /// A value read back from JSON. Objects keep the order the reader gives
32    /// (`serde_json` sorts keys); a number that is not an integer becomes its
33    /// text, since nothing vitrify writes has one.
34    pub fn from_value(v: &serde_json::Value) -> J {
35        use serde_json::Value;
36        match v {
37            Value::Null => J::Null,
38            Value::Bool(b) => J::Bool(*b),
39            Value::Number(n) => n
40                .as_i64()
41                .map(J::Int)
42                .unwrap_or_else(|| J::Str(n.to_string())),
43            Value::String(s) => J::Str(s.clone()),
44            Value::Array(items) => J::Arr(items.iter().map(J::from_value).collect()),
45            Value::Object(map) => J::Obj(
46                map.iter()
47                    .map(|(k, v)| (k.clone(), J::from_value(v)))
48                    .collect(),
49            ),
50        }
51    }
52
53    /// Two-space-indented form: separators `(",", ": ")`, non-ASCII escaped.
54    pub fn dumps_indent2(&self) -> String {
55        let mut out = String::new();
56        write_indent(self, 0, &mut out);
57        out
58    }
59
60    /// Single-line form — separators `(", ", ": ")`, non-ASCII escaped.
61    pub fn dumps_default(&self) -> String {
62        let mut out = String::new();
63        write_compact(self, ", ", ": ", &mut out);
64        out
65    }
66}
67
68fn escape_json_ascii(s: &str, out: &mut String) {
69    out.push('"');
70    for c in s.chars() {
71        match c {
72            '"' => out.push_str("\\\""),
73            '\\' => out.push_str("\\\\"),
74            '\n' => out.push_str("\\n"),
75            '\r' => out.push_str("\\r"),
76            '\t' => out.push_str("\\t"),
77            '\u{08}' => out.push_str("\\b"),
78            '\u{0c}' => out.push_str("\\f"),
79            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
80            c if (c as u32) < 0x7f => out.push(c),
81            c => {
82                // ensure_ascii: \uXXXX, surrogate pairs for astral chars
83                let cp = c as u32;
84                if cp <= 0xffff {
85                    out.push_str(&format!("\\u{cp:04x}"));
86                } else {
87                    let v = cp - 0x10000;
88                    out.push_str(&format!(
89                        "\\u{:04x}\\u{:04x}",
90                        0xd800 + (v >> 10),
91                        0xdc00 + (v & 0x3ff)
92                    ));
93                }
94            }
95        }
96    }
97    out.push('"');
98}
99
100fn write_compact(v: &J, item_sep: &str, kv_sep: &str, out: &mut String) {
101    match v {
102        J::Null => out.push_str("null"),
103        J::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
104        J::Int(i) => out.push_str(&i.to_string()),
105        J::Str(s) => escape_json_ascii(s, out),
106        J::Arr(items) => {
107            out.push('[');
108            for (i, item) in items.iter().enumerate() {
109                if i > 0 {
110                    out.push_str(item_sep);
111                }
112                write_compact(item, item_sep, kv_sep, out);
113            }
114            out.push(']');
115        }
116        J::Obj(pairs) => {
117            out.push('{');
118            for (i, (k, val)) in pairs.iter().enumerate() {
119                if i > 0 {
120                    out.push_str(item_sep);
121                }
122                escape_json_ascii(k, out);
123                out.push_str(kv_sep);
124                write_compact(val, item_sep, kv_sep, out);
125            }
126            out.push('}');
127        }
128    }
129}
130
131fn write_indent(v: &J, level: usize, out: &mut String) {
132    let pad = "  ".repeat(level + 1);
133    let close_pad = "  ".repeat(level);
134    match v {
135        J::Arr(items) if !items.is_empty() => {
136            out.push_str("[\n");
137            for (i, item) in items.iter().enumerate() {
138                if i > 0 {
139                    out.push_str(",\n");
140                }
141                out.push_str(&pad);
142                write_indent(item, level + 1, out);
143            }
144            out.push('\n');
145            out.push_str(&close_pad);
146            out.push(']');
147        }
148        J::Obj(pairs) if !pairs.is_empty() => {
149            out.push_str("{\n");
150            for (i, (k, val)) in pairs.iter().enumerate() {
151                if i > 0 {
152                    out.push_str(",\n");
153                }
154                out.push_str(&pad);
155                escape_json_ascii(k, out);
156                out.push_str(": ");
157                write_indent(val, level + 1, out);
158            }
159            out.push('\n');
160            out.push_str(&close_pad);
161            out.push('}');
162        }
163        other => write_compact(other, ", ", ": ", out),
164    }
165}
166
167/// Data to stdout. A stream that has gone away (a closed pipe, a terminal
168/// that hung up) is not a reason to stop: a run that loses its terminal
169/// still has claims to release.
170pub fn emit(data: &str) {
171    use std::io::Write;
172    let _ = writeln!(std::io::stdout().lock(), "{data}");
173}
174
175/// Data to stdout, flushed at once, for output someone watches line by line.
176/// `false` when stdout has gone away (a closed pipe, as with `| head`): a
177/// reader that only watches has no reason to go on.
178pub fn emit_checked(data: &str) -> bool {
179    use std::io::Write;
180    let mut out = std::io::stdout().lock();
181    writeln!(out, "{data}").and_then(|()| out.flush()).is_ok()
182}
183
184/// Diagnostics to stderr.
185pub fn diag(msg: &str) {
186    use std::io::Write;
187    let _ = writeln!(std::io::stderr().lock(), "{msg}");
188}