Struct Row

Source
pub struct Row { /* private fields */ }
Expand description

Represent a table row made of cells

Implementations§

Source§

impl Row

Source

pub fn new(cells: Vec<Cell>) -> Row

Create a new Row backed with cells vector

Examples found in repository?
examples/basic.rs (lines 25-29)
21fn main() {
22    let mut table = Table::new();
23    table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
24    table.add_row(row!["foobar", "bar", "foo"]);
25    table.add_row(Row::new(vec![
26        Cell::new("foobar2"),
27        Cell::new("bar2"),
28        Cell::new("foo2"),
29    ]));
30    table.printstd();
31    println!("Modified : ");
32    table.set_element("new_foo", 2, 1).unwrap();
33    table.printstd();
34
35    // The same table can be built the following way :
36    let _table = table!(
37        ["ABC", "DEFG", "HIJKLMN"],
38        ["foobar", "bar", "foo"],
39        ["foobar2", "bar2", "foo2"]
40    );
41
42    // Or directly print it like this
43    let _table = ptable!(
44        ["ABC", "DEFG", "HIJKLMN"],
45        ["foobar", "bar", "foo"],
46        ["foobar2", "bar2", "foo2"]
47    );
48}
More examples
Hide additional examples
examples/span.rs (lines 23-27)
3fn main() {
4    /*
5        The following code will output
6
7        +---------------+---------------+--------------+
8        |         A table with horizontal span         |
9        +===============+===============+==============+
10        | This is a cell with span of 2 | span of 1    |
11        +---------------+---------------+--------------+
12        | span of 1     | span of 1     | span of 1    |
13        +---------------+---------------+--------------+
14        |    This cell with a span of 3 is centered    |
15        +---------------+---------------+--------------+
16    */
17
18    let mut table: prettytable::Table = table![
19    [H2 -> "This is a cell with span of 2", "span of 1"],
20    ["span of 1", "span of 1", "span of 1"],
21    [H03c -> "This cell with a span of 3 is centered"]
22    ];
23    table.set_titles(Row::new(vec![Cell::new_align(
24        "A table with horizontal span",
25        Alignment::CENTER,
26    )
27    .with_hspan(3)]));
28    table.printstd();
29}
examples/style.rs (lines 13-21)
6fn main() {
7    let _ = table!();
8    let mut table = Table::new();
9    // Add style to a cell
10    table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
11    // Add style to a full row
12    table.add_row(row![FY => "styled", "bar", "foo"]);
13    table.add_row(Row::new(vec![
14        Cell::new("foobar2"),
15        // Create a cell with a red foreground color
16        Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)),
17        // Create a cell with red foreground color, yellow background color, with bold characters
18        Cell::new("foo2").style_spec("FrByb"),
19        // Using the cell! macro
20        cell!(Fr->"red"),
21    ]));
22
23    table.printstd();
24
25    // Print a table with some styles on it :
26    // FrBybl means : Foregound red, Background yellow, bold, left align
27    ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);
28
29    // You can also apply style to full rows :
30    let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
31    // Set a title line, with all text centered in the cell
32    table.set_titles(row![c => "Title 1", "Title 2"]);
33    table.printstd();
34}
Source

pub fn empty() -> Row

Create an row of length size, with empty strings stored

Source

pub fn len(&self) -> usize

Get the number of cells in this row

Source

pub fn is_empty(&self) -> bool

Check if the row is empty (has no cell)

Source

pub fn get_cell(&self, idx: usize) -> Option<&Cell>

Get the cell at index idx

Examples found in repository?
examples/tictactoe.rs (line 45)
11fn main() {
12    let mut table = table![
13        [EMPTY, EMPTY, EMPTY],
14        [EMPTY, EMPTY, EMPTY],
15        [EMPTY, EMPTY, EMPTY]
16    ];
17    let mut height = table.print_tty(false).unwrap();
18    let stdin = io::stdin();
19    let mut stdout = io::stdout();
20    let mut current = CROSS;
21    let mut terminal = term::stdout().unwrap();
22    loop {
23        let mut line = String::new();
24        print!("{} plays > ", current);
25        height += 1;
26        stdout.flush().unwrap();
27        stdin.read_line(&mut line).expect("Cannot read input");
28        let i = match usize::from_str(line.trim()) {
29            Ok(i) => i,
30            _ => {
31                println!("Bad input");
32                height += 1;
33                continue;
34            }
35        };
36        if i < 1 || i > 9 {
37            println!("Bad input, should be between 1 and 9");
38            height += 1;
39            continue;
40        }
41        let x = (i - 1) % 3;
42        let y = (i - 1) / 3;
43        {
44            let row = table.get_mut_row(y).unwrap();
45            if row.get_cell(x).unwrap().to_string() != EMPTY {
46                println!("There's already someone there");
47                height += 1;
48                continue;
49            }
50            row.set_cell(cell!(current), x).unwrap();
51        }
52        for _ in 0..height {
53            terminal.cursor_up().unwrap();
54            terminal.delete_line().unwrap();
55        }
56        height = table.print_tty(false).unwrap();
57        if check(&table) {
58            return;
59        }
60        if current == CROSS {
61            current = ROUND;
62        } else {
63            current = CROSS;
64        }
65    }
66}
67
68fn get(table: &Table, x: usize, y: usize) -> String {
69    match table.get_row(y) {
70        Some(r) => match r.get_cell(x) {
71            Some(c) => c.to_string(),
72            _ => EMPTY.to_string(),
73        },
74        _ => EMPTY.to_string(),
75    }
76}
Source

