1use base64::Engine;
2use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
3
4use super::value::{Fraction, Pair, Value};
5use crate::ast::Number;
6
7const BYTES_INLINE_THRESHOLD: usize = 32;
8
9#[derive(Clone, Copy)]
12enum Style {
13 Readable,
14 Plain,
15 Display,
16}
17
18#[must_use]
19pub fn format_value(value: &Value) -> String {
20 render(value, Style::Readable)
21}
22
23#[must_use]
25pub fn format_value_plain(value: &Value) -> String {
26 render(value, Style::Plain)
27}
28
29#[must_use]
32pub fn format_value_display(value: &Value) -> String {
33 render(value, Style::Display)
34}
35
36#[must_use]
38pub fn format_amount(amount: Fraction) -> String {
39 if amount.is_integer() {
40 amount.numer().to_string()
41 } else {
42 format!("{}/{}", amount.numer(), amount.denom())
43 }
44}
45
46fn number_text(number: Number, style: Style) -> String {
47 match (number, style) {
48 (Number::Scalar(scalar), Style::Display) => format_amount(scalar),
49 _ => number.to_string(),
50 }
51}
52
53fn render(value: &Value, style: Style) -> String {
54 let mut out = String::new();
55 write_value(&mut out, value, style);
56 out
57}
58
59fn write_value(out: &mut String, value: &Value, style: Style) {
60 match value {
61 Value::Nil => out.push_str("nil"),
62 Value::T => out.push('t'),
63 Value::Number(n) => out.push_str(&number_text(*n, style)),
64 Value::String(s) => match style {
65 Style::Readable | Style::Display => write_string_literal(out, s),
66 Style::Plain => out.push_str(s),
67 },
68 Value::Symbol(s) => out.push_str(s),
69 Value::Bytes(b) => write_bytes_literal(out, b),
70 Value::Pair(pair) => write_pair_or_list(out, pair, style),
71 Value::Vector(items) => write_vector(out, items, style),
72 Value::Closure(c) => match c.code_id {
73 Some(site) => out.push_str(&format!("#<closure:{site}>")),
74 None => out.push_str("#<closure>"),
75 },
76 Value::Condition => out.push_str("#<condition>"),
77 Value::Struct { name, fields } => write_struct(out, name, fields, style),
78 Value::Commodity {
79 amount,
80 commodity_id,
81 } => {
82 out.push_str("(:commodity ");
85 out.push_str(&format_amount(*amount));
86 out.push_str(" :id ");
87 write_value(out, &Value::String(commodity_id.to_string()), style);
88 out.push(')');
89 }
90 }
91}
92
93fn write_string_literal(out: &mut String, s: &str) {
94 out.push('"');
95 for ch in s.chars() {
96 match ch {
97 '\\' => out.push_str("\\\\"),
98 '"' => out.push_str("\\\""),
99 '\n' => out.push_str("\\n"),
100 '\t' => out.push_str("\\t"),
101 '\r' => out.push_str("\\r"),
102 other => out.push(other),
103 }
104 }
105 out.push('"');
106}
107
108fn write_bytes_literal(out: &mut String, bytes: &[u8]) {
109 if bytes.len() <= BYTES_INLINE_THRESHOLD {
110 out.push_str("#u8(");
111 let mut first = true;
112 for byte in bytes {
113 if first {
114 first = false;
115 } else {
116 out.push(' ');
117 }
118 out.push_str(&byte.to_string());
119 }
120 out.push(')');
121 } else {
122 out.push_str("#\"");
123 out.push_str(&BASE64_STANDARD.encode(bytes));
124 out.push('"');
125 }
126}
127
128fn write_pair_or_list(out: &mut String, pair: &Pair, style: Style) {
129 out.push('(');
130 write_value(out, &pair.car, style);
131 let mut cdr = &pair.cdr;
132 loop {
133 match cdr {
134 Value::Nil => break,
135 Value::Pair(next) => {
136 out.push(' ');
137 write_value(out, &next.car, style);
138 cdr = &next.cdr;
139 }
140 other => {
141 out.push_str(" . ");
142 write_value(out, other, style);
143 break;
144 }
145 }
146 }
147 out.push(')');
148}
149
150fn write_vector(out: &mut String, items: &[Value], style: Style) {
151 out.push_str("#(");
152 let mut first = true;
153 for item in items {
154 if first {
155 first = false;
156 } else {
157 out.push(' ');
158 }
159 write_value(out, item, style);
160 }
161 out.push(')');
162}
163
164fn write_struct(out: &mut String, name: &str, fields: &[(String, Value)], style: Style) {
165 out.push_str("#S(");
166 out.push_str(name);
167 for (field, value) in fields {
168 out.push_str(" :");
169 out.push_str(field);
170 out.push(' ');
171 write_value(out, value, style);
172 }
173 out.push(')');
174}
175
176#[cfg(test)]
177mod tests {
178 use super::super::value::{Closure, Fraction, Pair};
179 use super::*;
180 use crate::ast::{Expr, Number};
181 use crate::reader::Reader;
182
183 #[test]
184 fn formats_keywords_in_upper_case() {
185 let plist = Pair::cons(
186 Value::Symbol(":ROWS".into()),
187 Pair::cons(Value::Symbol(":HAS-MORE".into()), Value::Nil),
188 );
189 assert_eq!(format_value(&plist), "(:ROWS :HAS-MORE)");
190 }
191
192 #[test]
193 fn keeps_plain_symbols_as_stored() {
194 assert_eq!(format_value(&Value::Symbol("OK".into())), "OK");
195 }
196
197 #[test]
198 fn formats_nil() {
199 assert_eq!(format_value(&Value::Nil), "nil");
200 }
201
202 #[test]
203 fn formats_t() {
204 assert_eq!(format_value(&Value::T), "t");
205 }
206
207 #[test]
208 fn a_list_ending_in_nil_prints_as_a_proper_list() {
209 let list = Pair::cons(Value::Symbol("A".into()), Value::Nil);
210 assert_eq!(format_value(&list), "(A)");
211 }
212
213 #[test]
214 fn formats_integer_number() {
215 assert_eq!(format_value(&Value::Number(Number::Index(42))), "42");
216 }
217
218 #[test]
219 fn formats_negative_integer() {
220 assert_eq!(format_value(&Value::Number(Number::Index(-7))), "-7");
221 }
222
223 #[test]
224 fn formats_proper_fraction() {
225 assert_eq!(
226 format_value(&Value::Number(Number::Scalar(Fraction::new(3, 4)))),
227 "3/4"
228 );
229 }
230
231 #[test]
232 fn a_whole_scalar_prints_its_denominator() {
233 let whole = Value::Number(Number::Scalar(Fraction::from_integer(2)));
234 assert_eq!(format_value(&whole), "2/1");
235 assert_eq!(format_value_plain(&whole), "2/1");
236 }
237
238 #[test]
239 fn a_display_cell_prints_a_whole_scalar_as_an_integer() {
240 let whole = Value::Number(Number::Scalar(Fraction::from_integer(100)));
241 let list = Pair::cons(
242 whole.clone(),
243 Pair::cons(Value::Number(Number::Index(3)), Value::Nil),
244 );
245 assert_eq!(format_value_display(&whole), "100");
246 assert_eq!(format_value_display(&list), "(100 3)");
247 let fraction = Value::Number(Number::Scalar(Fraction::new(1, 4)));
248 assert_eq!(format_value_display(&fraction), "1/4");
249 assert_eq!(format_value_display(&Value::String("a".into())), "\"a\"");
250 }
251
252 #[test]
253 fn formats_string_with_escapes() {
254 let v = Value::String("a\nb\"c\\d".to_string());
255 assert_eq!(format_value(&v), "\"a\\nb\\\"c\\\\d\"");
256 }
257
258 #[test]
259 fn formats_symbol_verbatim() {
260 assert_eq!(format_value(&Value::Symbol("FOO".into())), "FOO");
261 }
262
263 #[test]
264 fn formats_short_bytes_as_u8_literal() {
265 let v = Value::Bytes(vec![0, 1, 255]);
266 assert_eq!(format_value(&v), "#u8(0 1 255)");
267 }
268
269 #[test]
270 fn formats_empty_bytes_as_u8_literal() {
271 assert_eq!(format_value(&Value::Bytes(Vec::new())), "#u8()");
272 }
273
274 #[test]
275 fn formats_bytes_at_inline_threshold() {
276 let bytes: Vec<u8> = (0..BYTES_INLINE_THRESHOLD as u8).collect();
277 let formatted = format_value(&Value::Bytes(bytes.clone()));
278 assert!(formatted.starts_with("#u8("));
279 assert!(formatted.ends_with(')'));
280 }
281
282 #[test]
283 fn formats_long_bytes_as_base64_literal() {
284 let bytes: Vec<u8> = (0..=BYTES_INLINE_THRESHOLD as u8).collect();
285 let formatted = format_value(&Value::Bytes(bytes.clone()));
286 assert!(formatted.starts_with("#\""));
287 assert!(formatted.ends_with('"'));
288 let payload = &formatted[2..formatted.len() - 1];
289 let decoded = BASE64_STANDARD.decode(payload).unwrap();
290 assert_eq!(decoded, bytes);
291 }
292
293 #[test]
294 fn formats_proper_list() {
295 let list = Pair::cons(
296 Value::Number(Number::Index(1)),
297 Pair::cons(
298 Value::Number(Number::Index(2)),
299 Pair::cons(Value::Number(Number::Index(3)), Value::Nil),
300 ),
301 );
302 assert_eq!(format_value(&list), "(1 2 3)");
303 }
304
305 #[test]
306 fn formats_dotted_pair() {
307 let pair = Pair::cons(Value::Symbol("A".into()), Value::Symbol("B".into()));
308 assert_eq!(format_value(&pair), "(A . B)");
309 }
310
311 #[test]
312 fn formats_improper_list() {
313 let list = Pair::cons(
314 Value::Number(Number::Index(1)),
315 Pair::cons(
316 Value::Number(Number::Index(2)),
317 Value::Number(Number::Index(3)),
318 ),
319 );
320 assert_eq!(format_value(&list), "(1 2 . 3)");
321 }
322
323 #[test]
324 fn formats_vector() {
325 let v = Value::Vector(vec![Value::Number(Number::Index(1)), Value::T]);
326 assert_eq!(format_value(&v), "#(1 t)");
327 }
328
329 #[test]
330 fn formats_closure() {
331 let c = Value::Closure(Closure::new(7, vec![]));
332 assert_eq!(format_value(&c), "#<closure:7>");
333 }
334
335 #[test]
336 fn formats_siteless_closure() {
337 let c = Value::Closure(Closure::siteless());
338 assert_eq!(format_value(&c), "#<closure>");
339 }
340
341 #[test]
342 fn formats_struct() {
343 let s = Value::Struct {
344 name: "ACCOUNT".into(),
345 fields: vec![("ID".into(), Value::Number(Number::Index(42)))],
346 };
347 assert_eq!(format_value(&s), "#S(ACCOUNT :ID 42)");
348 }
349
350 #[test]
351 fn round_trip_short_bytes_through_reader() {
352 let v = Value::Bytes(vec![0xCA, 0xFE, 0xBA, 0xBE]);
353 let formatted = format_value(&v);
354 let parsed = Reader::parse(&formatted).unwrap();
355 assert_eq!(
356 parsed.exprs,
357 vec![Expr::Bytes(vec![0xCA, 0xFE, 0xBA, 0xBE])]
358 );
359 }
360
361 #[test]
362 fn round_trip_long_bytes_through_reader() {
363 let bytes: Vec<u8> = (0..=255).chain(0..=255).collect();
364 let formatted = format_value(&Value::Bytes(bytes.clone()));
365 let parsed = Reader::parse(&formatted).unwrap();
366 assert_eq!(parsed.exprs, vec![Expr::Bytes(bytes)]);
367 }
368
369 #[test]
370 fn round_trip_full_byte_range_through_reader() {
371 let bytes: Vec<u8> = (0..=255).collect();
372 let formatted = format_value(&Value::Bytes(bytes.clone()));
373 let parsed = Reader::parse(&formatted).unwrap();
374 assert_eq!(parsed.exprs, vec![Expr::Bytes(bytes)]);
375 }
376
377 #[test]
378 fn round_trip_rational_through_reader() {
379 for (num, den) in [(1i64, 2i64), (-3, 4), (1, 3), (7, 11)] {
380 let v = Value::Number(Number::Scalar(Fraction::new(num, den)));
381 let formatted = format_value(&v);
382 let parsed = Reader::parse(&formatted).unwrap();
383 assert_eq!(
384 parsed.exprs,
385 vec![Expr::Number(Number::Scalar(Fraction::new(num, den)))]
386 );
387 }
388 }
389
390 #[test]
391 fn plain_style_prints_the_commodity_id_bare() {
392 let money = Value::Commodity {
393 amount: Fraction::from_integer(3),
394 commodity_id: uuid::Uuid::nil(),
395 };
396 let id = "00000000-0000-0000-0000-000000000000";
397 assert_eq!(
398 format_value_plain(&money),
399 format!("(:commodity 3 :id {id})")
400 );
401 assert_eq!(format_value(&money), format!("(:commodity 3 :id \"{id}\")"));
402 }
403
404 #[test]
405 fn plain_style_prints_strings_bare_at_every_depth() {
406 let list = Pair::cons(
407 Value::String("a\"b".into()),
408 Pair::cons(Value::Number(Number::Index(1)), Value::Nil),
409 );
410 assert_eq!(format_value_plain(&list), "(a\"b 1)");
411 assert_eq!(format_value(&list), "(\"a\\\"b\" 1)");
412 }
413}