1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
// Copyright (c) tabular-rs Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
use crate::{
column_spec::{parse_row_spec, row_spec_to_string, ColumnSpec},
error::Result,
row::{InternalRow, Row},
width_string::WidthString,
};
use std::fmt::{Debug, Display, Formatter};
/// Builder type for constructing a formatted table.
///
/// Construct this with [`Table::new()`] or [`Table::new_safe()`]. Then add rows
/// to it with [`Table::add_row()`] and [`Table::add_heading()`].
///
/// [`Table::new_safe()`]: struct.Table.html#method.new_safe
/// [`Table::new()`]: struct.Table.html#method.new
/// [`Table::add_row()`]: struct.Table.html#method.add_row
/// [`Table::add_heading()`]: struct.Table.html#method.add_heading
#[derive(Clone)]
pub struct Table {
n_columns: usize,
format: Vec<ColumnSpec>,
rows: Vec<InternalRow>,
column_widths: Vec<usize>,
line_end: String,
}
const DEFAULT_LINE_END: &str = "\n";
impl Table {
/// Constructs a new table with the format of each row specified by `row_spec`.
///
/// Unlike `format!` and friends, `row_spec` is processed dynamically, but it uses a small
/// subset of the syntax to determine how columns are laid out. In particular:
///
/// - `{:<}` produces a left-aligned column.
///
/// - `{:^}` produces a centered column.
///
/// - `{:>}` produces a right-aligned column.
///
/// - `{{` produces a literal `{` character.
///
/// - `}}` produces a literal `}` character.
///
/// - Any other appearances of `{` or `}` are errors.
///
/// - Everything else stands for itself.
///
/// # Examples
///
/// ```
/// # use tabular::*;
/// let table = Table::new("{{:<}} produces ‘{:<}’ and {{:>}} produces ‘{:>}’")
/// .with_row(Row::from_cells(["a", "bc"].iter().cloned()));
/// ```
pub fn new(row_spec: &str) -> Self {
Self::new_safe(row_spec)
.unwrap_or_else(|e: super::error::Error| panic!("tabular::Table::new: {}", e))
}
/// Like [`new`], but returns a [`Result`] instead of panicking if parsing `row_spec` fails.
///
/// [`new`]: #method.new
/// [`Result`]: type.Result.html
pub fn new_safe(row_spec: &str) -> Result<Self> {
let (format, n_columns) = parse_row_spec(row_spec)?;
Ok(Table {
n_columns,
format,
rows: vec![],
column_widths: vec![0; n_columns],
line_end: DEFAULT_LINE_END.to_owned(),
})
}
/// The number of columns in the table.
pub fn column_count(&self) -> usize {
// ^^^^^^^^^^^^ What’s a better name for this?
self.n_columns
}
/// Adds a pre-formatted row that spans all columns.
///
/// A heading does not interact with the formatting of rows made of cells.
/// This is like `\intertext` in LaTeX, not like `<head>` or `<th>` in HTML.
///
/// # Examples
///
/// ```
/// # use tabular::*;
/// let mut table = Table::new("{:<} {:>}");
/// table
/// .add_heading("./:")
/// .add_row(Row::new().with_cell("Cargo.lock").with_cell(433))
/// .add_row(Row::new().with_cell("Cargo.toml").with_cell(204))
/// .add_heading("")
/// .add_heading("src/:")
/// .add_row(Row::new().with_cell("lib.rs").with_cell(10257))
/// .add_heading("")
/// .add_heading("target/:")
/// .add_row(Row::new().with_cell("debug/").with_cell(672));
///
/// assert_eq!( format!("{}", table),
/// "./:\n\
/// Cargo.lock 433\n\
/// Cargo.toml 204\n\
/// \n\
/// src/:\n\
/// lib.rs 10257\n\
/// \n\
/// target/:\n\
/// debug/ 672\n\
/// " );
/// ```
///
pub fn add_heading<S: Into<String>>(&mut self, heading: S) -> &mut Self {
self.rows.push(InternalRow::Heading(heading.into()));
self
}
/// Convenience function for calling [`add_heading`].
///
/// [`add_heading`]: #method.add_heading
#[must_use]
pub fn with_heading<S: Into<String>>(mut self, heading: S) -> Self {
self.add_heading(heading);
self
}
/// Adds a row made up of cells.
///
/// When printed, each cell will be padded to the size of its column, which is the maximum of
/// the width of its cells.
///
/// # Panics
///
/// If `self.`[`column_count()`]` != row.`[`len()`].
///
/// [`column_count()`]: #method.column_count
/// [`len()`]: struct.Row.html#method.len
pub fn add_row(&mut self, row: Row) -> &mut Self {
let cells = row.0;
assert_eq!(
cells.len(),
self.n_columns,
"Number of columns in table and row don't match"
);
for (width, s) in self.column_widths.iter_mut().zip(cells.iter()) {
*width = ::std::cmp::max(*width, s.width());
}
self.rows.push(InternalRow::Cells(cells));
self
}
/// Convenience function for calling [`add_row`].
///
/// # Panics
///
/// The same as [`add_row`].
///
/// [`add_row`]: #method.add_row
#[must_use]
pub fn with_row(mut self, row: Row) -> Self {
self.add_row(row);
self
}
/// Sets the string to output at the end of every line.
///
/// By default this is `"\n"` on all platforms, like `println!`.
///
/// # Examples
///
/// ```
/// # use tabular::*;
/// #[cfg(windows)]
/// const DEFAULT_LINE_END: &'static str = "\r\n";
/// #[cfg(not(windows))]
/// const DEFAULT_LINE_END: &'static str = "\n";
///
/// let table = Table::new("{:>} {:<}").set_line_end(DEFAULT_LINE_END)
/// .with_row(Row::new().with_cell("x").with_cell("x"))
/// .with_row(Row::new().with_cell("yy").with_cell("yy"))
/// .with_row(Row::new().with_cell("zzz").with_cell("zzz"));
///
/// assert_eq!( table.to_string(),
/// format!(" x x{nl} yy yy{nl}zzz zzz{nl}", nl = DEFAULT_LINE_END) );
/// ```
///
/// This works better than putting the carriage return in the format string:
///
/// ```
/// # use tabular::*;
/// let table = Table::new("{:>} {:<}\r")
/// .with_row(Row::new().with_cell("x").with_cell("x"))
/// .with_row(Row::new().with_cell("yy").with_cell("yy"))
/// .with_row(Row::new().with_cell("zzz").with_cell("zzz"));
///
/// assert_eq!( table.to_string(),
/// format!(" x x \r\n yy yy \r\nzzz zzz\r\n") );
/// ```
///
/// Note the trailing spaces. Trailing spaces mean that if any lines are wrapped
/// then all lines are wrapped.
#[must_use]
pub fn set_line_end<S: Into<String>>(mut self, line_end: S) -> Self {
self.line_end = line_end.into();
self
}
}
impl Debug for Table {
// This method allocates in two places:
// - row_spec_to_string
// - row.clone()
// It doesn't need to do either.
fn fmt(&self, f: &mut Formatter) -> ::std::fmt::Result {
write!(f, "Table::new({:?})", row_spec_to_string(&self.format))?;
if self.line_end != DEFAULT_LINE_END {
write!(f, ".set_line_end({:?})", self.line_end)?;
}
for row in &self.rows {
match *row {
InternalRow::Cells(ref row) => write!(f, ".with_row({:?})", Row(row.clone()))?,
InternalRow::Heading(ref heading) => write!(f, ".with_heading({:?})", heading)?,
}
}
Ok(())
}
}
impl Display for Table {
fn fmt(&self, f: &mut Formatter) -> ::std::fmt::Result {
use crate::column_spec::{Alignment::*, ColumnSpec::*};
let max_column_width = self.column_widths.iter().cloned().max().unwrap_or(0);
let mut spaces = String::with_capacity(max_column_width);
for _ in 0..max_column_width {
spaces.push(' ');
}
let mt_width_string = WidthString::default();
let is_not_last = |field_index| field_index + 1 < self.format.len();
for row in &self.rows {
match *row {
InternalRow::Cells(ref cells) => {
let mut cw_iter = self.column_widths.iter().cloned();
let mut row_iter = cells.iter();
for field_index in 0..self.format.len() {
match self.format[field_index] {
Align(alignment) => {
let cw = cw_iter.next().unwrap();
let ws = row_iter.next().unwrap_or(&mt_width_string);
let needed = cw - ws.width();
let padding = &spaces[..needed];
match alignment {
Left => {
f.write_str(ws.as_str())?;
if is_not_last(field_index) {
f.write_str(padding)?;
}
}
Center => {
let (before, after) = padding.split_at(needed / 2);
f.write_str(before)?;
f.write_str(ws.as_str())?;
if is_not_last(field_index) {
f.write_str(after)?;
}
}
Right => {
f.write_str(padding)?;
f.write_str(ws.as_str())?;
}
}
}
Literal(ref s) => f.write_str(s)?,
}
}
}
InternalRow::Heading(ref s) => {
f.write_str(s)?;
}
}
f.write_str(&self.line_end)?;
}
Ok(())
}
}