Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions prettytable-rs-derive/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/target/
/Cargo.lock

\.vscode/
14 changes: 14 additions & 0 deletions prettytable-rs-derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "prettytable-rs-derive"
version = "0.1.0"
authors = ["Andrea Stevanato <[email protected]>"]
edition = "2018"

[dependencies]
syn = {version = "0.15.42", features = ["full"]}
quote = "0.6.13"
prettytable-rs = { path = "../" }

[lib]
proc-macro = true
name = "prettytable_derive"
29 changes: 29 additions & 0 deletions prettytable-rs-derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemStruct};

#[proc_macro_derive(TableElem)]
pub fn derive_table_elem(input: TokenStream) -> TokenStream {
let parsed_input = parse_macro_input!(input as ItemStruct);

let struct_name = &parsed_input.ident;
let field = &parsed_input.fields;

// Get struct field name
let f_name: Vec<syn::Ident> = field.iter().map(|f| f.ident.clone().unwrap()).collect();
let f_name_str: Vec<String> = f_name.iter().map(|f| f.to_string()).collect();

TokenStream::from(quote! {
impl prettytable::TableElem for #struct_name {
fn get_field_name() -> Vec<&'static str> {
vec![#(#f_name_str),*]
}

fn get_field(&self) -> Vec<String> {
vec![#(self.#f_name.to_string()),*]
}
}
})
}
23 changes: 23 additions & 0 deletions prettytable-rs-derive/tests/derive_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use prettytable_derive::TableElem;
use prettytable::TableElem;

#[derive(TableElem)]
struct NameStruct {
name: String,
surname: String,
}

#[test]
fn test_get_field_name() {
assert_eq!(vec!["name", "surname"], NameStruct::get_field_name());
}

#[test]
fn test_get_field() {
let t = NameStruct {
name: "real_name".to_string(),
surname: "real_surname".to_string(),
};

assert_eq!(vec!["real_name", "real_surname"], t.get_field());
}
72 changes: 72 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,40 @@ impl Table {
pub fn print_html<T: Write + ?Sized>(&self, out: &mut T) -> Result<(), Error> {
self.as_ref().print_html(out)
}

/// Construct the table from the `TableElem` elements vector.
///
/// A struct may implements the `TableElem` trait using the derive proc-macro
/// from `prettytable-rs-derive` crate
pub fn from_vec<T: TableElem>(v: &Vec<T>) -> Self {
// Create the table
let mut table = Self::new();

// Set the table titles with the name of the struct fields
table.set_titles(Row::new(
T::get_field_name()
.iter()
.map(|f| Cell::new(f))
.collect(),
));

v.into_iter().for_each(|r| {
table.add_row(Row::new(
r.get_field().iter().map(|elem| Cell::new(elem)).collect(),
));
});

table
}
}

/// A table may be costructed from a vector of elements that implements the
/// `TableElem` trait
pub trait TableElem {
/// Returns a vector containing the name of the struct fields
fn get_field_name() -> Vec<&'static str>;
/// Returns a vector that contains the contents of the struct's fields
fn get_field(&self) -> Vec<String>;
}

impl Index<usize> for Table {
Expand Down Expand Up @@ -1061,4 +1095,42 @@ mod tests {
assert!(table.print_html(&mut writer).is_ok());
assert_eq!(writer.as_string().replace("\r\n", "\n"), out);
}

#[test]
fn from_vec() {
struct Test {
t1: String,
t2: String,
t3: String,
};

impl crate::TableElem for Test {
fn get_field_name() -> Vec<&'static str> {
vec!["t1", "t2", "t3"]
}

fn get_field(&self) -> Vec<String> {
vec![self.t1.to_string(), self.t2.to_string(), self.t3.to_string()]
}
}

let v = vec![
Test {t1: "a".to_string(), t2: "bc".to_string(), t3: "def".to_string()},
Test {t1: "def".to_string(), t2: "bc".to_string(), t3: "a".to_string()},
];

let table = Table::from_vec(&v);
let out = "\
+-----+----+-----+
| t1 | t2 | t3 |
+=====+====+=====+
| a | bc | def |
+-----+----+-----+
| def | bc | a |
+-----+----+-----+
";

assert_eq!(table.to_string().replace("\r\n", "\n"), out);
assert_eq!(7, table.print(&mut StringWriter::new()).unwrap());
}
}