Lines
99.64 %
Functions
98.11 %
Branches
100 %
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use super::value::{Fraction, Pair, Value};
use crate::ast::Number;
const BYTES_INLINE_THRESHOLD: usize = 32;
/// How values print: strings quoted and escaped or bare as `princ` does, and
/// a whole scalar as `n/1` or, for a display cell, as `n`.
#[derive(Clone, Copy)]
enum Style {
Readable,
Plain,
Display,
}
#[must_use]
pub fn format_value(value: &Value) -> String {
render(value, Style::Readable)
/// Prints `value` as `PRINT` does: strings bare at every depth.
pub fn format_value_plain(value: &Value) -> String {
render(value, Style::Plain)
/// Prints `value` for a display cell: as the readable form, but a whole
/// scalar as its integer.
pub fn format_value_display(value: &Value) -> String {
render(value, Style::Display)
/// A money amount: an integer when whole, else `n/d`.
pub fn format_amount(amount: Fraction) -> String {
if amount.is_integer() {
amount.numer().to_string()
} else {
format!("{}/{}", amount.numer(), amount.denom())
fn number_text(number: Number, style: Style) -> String {
match (number, style) {
(Number::Scalar(scalar), Style::Display) => format_amount(scalar),
_ => number.to_string(),
fn render(value: &Value, style: Style) -> String {
let mut out = String::new();
write_value(&mut out, value, style);
out
fn write_value(out: &mut String, value: &Value, style: Style) {
match value {
Value::Nil => out.push_str("nil"),
Value::T => out.push('t'),
Value::Number(n) => out.push_str(&number_text(*n, style)),
Value::String(s) => match style {
Style::Readable | Style::Display => write_string_literal(out, s),
Style::Plain => out.push_str(s),
},
Value::Symbol(s) => out.push_str(s),
Value::Bytes(b) => write_bytes_literal(out, b),
Value::Pair(pair) => write_pair_or_list(out, pair, style),
Value::Vector(items) => write_vector(out, items, style),
Value::Closure(c) => match c.code_id {
Some(site) => out.push_str(&format!("#<closure:{site}>")),
None => out.push_str("#<closure>"),
Value::Condition => out.push_str("#<condition>"),
Value::Struct { name, fields } => write_struct(out, name, fields, style),
Value::Commodity {
amount,
commodity_id,
} => {
// Plist envelope keeps the wire shape uniform with native
// results: emacs `(read)` recovers `(:commodity <ratio> :id "<uuid>")`.
out.push_str("(:commodity ");
out.push_str(&format_amount(*amount));
out.push_str(" :id ");
write_value(out, &Value::String(commodity_id.to_string()), style);
out.push(')');
fn write_string_literal(out: &mut String, s: &str) {
out.push('"');
for ch in s.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
other => out.push(other),
fn write_bytes_literal(out: &mut String, bytes: &[u8]) {
if bytes.len() <= BYTES_INLINE_THRESHOLD {
out.push_str("#u8(");
let mut first = true;
for byte in bytes {
if first {
first = false;
out.push(' ');
out.push_str(&byte.to_string());
out.push_str("#\"");
out.push_str(&BASE64_STANDARD.encode(bytes));
fn write_pair_or_list(out: &mut String, pair: &Pair, style: Style) {
out.push('(');
write_value(out, &pair.car, style);
let mut cdr = &pair.cdr;
loop {
match cdr {
Value::Nil => break,
Value::Pair(next) => {
write_value(out, &next.car, style);
cdr = &next.cdr;
other => {
out.push_str(" . ");
write_value(out, other, style);
break;
fn write_vector(out: &mut String, items: &[Value], style: Style) {
out.push_str("#(");
for item in items {
write_value(out, item, style);
fn write_struct(out: &mut String, name: &str, fields: &[(String, Value)], style: Style) {
out.push_str("#S(");
out.push_str(name);
for (field, value) in fields {
out.push_str(" :");
out.push_str(field);
write_value(out, value, style);
#[cfg(test)]
mod tests {
use super::super::value::{Closure, Fraction, Pair};
use super::*;
use crate::ast::{Expr, Number};
use crate::reader::Reader;
#[test]
fn formats_keywords_in_upper_case() {
let plist = Pair::cons(
Value::Symbol(":ROWS".into()),
Pair::cons(Value::Symbol(":HAS-MORE".into()), Value::Nil),
);
assert_eq!(format_value(&plist), "(:ROWS :HAS-MORE)");
fn keeps_plain_symbols_as_stored() {
assert_eq!(format_value(&Value::Symbol("OK".into())), "OK");
fn formats_nil() {
assert_eq!(format_value(&Value::Nil), "nil");
fn formats_t() {
assert_eq!(format_value(&Value::T), "t");
fn a_list_ending_in_nil_prints_as_a_proper_list() {
let list = Pair::cons(Value::Symbol("A".into()), Value::Nil);
assert_eq!(format_value(&list), "(A)");
fn formats_integer_number() {
assert_eq!(format_value(&Value::Number(Number::Index(42))), "42");
fn formats_negative_integer() {
assert_eq!(format_value(&Value::Number(Number::Index(-7))), "-7");
fn formats_proper_fraction() {
assert_eq!(
format_value(&Value::Number(Number::Scalar(Fraction::new(3, 4)))),
"3/4"
fn a_whole_scalar_prints_its_denominator() {
let whole = Value::Number(Number::Scalar(Fraction::from_integer(2)));
assert_eq!(format_value(&whole), "2/1");
assert_eq!(format_value_plain(&whole), "2/1");
fn a_display_cell_prints_a_whole_scalar_as_an_integer() {
let whole = Value::Number(Number::Scalar(Fraction::from_integer(100)));
let list = Pair::cons(
whole.clone(),
Pair::cons(Value::Number(Number::Index(3)), Value::Nil),
assert_eq!(format_value_display(&whole), "100");
assert_eq!(format_value_display(&list), "(100 3)");
let fraction = Value::Number(Number::Scalar(Fraction::new(1, 4)));
assert_eq!(format_value_display(&fraction), "1/4");
assert_eq!(format_value_display(&Value::String("a".into())), "\"a\"");
fn formats_string_with_escapes() {
let v = Value::String("a\nb\"c\\d".to_string());
assert_eq!(format_value(&v), "\"a\\nb\\\"c\\\\d\"");
fn formats_symbol_verbatim() {
assert_eq!(format_value(&Value::Symbol("FOO".into())), "FOO");
fn formats_short_bytes_as_u8_literal() {
let v = Value::Bytes(vec![0, 1, 255]);
assert_eq!(format_value(&v), "#u8(0 1 255)");
fn formats_empty_bytes_as_u8_literal() {
assert_eq!(format_value(&Value::Bytes(Vec::new())), "#u8()");
fn formats_bytes_at_inline_threshold() {
let bytes: Vec<u8> = (0..BYTES_INLINE_THRESHOLD as u8).collect();
let formatted = format_value(&Value::Bytes(bytes.clone()));
assert!(formatted.starts_with("#u8("));
assert!(formatted.ends_with(')'));
fn formats_long_bytes_as_base64_literal() {
let bytes: Vec<u8> = (0..=BYTES_INLINE_THRESHOLD as u8).collect();
assert!(formatted.starts_with("#\""));
assert!(formatted.ends_with('"'));
let payload = &formatted[2..formatted.len() - 1];
let decoded = BASE64_STANDARD.decode(payload).unwrap();
assert_eq!(decoded, bytes);
fn formats_proper_list() {
Value::Number(Number::Index(1)),
Pair::cons(
Value::Number(Number::Index(2)),
),
assert_eq!(format_value(&list), "(1 2 3)");
fn formats_dotted_pair() {
let pair = Pair::cons(Value::Symbol("A".into()), Value::Symbol("B".into()));
assert_eq!(format_value(&pair), "(A . B)");
fn formats_improper_list() {
Value::Number(Number::Index(3)),
assert_eq!(format_value(&list), "(1 2 . 3)");
fn formats_vector() {
let v = Value::Vector(vec![Value::Number(Number::Index(1)), Value::T]);
assert_eq!(format_value(&v), "#(1 t)");
fn formats_closure() {
let c = Value::Closure(Closure::new(7, vec![]));
assert_eq!(format_value(&c), "#<closure:7>");
fn formats_siteless_closure() {
let c = Value::Closure(Closure::siteless());
assert_eq!(format_value(&c), "#<closure>");
fn formats_struct() {
let s = Value::Struct {
name: "ACCOUNT".into(),
fields: vec![("ID".into(), Value::Number(Number::Index(42)))],
};
assert_eq!(format_value(&s), "#S(ACCOUNT :ID 42)");
fn round_trip_short_bytes_through_reader() {
let v = Value::Bytes(vec![0xCA, 0xFE, 0xBA, 0xBE]);
let formatted = format_value(&v);
let parsed = Reader::parse(&formatted).unwrap();
parsed.exprs,
vec![Expr::Bytes(vec![0xCA, 0xFE, 0xBA, 0xBE])]
fn round_trip_long_bytes_through_reader() {
let bytes: Vec<u8> = (0..=255).chain(0..=255).collect();
assert_eq!(parsed.exprs, vec![Expr::Bytes(bytes)]);
fn round_trip_full_byte_range_through_reader() {
let bytes: Vec<u8> = (0..=255).collect();
fn round_trip_rational_through_reader() {
for (num, den) in [(1i64, 2i64), (-3, 4), (1, 3), (7, 11)] {
let v = Value::Number(Number::Scalar(Fraction::new(num, den)));
vec![Expr::Number(Number::Scalar(Fraction::new(num, den)))]
fn plain_style_prints_the_commodity_id_bare() {
let money = Value::Commodity {
amount: Fraction::from_integer(3),
commodity_id: uuid::Uuid::nil(),
let id = "00000000-0000-0000-0000-000000000000";
format_value_plain(&money),
format!("(:commodity 3 :id {id})")
assert_eq!(format_value(&money), format!("(:commodity 3 :id \"{id}\")"));
fn plain_style_prints_strings_bare_at_every_depth() {
Value::String("a\"b".into()),
Pair::cons(Value::Number(Number::Index(1)), Value::Nil),
assert_eq!(format_value_plain(&list), "(a\"b 1)");
assert_eq!(format_value(&list), "(\"a\\\"b\" 1)");