Skip to main content

rtb_tui/
render.rs

1//! `render_table` / `render_json` — uniform structured-output
2//! helpers consumed by the v0.4 `--output text|json` flag.
3
4use serde::Serialize;
5use tabled::settings::Style;
6use tabled::{Table, Tabled};
7
8use crate::error::RenderError;
9
10/// Render `rows` as a `tabled` text table with the canonical v0.1
11/// style. Returns the rendered string with a trailing newline so
12/// callers can `print!` directly.
13///
14/// The style is fixed at v0.1 (psql-equivalent). Theming is a v0.2+
15/// concern — see W2 in the spec.
16#[must_use]
17pub fn render_table<R: Tabled>(rows: &[R]) -> String {
18    let mut table = Table::new(rows);
19    table.with(Style::psql());
20    let mut s = table.to_string();
21    if !s.ends_with('\n') {
22        s.push('\n');
23    }
24    s
25}
26
27/// Render `rows` as a pretty-printed JSON array (one element per
28/// row, two-space indent, trailing newline).
29///
30/// # Errors
31///
32/// [`RenderError::Json`] when any row fails to serialise — typical
33/// causes are non-string `Map` keys or non-finite floats. Always
34/// programmer mistake; payload is a stringified `serde_json::Error`.
35pub fn render_json<R: Serialize>(rows: &[R]) -> Result<String, RenderError> {
36    let mut out =
37        serde_json::to_string_pretty(rows).map_err(|e| RenderError::Json(e.to_string()))?;
38    out.push('\n');
39    Ok(out)
40}