pub fn get_mut_cell(&mut self, idx: usize) -> Option<&mut Cell>

Get the mutable cell at index idx

Source

pub fn set_cell(&mut self, cell: Cell, idx: usize) -> Result<(), &str>

Set the cell in the row at the given idx index

Examples found in repository?
examples/tictactoe.rs (line 50)
11fn main() {
12    let mut table = table![
13        [EMPTY, EMPTY, EMPTY],
14        [EMPTY, EMPTY, EMPTY],
15        [EMPTY, EMPTY, EMPTY]
16    ];
17    let mut height = table.print_tty(false).unwrap();
18    let stdin = io::stdin();
19    let mut stdout = io::stdout();
20    let mut current = CROSS;
21    let mut terminal = term::stdout().unwrap();
22    loop {
23        let mut line = String::new();
24        print!("{} plays > ", current);
25        height += 1;
26        stdout.flush().unwrap();
27        stdin.read_line(&mut line).expect("Cannot read input");
28        let i = match usize::from_str(line.trim()) {
29            Ok(i) => i,
30            _ => {
31                println!("Bad input");
32                height += 1;
33                continue;
34            }
35        };
36        if i < 1 || i > 9 {
37            println!("Bad input, should be between 1 and 9");
38            height += 1;
39            continue;
40        }
41        let x = (i - 1) % 3;
42        let y = (i - 1) / 3;
43        {
44            let row = table.get_mut_row(y).unwrap();
45            if row.get_cell(x).unwrap().to_string() != EMPTY {
46                println!("There's already someone there");
47                height += 1;
48                continue;
49            }
50            row.set_cell(cell!(current), x).unwrap();
51        }
52        for _ in 0..height {
53            terminal.cursor_up().unwrap();
54            terminal.delete_line().unwrap();
55        }
56        height = table.print_tty(false).unwrap();
57        if check(&table) {
58            return;
59        }
60        if current == CROSS {
61            current = ROUND;
62        } else {
63            current = CROSS;
64        }
65    }
66}
Source

pub fn add_cell(&mut self, cell: Cell)

Append a cell at the end of the row

Source

pub fn insert_cell(&mut self, index: usize, cell: Cell)

Insert cell at position index. If index is higher than the row length, the cell will be appended at the end

Source

pub fn remove_cell(&mut self, index: usize)

Remove the cell at position index. Silently skip if this cell does not exist

Source

pub fn iter(&self) -> Iter<'_, Cell>

Returns an immutable iterator over cells

Source

pub fn iter_mut(&mut self) -> IterMut<'_, Cell>

Returns an mutable iterator over cells

Source

pub fn print_html<T: Write + ?Sized>( &self, out: &mut T, col_num: usize, ) -> Result<(), Error>

Print the row in HTML format to out.

If the row is has fewer columns than col_num, the row is padded with empty cells.

Trait Implementations§

Source§

impl Clone for Row

Source§

fn clone(&self) -> Row

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Row

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Row

Source§

fn default() -> Row

Returns the “default value” for a type. Read more
Source§

impl<S: ToString> Extend<S> for Row

Source§

fn extend<T: IntoIterator<Item = S>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<T, A> From<T> for Row
where A: ToString, T: IntoIterator<Item = A>,

Source§

fn from(it: T) -> Row

Converts to this type from the input type.
Source§

impl<A: ToString> FromIterator<A> for Row

Source§

fn from_iter<T>(iterator: T) -> Row
where T: IntoIterator<Item = A>,

Creates a value from an iterator. Read more
Source§

impl FromIterator<Row> for Table

Source§

fn from_iter<T>(iterator: T) -> Table
where T: IntoIterator<Item = Row>,

Creates a value from an iterator. Read more
Source§

impl Hash for Row

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Index<usize> for Row

Source§

type Output = Cell

The returned type after indexing.
Source§

fn index(&self, idx: usize) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl IndexMut<usize> for Row

Source§

fn index_mut(&mut self, idx: usize) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<'a> IntoIterator for &'a Row

Source§

type Item = &'a Cell

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, Cell>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a mut Row

Source§

type Item = &'a mut Cell

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, Cell>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for Row

Source§

fn eq(&self, other: &Row) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Row

Source§

impl StructuralPartialEq for Row

Auto Trait Implementations§

§

impl Freeze for Row

§

impl RefUnwindSafe for Row

§

impl Send for Row

§

impl Sync for Row

§

impl Unpin for Row

§

impl UnwindSafe for Row

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.