use anyhow::{Error, Result, anyhow};
use std::{fs::File, io::Write};
pub trait CSV {
fn headers(&self) -> String;
fn row(&self) -> String;
}
pub fn to_csv_as_string<T: CSV>(entries: &Vec<T>) -> Result<String, Error> {
if entries.is_empty() {
return Err(anyhow!("Entries vec is empty"));
}
let mut csv_string = format!("{},\n", entries[0].headers());
entries.iter().for_each(|entry| {
csv_string = format!("{}{},\n", csv_string, entry.row());
});
Ok(csv_string)
}
pub fn to_csv_as_string_with_encode<T: CSV>(entries: &Vec<T>) -> Result<String, Error> {
if entries.is_empty() {
return Err(anyhow!("Entries vec is empty"));
}
let mut csv_string = format!("{},%0D%0A", entries[0].headers());
entries.iter().for_each(|entry| {
csv_string = format!("{}{},%0D%0A", csv_string, entry.row());
});
Ok(csv_string)
}
pub fn to_csv_as_file<T: CSV>(file_path: &str, entries: &Vec<T>) -> Result<(), Error> {
if entries.is_empty() {
return Err(anyhow!("Entries vec is empty"));
}
let mut csv_string = format!("{},\n", entries[0].headers());
entries.iter().for_each(|entry| {
csv_string = format!("{}{},\n", csv_string, entry.row());
});
let mut file = File::create(file_path).unwrap();
file.write_all(csv_string.as_bytes())?;
Ok(())
}