From 27979dd617bfb9af83dc3801eb4372f3a38812a3 Mon Sep 17 00:00:00 2001 From: pierresy Date: Wed, 10 Jun 2015 21:28:23 +0200 Subject: Capability to update row (append, insert, remove cells) --- src/row.rs | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) (limited to 'src/row.rs') diff --git a/src/row.rs b/src/row.rs index 2ccca0b..cbf1e91 100644 --- a/src/row.rs +++ b/src/row.rs @@ -20,8 +20,8 @@ impl Row { } /// Create an row of length `size`, with empty strings stored - pub fn empty(size: usize) -> Row { - return Self::new(vec![Cell::default(); size]); + pub fn empty() -> Row { + return Self::new(vec![Cell::default(); 0]); } /// Get the number of cells in this row @@ -58,12 +58,34 @@ impl Row { /// Set the `cell` in the row at the given `column` pub fn set_cell(&mut self, cell: Cell, column: usize) -> Result<(), &str> { if column >= self.len() { - return Err("Column index is higher than expected"); + return Err("Cannot find cell"); } self.cells[column] = cell; return Ok(()); } + /// Append a `cell` at the end of the row + pub fn add_cell(&mut self, cell: Cell) { + self.cells.push(cell); + } + + /// Insert `cell` at position `index`. If `index` is higher than the row lenght, + /// the cell will be appended at the end + pub fn insert_cell(&mut self, index: usize, cell: Cell) { + if index < self.cells.len() { + self.cells.insert(index, cell); + } else { + self.add_cell(cell); + } + } + + /// Remove the cell at position `index`. Silently skip if this cell does not exist + pub fn remove_cell(&mut self, index: usize) { + if index < self.cells.len() { + self.cells.remove(index); + } + } + /// Print the row to `out`, with `separator` as column separator, and `col_width` /// specifying the width of each columns pub fn print(&self, out: &mut T, separator: char, col_width: &[usize]) -> Result<(), Error> { @@ -82,6 +104,12 @@ impl Row { } } +impl Default for Row { + fn default() -> Row { + return Row::empty(); + } +} + impl FromIterator for Row { fn from_iter(iterator: T) -> Row where T: IntoIterator { return Self::new(iterator.into_iter().map(|ref e| Cell::from(e)).collect()); -- cgit v1.2.3