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
//! A formatted and aligned table printer written in rust
extern crate unicode_width;

use std::io::{stdout, Write, Error};
use std::fmt;
use std::iter::{FromIterator, IntoIterator};

pub mod cell;
pub mod row;
pub mod format;
mod utils;

use row::Row;
use cell::Cell;
use format::{TableFormat, FORMAT_DEFAULT};
use utils::StringWriter;

/// A Struct representing a printable table
#[derive(Clone, Debug)]
pub struct Table {
	format: TableFormat,
	titles: Option<Row>,
	rows: Vec<Row>
}

impl Table {
	/// Create an empty table
	pub fn new() -> Table {
		return Self::init(Vec::new());
	}
	
	/// Create a table initialized with ``rows`
	pub fn init(rows: Vec<Row>) -> Table {
		return Table {
			rows: rows,
			titles: None,
			format: FORMAT_DEFAULT
		};
	}
	
	/// Change separators the table format
	pub fn set_format(&mut self, format: TableFormat) {
		self.format = format;
	}
	
	/// Compute and return the number of column
	pub fn get_column_num(&self) -> usize {
		let mut cnum = 0;
		for r in &self.rows {
			let l = r.len();
			if l > cnum {
				cnum = l;
			}
		}
		return cnum;
	}
	
	/// Get the number of rows
	pub fn len(&self) -> usize {
		return self.rows.len();
	}
	
	/// Set the optional title lines
	pub fn set_titles(&mut self, titles: Row) {
		self.titles = Some(titles);
	}
	
	/// Unset the title line
	pub fn unset_titles(&mut self) {
		self.titles = None;
	}
	
	/// Get a mutable reference to a row
	pub fn get_mut_row(&mut self, row: usize) -> Option<&mut Row> {
		return self.rows.get_mut(row);
	}
	
	/// Get an immutable reference to a row
	pub fn get_row(&self, row: usize) -> Option<&Row> {
		return self.rows.get(row);
	}
	
	/// Append a row in the table, transferring ownership of this row to the table
	/// and returning a mutable reference to the row
	pub fn add_row(&mut self, row: Row) -> &mut Row {
		self.rows.push(row);
		let l = self.rows.len()-1;
		return &mut self.rows[l];
	}
	
	/// Append an empty row in the table. Return a mutable reference to this new row.
	pub fn add_empty_row(&mut self) -> &mut Row {
		return self.add_row(Row::default());	
	}
	
	/// Insert `row` at the position `index`, and return a mutable reference to this row.
	/// If index is higher than current numbers of rows, `row` is appended at the end of the table
	pub fn insert_row(&mut self, index: usize, row: Row) -> &mut Row {
		if index < self.rows.len() {
			self.rows.insert(index, row);
			return &mut self.rows[index];
		} else {
			return self.add_row(row);
		}
	}
	
	/// Modify a single element in the table
	pub fn set_element(&mut self, element: &str, column: usize, row: usize) -> Result<(), &str> {
		let rowline = try!(self.get_mut_row(row).ok_or("Cannot find row"));
		// TODO : If a cell already exist, copy it's alignment parameter
		return rowline.set_cell(Cell::new(element), column);
	}
	
	/// Remove the row at position `index`. Silently skip if the row does not exist
	pub fn remove_row(&mut self, index: usize) {
		if index < self.rows.len() {
			self.rows.remove(index);
		}
	}
	
	/// Get the width of the column at position `col_idx`.
	/// Return 0 if the column does not exists;
	pub fn get_column_width(&self, col_idx: usize) -> usize {
		let mut width = match self.titles {
			Some(ref t) => t.get_cell_width(col_idx),
			None => 0
		};
		for r in &self.rows {
			let l = r.get_cell_width(col_idx);
			if l > width {
				width = l;
			}
		}
		return width;
	}
	
	/// Get the width of all columns, and return a slice 
	/// with the result for each column
	pub fn get_all_column_width(&self) -> Vec<usize> {
		let colnum = self.get_column_num();
		let mut col_width = vec![0usize; colnum];
		for i in 0..colnum {
			col_width[i] = self.get_column_width(i);
		}
		return col_width;
	}
	
