Skip to main content

tap/tooling/
renderable.rs

1use std::{collections::HashMap, error::Error, fmt, sync::Arc};
2
3use string_template::Template;
4
5use crate::tooling::colors::set::colorize;
6
7type RenderScopeT<'a> = HashMap<&'a str, &'a str>;
8type RendererT<'a> = Arc<dyn Fn(&RenderScopeT<'a>) -> Result<String, Box<dyn Error>> + 'a>;
9
10#[derive(Debug)]
11pub enum RenderError {
12    RendererNotFound(String),
13    RendererError(Box<dyn Error>),
14    InvalidValue {
15        key: String,
16        kind: &'static str,
17        value: String,
18    },
19}
20
21impl fmt::Display for RenderError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            Self::RendererNotFound(name) => write!(f, "renderer not found: {name}"),
25            Self::RendererError(err) => write!(f, "renderer error: {err}"),
26            Self::InvalidValue { key, kind, value } => {
27                write!(f, "{key:?}:{kind} has invalid value: {value:?}")
28            }
29        }
30    }
31}
32
33impl Error for RenderError {}
34
35#[derive(Default, Clone)]
36pub struct Renderable<'a> {
37    pub renderers: HashMap<String, RendererT<'a>>,
38    pub scope: RenderScopeT<'a>,
39}
40
41impl<'a> fmt::Debug for Renderable<'a> {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.debug_struct("Renderable")
44            .field("renderers", &self.renderers.keys().collect::<Vec<_>>())
45            .field("scope", &self.scope)
46            .finish()
47    }
48}
49
50#[derive(Clone, Copy)]
51enum Kind {
52    Str,
53    Int,
54    Float,
55    Bool,
56    Raw,
57}
58
59fn split_kind(key: &str) -> (&str, Kind) {
60    if let Some(k) = key.strip_suffix(":int") {
61        (k, Kind::Int)
62    } else if let Some(k) = key.strip_suffix(":float") {
63        (k, Kind::Float)
64    } else if let Some(k) = key.strip_suffix(":bool") {
65        (k, Kind::Bool)
66    } else if let Some(k) = key.strip_suffix(":raw") {
67        (k, Kind::Raw)
68    } else {
69        (key, Kind::Str)
70    }
71}
72
73impl<'a> Renderable<'a> {
74    pub fn new() -> Self {
75        Self::default()
76    }
77
78    pub fn render_json(&self) -> Result<String, RenderError> {
79        let mut items: Vec<(&str, &str, Kind)> = self
80            .scope
81            .iter()
82            .map(|(k, v)| {
83                let (name, kind) = split_kind(k);
84                (name, *v, kind)
85            })
86            .collect();
87        items.sort_by_key(|(name, _, _)| *name);
88
89        let mut out = String::from("{");
90        for (i, (name, value, kind)) in items.into_iter().enumerate() {
91            if i > 0 {
92                out.push(',');
93            }
94            push_json_string(&mut out, name);
95            out.push(':');
96            match kind {
97                Kind::Str => push_json_string(&mut out, value),
98                Kind::Int => {
99                    if !is_json_int(value) {
100                        return Err(RenderError::InvalidValue {
101                            key: name.to_string(),
102                            kind: "int",
103                            value: value.to_string(),
104                        });
105                    }
106                    out.push_str(value);
107                }
108                Kind::Float => {
109                    if !is_json_number(value) {
110                        return Err(RenderError::InvalidValue {
111                            key: name.to_string(),
112                            kind: "float",
113                            value: value.to_string(),
114                        });
115                    }
116                    out.push_str(value);
117                }
118                Kind::Bool => {
119                    if value != "true" && value != "false" {
120                        return Err(RenderError::InvalidValue {
121                            key: name.to_string(),
122                            kind: "bool",
123                            value: value.to_string(),
124                        });
125                    }
126                    out.push_str(value);
127                }
128                Kind::Raw => out.push_str(value),
129            }
130        }
131        out.push('}');
132        Ok(out)
133    }
134
135    pub fn render_with(&self, name: &str) -> Result<String, RenderError> {
136        let renderer = self
137            .renderers
138            .get(name)
139            .ok_or_else(|| RenderError::RendererNotFound(name.to_string()))?;
140
141        let mut scope: RenderScopeT<'a> = HashMap::with_capacity(self.scope.len());
142        for (k, v) in &self.scope {
143            let (key, _) = split_kind(k);
144            scope.insert(key, v);
145        }
146
147        renderer(&scope).map_err(RenderError::RendererError)
148    }
149}
150
151pub fn render_json_array(rows: &[Renderable<'_>]) -> Result<String, RenderError> {
152    let parts: Vec<String> = rows
153        .iter()
154        .map(Renderable::render_json)
155        .collect::<Result<_, _>>()?;
156    Ok(format!("[{}]", parts.join(",")))
157}
158
159pub fn add_template_render<'a>(
160    templ: &'a str,
161    name: impl Into<String>,
162    renderable: &mut Renderable<'a>,
163) {
164    let template = Template::new(templ);
165    let func: RendererT<'a> = Arc::new(
166        move |scope: &RenderScopeT<'a>| -> Result<String, Box<dyn Error>> {
167            Ok(template.render(scope))
168        },
169    );
170    renderable.renderers.insert(name.into(), func);
171}
172
173pub fn add_template_render_colored<'a>(
174    templ: &'a str,
175    name: impl Into<String>,
176    renderable: &mut Renderable<'a>,
177) {
178    let template = Template::new(templ);
179    let func: RendererT<'a> = Arc::new(
180        move |scope: &RenderScopeT<'a>| -> Result<String, Box<dyn Error>> {
181            Ok(colorize(&template.render(scope)))
182        },
183    );
184    renderable.renderers.insert(name.into(), func);
185}
186
187fn push_json_string(out: &mut String, s: &str) {
188    use std::fmt::Write;
189    out.push('"');
190    for c in s.chars() {
191        match c {
192            '"' => out.push_str("\\\""),
193            '\\' => out.push_str("\\\\"),
194            '\n' => out.push_str("\\n"),
195            '\r' => out.push_str("\\r"),
196            '\t' => out.push_str("\\t"),
197            '\u{08}' => out.push_str("\\b"),
198            '\u{0C}' => out.push_str("\\f"),
199            c if (c as u32) < 0x20 => {
200                let _ = write!(out, "\\u{:04x}", c as u32);
201            }
202            c => out.push(c),
203        }
204    }
205    out.push('"');
206}
207
208// JSON int: -?(0|[1-9][0-9]*)
209fn is_json_int(s: &str) -> bool {
210    let b = s.as_bytes();
211    let mut i = 0;
212    if i < b.len() && b[i] == b'-' {
213        i += 1;
214    }
215    match b.get(i) {
216        Some(b'0') => i += 1,
217        Some(c) if c.is_ascii_digit() => {
218            while i < b.len() && b[i].is_ascii_digit() {
219                i += 1;
220            }
221        }
222        _ => return false,
223    }
224    i == b.len()
225}
226
227// JSON number: -?int(\.\d+)?([eE][+-]?\d+)?
228fn is_json_number(s: &str) -> bool {
229    let b = s.as_bytes();
230    let mut i = 0;
231    if i < b.len() && b[i] == b'-' {
232        i += 1;
233    }
234    match b.get(i) {
235        Some(b'0') => i += 1,
236        Some(c) if c.is_ascii_digit() => {
237            while i < b.len() && b[i].is_ascii_digit() {
238                i += 1;
239            }
240        }
241        _ => return false,
242    }
243    if i < b.len() && b[i] == b'.' {
244        i += 1;
245        if i >= b.len() || !b[i].is_ascii_digit() {
246            return false;
247        }
248        while i < b.len() && b[i].is_ascii_digit() {
249            i += 1;
250        }
251    }
252    if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
253        i += 1;
254        if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
255            i += 1;
256        }
257        if i >= b.len() || !b[i].is_ascii_digit() {
258            return false;
259        }
260        while i < b.len() && b[i].is_ascii_digit() {
261            i += 1;
262        }
263    }
264    i == b.len()
265}