#[derive(Clone, Copy, Debug)]
pub struct DumpOptions {
pub precision: usize,
pub max_rows: usize,
pub max_cols: usize,
}
impl Default for DumpOptions {
fn default() -> Self {
Self {
precision: 3,
max_rows: 20,
max_cols: 12,
}
}
}
pub trait Dump {
fn render(&self, opts: &DumpOptions) -> String;
fn dump(&self) {
self.dump_with(&DumpOptions::default());
}
fn dump_with(&self, opts: &DumpOptions) {
println!("{}", self.render(opts));
}
}
#[cfg(feature = "python-api")]
pub fn py_print(py: pyo3::Python<'_>, text: &str) -> pyo3::PyResult<()> {
use pyo3::types::PyAnyMethods;
py.import("builtins")?.call_method1("print", (text,))?;
Ok(())
}
pub fn fmt_float(v: f64, precision: usize) -> String {
format!("{:.*}", precision, v)
}
pub fn table(headers: &[String], rows: &[Vec<String>], opts: &DumpOptions) -> String {
let ncol = headers.len();
if ncol == 0 {
return String::new();
}
let value_cols = ncol - 1;
let shown_value_cols = value_cols.min(opts.max_cols);
let col_truncated = value_cols > shown_value_cols;
let shown_cols = 1 + shown_value_cols;
let shown_rows = rows.len().min(opts.max_rows);
let row_truncated = rows.len() > shown_rows;
let mut grid: Vec<Vec<String>> = Vec::with_capacity(shown_rows + 2);
let build_line = |src: &[String]| -> Vec<String> {
let mut line: Vec<String> = src[..shown_cols].to_vec();
if col_truncated {
line.push("…".to_string());
}
line
};
grid.push(build_line(headers));
for r in &rows[..shown_rows] {
grid.push(build_line(r));
}
if row_truncated {
let n = if col_truncated {
shown_cols + 1
} else {
shown_cols
};
grid.push(vec!["⋮".to_string(); n]);
}
let cols = grid[0].len();
let mut widths = vec![0usize; cols];
for line in &grid {
for (i, cell) in line.iter().enumerate() {
widths[i] = widths[i].max(cell.chars().count());
}
}
let mut out = String::new();
for line in &grid {
for (i, cell) in line.iter().enumerate() {
if i > 0 {
out.push_str(" ");
}
for _ in 0..widths[i] - cell.chars().count() {
out.push(' ');
}
out.push_str(cell);
}
out.push('\n');
}
if row_truncated {
out.push_str(&format!(
"… ({} ligne(s) de plus)\n",
rows.len() - shown_rows
));
}
if col_truncated {
out.push_str(&format!(
"… ({} colonne(s) de plus)\n",
value_cols - shown_value_cols
));
}
out
}
pub fn labeled_grid(
row_labels: &[String],
col_labels: &[String],
data: &[f64],
opts: &DumpOptions,
) -> String {
let nc = col_labels.len();
let mut headers = Vec::with_capacity(nc + 1);
headers.push(String::new()); headers.extend(col_labels.iter().cloned());
let rows: Vec<Vec<String>> = row_labels
.iter()
.enumerate()
.map(|(i, rl)| {
let mut line = Vec::with_capacity(nc + 1);
line.push(rl.clone());
for j in 0..nc {
line.push(fmt_float(data[i * nc + j], opts.precision));
}
line
})
.collect();
table(&headers, &rows, opts)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn small_labeled_grid_aligns() {
let rows = vec!["(n1,q)".into(), "(n2,q)".into()];
let cols = vec!["(n1,T)".into(), "(n2,T)".into()];
let data = vec![2.0, -1.0, -1.0, 2.0];
let s = labeled_grid(&rows, &cols, &data, &DumpOptions::default());
let expected = concat!(
" (n1,T) (n2,T)\n",
"(n1,q) 2.000 -1.000\n",
"(n2,q) -1.000 2.000\n",
);
assert_eq!(s, expected);
}
#[test]
fn row_elision_marks_overflow() {
let headers = vec!["node".into(), "T".into()];
let rows: Vec<Vec<String>> = (0..5)
.map(|i| vec![i.to_string(), format!("{i}.0")])
.collect();
let opts = DumpOptions {
precision: 1,
max_rows: 2,
max_cols: 12,
};
let s = table(&headers, &rows, &opts);
assert!(s.contains("⋮"), "expected an elision cue row:\n{s}");
assert!(
s.contains("3 ligne(s) de plus"),
"expected a row note:\n{s}"
);
}
#[test]
fn col_elision_keeps_label_column() {
let headers: Vec<String> = std::iter::once("node".to_string())
.chain((0..4).map(|c| format!("c{c}")))
.collect();
let rows = vec![vec![
"n0".into(),
"1".into(),
"2".into(),
"3".into(),
"4".into(),
]];
let opts = DumpOptions {
precision: 1,
max_rows: 20,
max_cols: 2,
};
let s = table(&headers, &rows, &opts);
assert!(s.contains("node"), "label column must survive:\n{s}");
assert!(
s.contains("2 colonne(s) de plus"),
"expected a column note:\n{s}"
);
}
#[test]
fn default_render_uses_default_options() {
struct One;
impl Dump for One {
fn render(&self, o: &DumpOptions) -> String {
fmt_float(1.0, o.precision)
}
}
assert_eq!(One.render(&DumpOptions::default()), "1.000");
}
}