	/// Return an iterator over the immutable cells of the column specified by `column`
	pub fn column_iter(&self, column: usize) -> ColumnIter {
		return ColumnIter(self.rows.iter(), column);
	}
	
	/// Return an iterator over the mutable cells of the column specified by `column`
	pub fn column_iter_mut(&mut self, column: usize) -> ColumnIterMut {
		return ColumnIterMut(self.rows.iter_mut(), column);
	}
	
	/// Print the table to `out`
	pub fn print<T: Write>(&self, out: &mut T) -> Result<(), Error> {
		// Compute columns width
		let col_width = self.get_all_column_width();
		try!(self.format.print_line_separator(out, &col_width));
		if let Some(ref t) = self.titles {
			try!(t.print(out, &self.format, &col_width));
			try!(self.format.print_title_separator(out, &col_width));
		}
		// Print rows
		for r in &self.rows {
			try!(r.print(out, &self.format, &col_width));
			try!(self.format.print_line_separator(out, &col_width));
		}
		return out.flush();
	}
	
	/// Print the table to standard output
	/// # Panic
	/// Panic if writing to standard output fails
	pub fn printstd(&self) {
		self.print(&mut stdout())
			.ok()
			.expect("Cannot print table to standard output");
	}
}

impl fmt::Display for Table {
	fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
		let mut writer = StringWriter::new();
		if let Err(_) = self.print(&mut writer) {
			return Err(fmt::Error)
		}
		return fmt.write_str(writer.as_string());
	}
}

impl <B: ToString, A: IntoIterator<Item=B>> FromIterator<A> for Table {
	fn from_iter<T>(iterator: T) -> Table where T: IntoIterator<Item=A> {
		return Self::init(iterator.into_iter().map(|r| Row::from(r)).collect());
	}
}

impl <T, A, B> From<T> for Table where B: ToString, A: IntoIterator<Item=B>, T : IntoIterator<Item=A> {
	fn from(it: T) -> Table {
		return Self::from_iter(it);
	}
}

/// Iterator over immutable cells in a column
pub struct ColumnIter<'a>(std::slice::Iter<'a, Row>, usize);

impl <'a> std::iter::Iterator for ColumnIter<'a> {
	type Item = &'a Cell;
	
	fn next(&mut self) -> Option<&'a Cell> {
		return match self.0.next() {
			None => None,
			Some(row) => row.get_cell(self.1)
		}
	}
}

/// Iterator over mutable cells in a column
pub struct ColumnIterMut<'a>(std::slice::IterMut<'a, Row>, usize);

impl <'a> std::iter::Iterator for ColumnIterMut<'a> {
	type Item = &'a mut Cell;
	
	fn next(&mut self) -> Option<&'a mut Cell> {
		return match self.0.next() {
			None => None,
			Some(row) => row.get_mut_cell(self.1)
		}
	}
}

/// Create a table filled with some values
/// 
/// All the arguments used for elements must implement the `std::string::ToString` trait
/// # Syntax
/// table!([Element1_ row1, Element2_ row1, ...], [Element1_row2, ...], ...);
///
/// # Example
/// ```
/// # #[macro_use] extern crate prettytable;
/// # fn main() {
/// // Create a table initialized with some rows :
/// let tab = table!(["Element1", "Element2", "Element3"],
/// 				 [1, 2, 3],
/// 				 ["A", "B", "C"]
/// 				 );
/// # drop(tab);
/// # }
/// ```
#[macro_export]
macro_rules! table {
	($([$($value:expr), *]), *) => (
		$crate::Table::init(vec![$(row![$($value), *]), *])
	)
}

/// Create a table with `table!` macro, print it to standard output, then return this table for future usage.
/// 
/// The syntax is the same that the one for the `table!` macro
#[macro_export]
macro_rules! ptable {
	($([$($value: expr), *]), *) => (
		{
			let tab = table!($([$($value), *]), *);
			tab.printstd();
			tab
		}
	)
}