logicaffeine_compile/semantics/
format.rs1use crate::interpreter::RuntimeValue;
4
5pub fn apply_format_spec(val: &RuntimeValue, spec: &str) -> String {
7 if spec == "$" {
9 if let RuntimeValue::BigInt(b) = val {
12 return format!("${}.00", b);
13 }
14 let f = match val {
15 RuntimeValue::Float(f) => *f,
16 RuntimeValue::Int(n) => *n as f64,
17 _ => return format!("${}", val.to_display_string()),
18 };
19 return format!("${:.2}", f);
20 }
21 if spec.starts_with('.') {
23 if let Ok(precision) = spec[1..].parse::<usize>() {
24 match val {
25 RuntimeValue::Float(f) => return format!("{:.prec$}", f, prec = precision),
26 RuntimeValue::Int(n) => return format!("{:.prec$}", *n as f64, prec = precision),
27 RuntimeValue::BigInt(b) => {
28 return format!("{:.prec$}", b.to_f64(), prec = precision)
29 }
30 _ => return val.to_display_string(),
31 }
32 }
33 }
34 if spec.len() >= 2 {
36 let first = spec.as_bytes()[0];
37 if first == b'>' || first == b'<' || first == b'^' {
38 if let Ok(width) = spec[1..].parse::<usize>() {
39 let s = val.to_display_string();
40 return match first {
41 b'>' => format!("{:>w$}", s, w = width),
42 b'<' => format!("{:<w$}", s, w = width),
43 b'^' => format!("{:^w$}", s, w = width),
44 _ => unreachable!(),
45 };
46 }
47 }
48 }
49 if let Ok(width) = spec.parse::<usize>() {
51 let s = val.to_display_string();
52 return format!("{:>w$}", s, w = width);
53 }
54 val.to_display_string()
55}