Add option to export JSON, change file handling

No longer serialize into strings, instead use Vec<u8> as it is
what we're writing to the files.

Fixup comments
This commit is contained in:
Steve Pentland authored and David Peter committed 2018-03-20 20:14:14 +01:00
1 parent ce79d81bd2
commit c59110d652
6 files changed
+130 -32

No files matched your search

+29 -10
View File
@@ -1,8 +1,11 @@
mod csv;
mod json;
use self::csv::CsvExporter;
use self::json::JsonExporter;
use std::io::Result;
use std::io::{Result, Write};
use std::fs::File;
use hyperfine::internal::Second;
@@ -51,16 +54,19 @@ impl ExportEntry {
/// The ResultExportType enum is used to denote the desired form
/// of exporter to use for a given file.
#[derive(Clone)]
pub enum ResultExportType {
/// Export to a csv file with the provided name
Csv(String),
/// Export to a JSON file
Json(String),
}
/// A ResultExporter is responsible for writing all results to the
/// appropriate file
trait ResultExporter {
/// Write all entries to the target destination
fn write(&self, values: &Vec<ExportEntry>) -> Result<()>;
fn write(&self, values: &Vec<ExportEntry>) -> Result<Vec<u8>>;
}
/// Create a new ExportManager
@@ -70,23 +76,36 @@ pub fn create_export_manager() -> ExportManager {
}
}
/// The Exporter is the internal implementation of the ExportManager
/// The ExportManager handles the management of multiple file
/// exporters.
pub struct ExportManager {
exporters: Vec<Box<ResultExporter>>,
exporters: Vec<ResultExportType>,
}
impl ExportManager {
pub fn add_exporter(&mut self, for_type: &ResultExportType) {
match for_type {
&ResultExportType::Csv(ref file_name) => self.exporters
.push(Box::from(CsvExporter::new(file_name.clone()))),
};
/// Add an additional exporter to the ExportManager
pub fn add_exporter(&mut self, for_type: ResultExportType) {
self.exporters.push(for_type);
}
/// Write the given results to all Exporters contained within this manager
pub fn write_results(&self, to_write: Vec<ExportEntry>) -> Result<()> {
for exp in &self.exporters {
exp.write(&to_write)?;
let (exporter, filename): (Box<ResultExporter>, &str) = match exp {
&ResultExportType::Csv(ref file) => (Box::from(CsvExporter::new()), file),
&ResultExportType::Json(ref file) => (Box::from(JsonExporter::new()), file),
};
let file_content = exporter.write(&to_write)?;
write_to_file(filename, file_content)?;
}
Ok(())
}
}
/// Write the given content to a file with the specified name
fn write_to_file(filename: &str, content: Vec<u8>) -> Result<()> {
let mut file = File::create(filename)?;
file.write_all(&content)?;
Ok(())
}