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
use column_spec::{ColumnSpec, parse_row_spec, row_spec_to_string};
use error::Result;
use row::{InternalRow, Row};

use std::fmt::{Debug, Formatter, Display};

/// 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>,
}

impl Table {
    /// Constructs a new table with the format of each row specified by `row_spec`.
    ///
    /// Unlike `format!` and friends, `row_spec` is processed manually, 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 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]
        })
    }

    /// 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
    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);

        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
    pub fn with_row(mut self, row: Row) -> Self {
        self.add_row(row);
        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))?;

        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 column_spec::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(' ');
        }

        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 in 0 .. self.format.len() {
                        match self.format[field] {
                            Left  => {
                                let cw    = cw_iter.next().unwrap();
                                let width = match row_iter.next() {
                                    Some(ws) => {
                                        f.write_str(ws.as_str())?;
                                        ws.width()
                                    }
                                    None     => 0,
                                };

                                if field + 1 < self.format.len() {
                                    f.write_str(&spaces[.. cw - width])?;
                                }
                            }

                            Right => {
                                let cw = cw_iter.next().unwrap();
                                match row_iter.next() {
                                    Some(ws) => {
                                        f.write_str(&spaces[.. cw - ws.width()])?;
                                        f.write_str(ws.as_str())?;
                                    },
                                    None     => f.write_str(&spaces[.. cw])?,
                                };
                            }

                            Literal(ref s) => f.write_str(s)?,
                        }
                    }
                }

                InternalRow::Heading(ref s) => {
                    f.write_str(s)?;
                }
            }
            f.write_str("\n")?;
        }

        Ok(())
    }
}