comfy_table/table.rs
1#[cfg(feature = "tty")]
2use std::sync::OnceLock;
3use std::{
4 fmt,
5 iter::IntoIterator,
6 slice::{Iter, IterMut},
7};
8
9use crate::{
10 cell::Cell,
11 column::Column,
12 inline_table::InlineTable,
13 row::Row,
14 style::{ColumnConstraint, ContentArrangement, TableStyle, presets::ASCII_FULL},
15 utils::build_table,
16};
17
18/// This is the main interface for building a table.
19/// Each table consists of [Rows](Row), which in turn contain [Cells](crate::cell::Cell).
20///
21/// There also exists a representation of a [Column].
22/// Columns are automatically created when adding rows to a table.
23#[derive(Debug, Clone)]
24pub struct Table {
25 pub(crate) columns: Vec<Column>,
26 pub(crate) style: TableStyle,
27 pub(crate) header: Option<Row>,
28 pub(crate) rows: Vec<Row>,
29 pub(crate) inline_tables: Vec<InlineTable>,
30 pub(crate) arrangement: ContentArrangement,
31 pub(crate) delimiter: Option<char>,
32 pub(crate) truncation_indicator: String,
33 #[cfg(feature = "tty")]
34 no_tty: bool,
35 #[cfg(feature = "tty")]
36 is_tty_cache: OnceLock<bool>,
37 #[cfg(feature = "tty")]
38 use_stderr: bool,
39 width: Option<u16>,
40 #[cfg(feature = "tty")]
41 enforce_styling: bool,
42 /// Define whether everything in a cells should be styled, including whitespaces
43 /// or whether only the text should be styled.
44 #[cfg(feature = "tty")]
45 pub(crate) style_text_only: bool,
46}
47
48impl fmt::Display for Table {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 write!(f, "{}", self.lines().collect::<Vec<_>>().join("\n"))
51 }
52}
53
54impl Default for Table {
55 fn default() -> Self {
56 Self::new()
57 }
58}
59
60impl Table {
61 /// Create a new table with default ASCII styling.
62 pub fn new() -> Self {
63 Self {
64 columns: Vec::new(),
65 header: None,
66 rows: Vec::new(),
67 inline_tables: Vec::new(),
68 arrangement: ContentArrangement::Disabled,
69 delimiter: None,
70 truncation_indicator: "…".to_string(),
71 #[cfg(feature = "tty")]
72 no_tty: false,
73 #[cfg(feature = "tty")]
74 is_tty_cache: OnceLock::new(),
75 #[cfg(feature = "tty")]
76 use_stderr: false,
77 width: None,
78 style: ASCII_FULL,
79 #[cfg(feature = "tty")]
80 enforce_styling: false,
81 #[cfg(feature = "tty")]
82 style_text_only: false,
83 }
84 }
85
86 /// This is an alternative `fmt` function, which simply removes any trailing whitespaces.
87 /// Trailing whitespaces often occur, when using tables without a right border.
88 pub fn trim_fmt(&self) -> String {
89 self.lines()
90 .map(|line| line.trim_end().to_string())
91 .collect::<Vec<_>>()
92 .join("\n")
93 }
94
95 /// This is an alternative to `fmt`, but rather returns an iterator to each line, rather than
96 /// one String separated by newlines.
97 pub fn lines(&self) -> impl Iterator<Item = String> {
98 build_table(self)
99 }
100
101 /// Set the header row of the table. This is usually the title of each column.\
102 /// There'll be no header unless you explicitly set it with this function.
103 ///
104 /// ```
105 /// use comfy_table::{Row, Table};
106 ///
107 /// let mut table = Table::new();
108 /// let header = Row::from(vec!["Header One", "Header Two"]);
109 /// table.set_header(header);
110 /// ```
111 pub fn set_header<T: Into<Row>>(&mut self, row: T) -> &mut Self {
112 let row = row.into();
113 self.autogenerate_columns(&row);
114 self.header = Some(row);
115
116 self
117 }
118
119 pub fn header(&self) -> Option<&Row> {
120 self.header.as_ref()
121 }
122
123 /// Returns the number of currently present columns.
124 ///
125 /// ```
126 /// use comfy_table::Table;
127 ///
128 /// let mut table = Table::new();
129 /// table.set_header(vec!["Col 1", "Col 2", "Col 3"]);
130 ///
131 /// assert_eq!(table.column_count(), 3);
132 /// ```
133 pub fn column_count(&mut self) -> usize {
134 self.discover_columns();
135 self.columns.len()
136 }
137
138 /// Add a new row to the table.
139 ///
140 /// ```
141 /// use comfy_table::{Row, Table};
142 ///
143 /// let mut table = Table::new();
144 /// table.add_row(vec!["One", "Two"]);
145 /// ```
146 pub fn add_row<T: Into<Row>>(&mut self, row: T) -> &mut Self {
147 let mut row = row.into();
148 self.autogenerate_columns(&row);
149 row.index = Some(self.rows.len());
150 self.rows.push(row);
151
152 self
153 }
154
155 /// Add a new row to the table if the predicate evaluates to `true`.
156 ///
157 /// ```
158 /// use comfy_table::{Row, Table};
159 ///
160 /// let mut table = Table::new();
161 /// table.add_row_if(|index, row| true, vec!["One", "Two"]);
162 /// ```
163 pub fn add_row_if<P, T>(&mut self, predicate: P, row: T) -> &mut Self
164 where
165 P: Fn(usize, &T) -> bool,
166 T: Into<Row>,
167 {
168 if predicate(self.rows.len(), &row) {
169 return self.add_row(row);
170 }
171
172 self
173 }
174
175 /// Add multiple rows to the table.
176 ///
177 /// ```
178 /// use comfy_table::{Row, Table};
179 ///
180 /// let mut table = Table::new();
181 /// let rows = vec![vec!["One", "Two"], vec!["Three", "Four"]];
182 /// table.add_rows(rows);
183 /// ```
184 pub fn add_rows<I>(&mut self, rows: I) -> &mut Self
185 where
186 I: IntoIterator,
187 I::Item: Into<Row>,
188 {
189 for row in rows.into_iter() {
190 let mut row = row.into();
191 self.autogenerate_columns(&row);
192 row.index = Some(self.rows.len());
193 self.rows.push(row);
194 }
195
196 self
197 }
198
199 /// Add multiple rows to the table if the predicate evaluates to `true`.
200 ///
201 /// ```
202 /// use comfy_table::{Row, Table};
203 ///
204 /// let mut table = Table::new();
205 /// let rows = vec![vec!["One", "Two"], vec!["Three", "Four"]];
206 /// table.add_rows_if(|index, rows| true, rows);
207 /// ```
208 pub fn add_rows_if<P, I>(&mut self, predicate: P, rows: I) -> &mut Self
209 where
210 P: Fn(usize, &I) -> bool,
211 I: IntoIterator,
212 I::Item: Into<Row>,
213 {
214 if predicate(self.rows.len(), &rows) {
215 return self.add_rows(rows);
216 }
217
218 self
219 }
220
221 /// Returns the number of currently present rows.
222 ///
223 /// ```
224 /// use comfy_table::Table;
225 ///
226 /// let mut table = Table::new();
227 /// table.add_row(vec!["One", "Two"]);
228 ///
229 /// assert_eq!(table.row_count(), 1);
230 /// ```
231 pub fn row_count(&self) -> usize {
232 self.rows.len()
233 }
234
235 /// Returns if the table is empty (contains no data rows).
236 ///
237 /// ```
238 /// use comfy_table::Table;
239 ///
240 /// let mut table = Table::new();
241 /// assert!(table.is_empty());
242 ///
243 /// table.add_row(vec!["One", "Two"]);
244 /// assert!(!table.is_empty());
245 /// ```
246 pub fn is_empty(&self) -> bool {
247 self.rows.is_empty()
248 }
249
250 /// Enforce a max width that should be used in combination with [dynamic content
251 /// arrangement](ContentArrangement::Dynamic).\ This is usually not necessary, if you plan
252 /// to output your table to a tty, since the terminal width can be automatically determined.
253 pub fn set_width(&mut self, width: u16) -> &mut Self {
254 self.width = Some(width);
255
256 self
257 }
258
259 /// Get the expected width of the table.
260 ///
261 /// This will be `Some(width)`, if the terminal width can be detected or if the table width is
262 /// set via [set_width](Table::set_width).
263 ///
264 /// If neither is not possible, `None` will be returned.\
265 /// This implies that both the [Dynamic](ContentArrangement::Dynamic) mode and the
266 /// [Percentage](crate::style::Width::Percentage) constraint won't work.
267 #[cfg(feature = "tty")]
268 pub fn width(&self) -> Option<u16> {
269 if let Some(width) = self.width {
270 Some(width)
271 } else if self.is_tty() {
272 if let Ok((width, _)) = crossterm::terminal::size() {
273 Some(width)
274 } else {
275 None
276 }
277 } else {
278 None
279 }
280 }
281
282 #[cfg(not(feature = "tty"))]
283 pub fn width(&self) -> Option<u16> {
284 self.width
285 }
286
287 /// Specify how Comfy Table should arrange the content in your table.
288 ///
289 /// ```
290 /// use comfy_table::{ContentArrangement, Table};
291 ///
292 /// let mut table = Table::new();
293 /// table.set_content_arrangement(ContentArrangement::Dynamic);
294 /// ```
295 pub fn set_content_arrangement(&mut self, arrangement: ContentArrangement) -> &mut Self {
296 self.arrangement = arrangement;
297
298 self
299 }
300
301 /// Get the current content arrangement of the table.
302 pub fn content_arrangement(&self) -> ContentArrangement {
303 self.arrangement.clone()
304 }
305
306 /// Set the delimiter used to split text in all cells.
307 ///
308 /// A custom delimiter on a cell in will overwrite the column's delimiter.\
309 /// Normal text uses spaces (` `) as delimiters. This is necessary to help comfy-table
310 /// understand the concept of _words_.
311 pub fn set_delimiter(&mut self, delimiter: char) -> &mut Self {
312 self.delimiter = Some(delimiter);
313
314 self
315 }
316
317 /// Set the truncation indicator for cells that are too long to be displayed.
318 ///
319 /// Defaults to "…". Set it to "..." for example if you want to stick to ASCII.
320 pub fn set_truncation_indicator(&mut self, indicator: &str) -> &mut Self {
321 self.truncation_indicator = indicator.to_string();
322
323 self
324 }
325
326 /// In case you are sure you don't want export tables to a tty or you experience
327 /// problems with tty specific code, you can enforce a non_tty mode.
328 ///
329 /// This disables:
330 ///
331 /// - width lookup from the current tty
332 /// - Styling and attributes on cells (unless you use [Table::enforce_styling])
333 ///
334 /// If you use the [dynamic content arrangement](ContentArrangement::Dynamic),
335 /// you need to set the width of your desired table manually with [set_width](Table::set_width).
336 #[cfg(feature = "tty")]
337 pub fn force_no_tty(&mut self) -> &mut Self {
338 self.no_tty = true;
339
340 self
341 }
342
343 /// Use this function to check whether `stderr` is a tty.
344 ///
345 /// The default is `stdout`.
346 #[cfg(feature = "tty")]
347 pub fn use_stderr(&mut self) -> &mut Self {
348 self.use_stderr = true;
349
350 self
351 }
352
353 /// Returns whether the table will be handled as if it's printed to a tty.
354 ///
355 /// By default, comfy-table looks at `stdout` and checks whether it's a tty.
356 /// This behavior can be changed via [Table::force_no_tty] and [Table::use_stderr].
357 #[cfg(feature = "tty")]
358 pub fn is_tty(&self) -> bool {
359 use std::io::IsTerminal;
360
361 if self.no_tty {
362 return false;
363 }
364
365 *self.is_tty_cache.get_or_init(|| {
366 if self.use_stderr {
367 std::io::stderr().is_terminal()
368 } else {
369 std::io::stdout().is_terminal()
370 }
371 })
372 }
373
374 /// Enforce terminal styling.
375 ///
376 /// Only useful if you forcefully disabled tty, but still want those fancy terminal styles.
377 ///
378 /// ```
379 /// use comfy_table::Table;
380 ///
381 /// let mut table = Table::new();
382 /// table.force_no_tty().enforce_styling();
383 /// ```
384 #[cfg(feature = "tty")]
385 pub fn enforce_styling(&mut self) -> &mut Self {
386 self.enforce_styling = true;
387
388 self
389 }
390
391 /// Returns whether the content of this table should be styled with the current settings and
392 /// environment.
393 #[cfg(feature = "tty")]
394 pub fn should_style(&self) -> bool {
395 if self.enforce_styling {
396 return true;
397 }
398 self.is_tty()
399 }
400
401 /// By default, the whole content of a cells will be styled.
402 /// Calling this function disables this behavior for all cells, resulting in
403 /// only the text of cells being styled.
404 #[cfg(feature = "tty")]
405 pub fn style_text_only(&mut self) {
406 self.style_text_only = true;
407 }
408
409 /// Convenience method to set a [ColumnConstraint] for all columns at once.
410 /// Constraints are used to influence the way the columns will be arranged.
411 /// Check out their docs for more information.
412 ///
413 /// **Attention:**
414 /// This function should be called after at least one row (or the headers) has been added to the
415 /// table. Before that, the columns won't initialized.
416 ///
417 /// If more constraints are passed than there are columns, any superfluous constraints will be
418 /// ignored.
419 ///
420 /// ```
421 /// use comfy_table::{CellAlignment, ColumnConstraint::*, ContentArrangement, Table, Width::*};
422 ///
423 /// let mut table = Table::new();
424 /// table
425 /// .add_row(&vec!["one", "two", "three"])
426 /// .set_content_arrangement(ContentArrangement::Dynamic)
427 /// .set_constraints(vec![UpperBoundary(Fixed(15)), LowerBoundary(Fixed(20))]);
428 /// ```
429 pub fn set_constraints<T: IntoIterator<Item = ColumnConstraint>>(
430 &mut self,
431 constraints: T,
432 ) -> &mut Self {
433 let mut constraints = constraints.into_iter();
434 for column in self.column_iter_mut() {
435 if let Some(constraint) = constraints.next() {
436 column.set_constraint(constraint);
437 } else {
438 break;
439 }
440 }
441
442 self
443 }
444
445 /// Load a [TableStyle] for this table, replacing the current style. \
446 /// Preset styles can be found in the [presets](crate::style::presets) module.
447 ///
448 /// You can also build your own styles by creating your own [TableStyle].
449 ///
450 /// ```
451 /// use comfy_table::{Table, presets::UTF8_FULL};
452 ///
453 /// let mut table = Table::new();
454 /// table.load_style(UTF8_FULL.with_rounded_corners());
455 /// ```
456 pub fn load_style(&mut self, style: TableStyle) -> &mut Self {
457 self.style = style;
458
459 self
460 }
461
462 /// Returns a copy of the table's current [TableStyle].
463 ///
464 /// ```
465 /// use comfy_table::{Table, presets::UTF8_FULL};
466 ///
467 /// let mut table = Table::new();
468 /// table.load_style(UTF8_FULL);
469 ///
470 /// assert_eq!(UTF8_FULL, table.style())
471 /// ```
472 pub fn style(&self) -> TableStyle {
473 self.style
474 }
475
476 /// Get a mutable handle to the table's [TableStyle] to edit it in place.
477 ///
478 /// ```
479 /// use comfy_table::{Table, presets::UTF8_FULL};
480 ///
481 /// let mut table = Table::new();
482 /// // Load the UTF8_FULL style
483 /// table.load_style(UTF8_FULL);
484 /// // Set all outer corners to round UTF8 corners
485 /// // This is basically the same as TableStyle::with_rounded_corners
486 /// let style = table.style_mut();
487 /// style.top_border.left = Some('╭');
488 /// style.top_border.right = Some('╮');
489 /// style.bottom_border.left = Some('╰');
490 /// style.bottom_border.right = Some('╯');
491 /// ```
492 pub fn style_mut(&mut self) -> &mut TableStyle {
493 &mut self.style
494 }
495
496 /// Get a reference to a specific column.
497 pub fn column(&self, index: usize) -> Option<&Column> {
498 self.columns.get(index)
499 }
500
501 /// Get a mutable reference to a specific column.
502 pub fn column_mut(&mut self, index: usize) -> Option<&mut Column> {
503 self.columns.get_mut(index)
504 }
505
506 /// Iterator over all columns
507 pub fn column_iter(&self) -> Iter<'_, Column> {
508 self.columns.iter()
509 }
510
511 /// Get a mutable iterator over all columns.
512 ///
513 /// ```
514 /// use comfy_table::{ColumnConstraint::*, Table, Width::*};
515 ///
516 /// let mut table = Table::new();
517 /// table.add_row(&vec!["First", "Second", "Third"]);
518 ///
519 /// // Add a ColumnConstraint to each column (left->right)
520 /// // first -> min width of 10
521 /// // second -> max width of 8
522 /// // third -> fixed width of 10
523 /// let constraints = vec![
524 /// LowerBoundary(Fixed(10)),
525 /// UpperBoundary(Fixed(8)),
526 /// Absolute(Fixed(10)),
527 /// ];
528 ///
529 /// // Add the constraints to their respective column
530 /// for (column_index, column) in table.column_iter_mut().enumerate() {
531 /// let constraint = constraints.get(column_index).unwrap();
532 /// column.set_constraint(*constraint);
533 /// }
534 /// ```
535 pub fn column_iter_mut(&mut self) -> IterMut<'_, Column> {
536 self.columns.iter_mut()
537 }
538
539 /// Get a mutable iterator over cells of a column.
540 /// The iterator returns a nested `Option<Option<Cell>>`, since there might be
541 /// rows that are missing this specific Cell.
542 ///
543 /// ```
544 /// use comfy_table::Table;
545 /// let mut table = Table::new();
546 /// table.add_row(&vec!["First", "Second"]);
547 /// table.add_row(&vec!["Third"]);
548 /// table.add_row(&vec!["Fourth", "Fifth"]);
549 ///
550 /// // Create an iterator over the second column
551 /// let mut cell_iter = table.column_cells_iter(1);
552 /// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Second");
553 /// assert!(cell_iter.next().unwrap().is_none());
554 /// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Fifth");
555 /// assert!(cell_iter.next().is_none());
556 /// ```
557 pub fn column_cells_iter(&self, column_index: usize) -> ColumnCellIter<'_> {
558 ColumnCellIter {
559 rows: &self.rows,
560 column_index,
561 row_index: 0,
562 }
563 }
564
565 /// Get a mutable iterator over cells of a column, including the header cell.
566 /// The header cell will be the very first cell returned.
567 /// The iterator returns a nested `Option<Option<Cell>>`, since there might be
568 /// rows that are missing this specific Cell.
569 ///
570 /// ```
571 /// use comfy_table::Table;
572 /// let mut table = Table::new();
573 /// table.set_header(&vec!["A", "B"]);
574 /// table.add_row(&vec!["First", "Second"]);
575 /// table.add_row(&vec!["Third"]);
576 /// table.add_row(&vec!["Fourth", "Fifth"]);
577 ///
578 /// // Create an iterator over the second column
579 /// let mut cell_iter = table.column_cells_with_header_iter(1);
580 /// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "B");
581 /// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Second");
582 /// assert!(cell_iter.next().unwrap().is_none());
583 /// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Fifth");
584 /// assert!(cell_iter.next().is_none());
585 /// ```
586 pub fn column_cells_with_header_iter(
587 &self,
588 column_index: usize,
589 ) -> ColumnCellsWithHeaderIter<'_> {
590 ColumnCellsWithHeaderIter {
591 header_checked: false,
592 header: &self.header,
593 rows: &self.rows,
594 column_index,
595 row_index: 0,
596 }
597 }
598
599 /// Reference to a specific row
600 pub fn row(&self, index: usize) -> Option<&Row> {
601 self.rows.get(index)
602 }
603
604 /// Mutable reference to a specific row
605 pub fn row_mut(&mut self, index: usize) -> Option<&mut Row> {
606 self.rows.get_mut(index)
607 }
608
609 /// Iterator over all rows
610 pub fn row_iter(&self) -> Iter<'_, Row> {
611 self.rows.iter()
612 }
613
614 /// Get a mutable iterator over all rows.
615 ///
616 /// ```
617 /// use comfy_table::Table;
618 /// let mut table = Table::new();
619 /// table.add_row(&vec!["First", "Second", "Third"]);
620 ///
621 /// // Add the constraints to their respective row
622 /// for row in table.row_iter_mut() {
623 /// row.max_height(5);
624 /// }
625 /// assert!(table.row_iter_mut().len() == 1);
626 /// ```
627 pub fn row_iter_mut(&mut self) -> IterMut<'_, Row> {
628 self.rows.iter_mut()
629 }
630
631 /// Return a vector representing the maximum amount of characters in any line of this column.\
632 ///
633 /// **Attention** This scans the whole current content of the table.
634 pub fn column_max_content_widths(&self) -> Vec<u16> {
635 fn set_max_content_widths(max_widths: &mut [u16], row: &Row) {
636 // Get the max width for each cell of the row
637 let row_max_widths = row.max_content_widths();
638 for (index, width) in row_max_widths.iter().enumerate() {
639 let mut width = (*width).try_into().unwrap_or(u16::MAX);
640 // A column's content is at least 1 char wide.
641 width = std::cmp::max(1, width);
642
643 // Set a new max, if the current cell is the longest for that column.
644 let current_max = max_widths[index];
645 if current_max < width {
646 max_widths[index] = width;
647 }
648 }
649 }
650 // The vector that'll contain the max widths per column.
651 let mut max_widths = vec![0; self.columns.len()];
652
653 if let Some(header) = &self.header {
654 set_max_content_widths(&mut max_widths, header);
655 }
656 // Iterate through all rows of the table.
657 for row in self.rows.iter() {
658 set_max_content_widths(&mut max_widths, row);
659 }
660
661 max_widths
662 }
663
664 /// Autogenerate new columns, if a row is added with more cells than existing columns.
665 fn autogenerate_columns(&mut self, row: &Row) {
666 if row.cell_count() > self.columns.len() {
667 for index in self.columns.len()..row.cell_count() {
668 self.columns.push(Column::new(index));
669 }
670 }
671 }
672
673 /// Calling this might be necessary if you add new cells to rows that're already added to the
674 /// table.
675 ///
676 /// If more cells than're currently know to the table are added to that row,
677 /// the table cannot know about these, since new [Column]s are only
678 /// automatically detected when a new row is added.
679 ///
680 /// To make sure everything works as expected, just call this function if you're adding cells
681 /// to rows that're already added to the table.
682 pub fn discover_columns(&mut self) {
683 for row in self.rows.iter() {
684 if row.cell_count() > self.columns.len() {
685 for index in self.columns.len()..row.cell_count() {
686 self.columns.push(Column::new(index));
687 }
688 }
689 }
690 }
691
692 /// Add an inline nested table directly beneath the most recently added row.
693 ///
694 /// If no rows have been added yet, the inline table is rendered before the first row.
695 /// The inline table automatically adopts border styles and horizontal separators from this table.
696 ///
697 /// # Best Practice: Inside-Out Construction
698 ///
699 /// When composing tables with nested inline tables, it is best practice to construct them
700 /// **inside-out** (bottom-up): define and configure the innermost [`InlineTable`] instances first,
701 /// attach them into intermediate tables, and finally assemble the outer [`Table`].
702 ///
703 /// # Example
704 ///
705 /// ```
706 /// use comfy_table::{InlineTable, Table};
707 ///
708 /// // 1. Define the inline table first (inside-out)
709 /// let mut inline = InlineTable::new();
710 /// inline
711 /// .set_header(vec!["Item", "Value"])
712 /// .add_row(vec!["Nested 1", "Alpha"])
713 /// .add_row(vec!["Nested 2", "Beta"]);
714 ///
715 /// // 2. Assemble the outer table
716 /// let mut table = Table::new();
717 /// table
718 /// .set_header(vec!["Section", "Summary"])
719 /// .add_row(vec!["Header Row", "Primary content"])
720 /// .add_inline_table(inline)
721 /// .add_row(vec!["Next Row", "More content"]);
722 /// ```
723 pub fn add_inline_table(&mut self, mut table: InlineTable) -> &mut Self {
724 let index_row_above: Option<usize> = match self.rows.last() {
725 Some(row) => row.index,
726 None => None,
727 };
728 table.set_row_above_index(index_row_above);
729 self.inline_tables.push(table);
730
731 self
732 }
733}
734
735/// An iterator over cells of a specific column.
736/// A dedicated struct is necessary, as data is usually handled by rows and thereby stored in
737/// `Table::rows`. This type is returned by [Table::column_cells_iter].
738pub struct ColumnCellIter<'a> {
739 rows: &'a [Row],
740 column_index: usize,
741 row_index: usize,
742}
743
744impl<'a> Iterator for ColumnCellIter<'a> {
745 type Item = Option<&'a Cell>;
746 fn next(&mut self) -> Option<Option<&'a Cell>> {
747 // Check if there's a next row
748 if let Some(row) = self.rows.get(self.row_index) {
749 self.row_index += 1;
750
751 // Return the cell (if it exists).
752 return Some(row.cells.get(self.column_index));
753 }
754
755 None
756 }
757}
758
759/// An iterator over cells of a specific column.
760/// A dedicated struct is necessary, as data is usually handled by rows and thereby stored in
761/// `Table::rows`. This type is returned by [Table::column_cells_iter].
762pub struct ColumnCellsWithHeaderIter<'a> {
763 header_checked: bool,
764 header: &'a Option<Row>,
765 rows: &'a [Row],
766 column_index: usize,
767 row_index: usize,
768}
769
770impl<'a> Iterator for ColumnCellsWithHeaderIter<'a> {
771 type Item = Option<&'a Cell>;
772 fn next(&mut self) -> Option<Option<&'a Cell>> {
773 // Get the header as the first cell
774 if !self.header_checked {
775 self.header_checked = true;
776
777 return match self.header {
778 Some(header) => {
779 // Return the cell (if it exists).
780 Some(header.cells.get(self.column_index))
781 }
782 None => Some(None),
783 };
784 }
785
786 // Check if there's a next row
787 if let Some(row) = self.rows.get(self.row_index) {
788 self.row_index += 1;
789
790 // Return the cell (if it exists).
791 return Some(row.cells.get(self.column_index));
792 }
793
794 None
795 }
796}
797
798#[cfg(test)]
799mod tests {
800 use super::*;
801
802 #[test]
803 fn test_column_generation() {
804 let mut table = Table::new();
805 table.set_header(vec!["thr", "four", "fivef"]);
806
807 // When adding a new row, columns are automatically generated
808 assert_eq!(table.columns.len(), 3);
809 // The max content width is also correctly set for each column
810 assert_eq!(table.column_max_content_widths(), vec![3, 4, 5]);
811
812 // When adding a new row, the max content width is updated accordingly
813 table.add_row(vec!["four", "fivef", "very long text with 23"]);
814 assert_eq!(table.column_max_content_widths(), vec![4, 5, 22]);
815
816 // Now add a row that has column lines. The max content width shouldn't change
817 table.add_row(vec!["", "", "shorter"]);
818 assert_eq!(table.column_max_content_widths(), vec![4, 5, 22]);
819
820 println!("{table}");
821 }
822}